blob: 3f8410f0cc7fb4e40e78107219a21f44d2d214ab [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
markchien26299ed2019-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 /**
lucasline252a742019-03-12 13:08:03 +0800430 * Action used to display a dialog that asks the user whether to stay connected to a network
431 * that has not validated. This intent is used to start the dialog in settings via
432 * startActivity.
433 *
434 * @hide
435 */
436 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
437 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
438
439 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800440 * Invalid tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900441 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800442 * @hide
443 */
444 public static final int TETHERING_INVALID = -1;
445
446 /**
447 * Wifi tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900448 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800449 * @hide
450 */
451 @SystemApi
452 public static final int TETHERING_WIFI = 0;
453
454 /**
455 * USB tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900456 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800457 * @hide
458 */
459 @SystemApi
460 public static final int TETHERING_USB = 1;
461
462 /**
463 * Bluetooth tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900464 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800465 * @hide
466 */
467 @SystemApi
468 public static final int TETHERING_BLUETOOTH = 2;
469
470 /**
471 * Extra used for communicating with the TetherService. Includes the type of tethering to
472 * enable if any.
473 * @hide
474 */
475 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
476
477 /**
478 * Extra used for communicating with the TetherService. Includes the type of tethering for
479 * which to cancel provisioning.
480 * @hide
481 */
482 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
483
484 /**
485 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
486 * provisioning.
487 * @hide
488 */
489 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
490
491 /**
492 * Tells the TetherService to run a provision check now.
493 * @hide
494 */
495 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
496
497 /**
498 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
499 * which will receive provisioning results. Can be left empty.
500 * @hide
501 */
502 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
503
504 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800505 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700506 * @hide
507 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100508 @UnsupportedAppUsage
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700509 public static final int TYPE_NONE = -1;
510
511 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900512 * A Mobile 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_MOBILE = 0;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900520
Robert Greenwalt42acef32009-08-12 16:08:25 -0700521 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900522 * A WIFI data connection. Devices may support more than one.
523 *
524 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
525 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
526 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700527 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900528 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700529 public static final int TYPE_WIFI = 1;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900530
Robert Greenwalt42acef32009-08-12 16:08:25 -0700531 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800532 * An MMS-specific Mobile data connection. This network type may use the
533 * same network interface as {@link #TYPE_MOBILE} or it may use a different
534 * one. This is used by applications needing to talk to the carrier's
535 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900536 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900537 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900538 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900539 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700540 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700541 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700542 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900543
Robert Greenwalt42acef32009-08-12 16:08:25 -0700544 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800545 * A SUPL-specific Mobile data connection. This network type may use the
546 * same network interface as {@link #TYPE_MOBILE} or it may use a different
547 * one. This is used by applications needing to talk to the carrier's
548 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900549 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900550 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900551 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900552 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700553 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700554 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700555 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900556
Robert Greenwalt42acef32009-08-12 16:08:25 -0700557 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800558 * A DUN-specific Mobile data connection. This network type may use the
559 * same network interface as {@link #TYPE_MOBILE} or it may use a different
560 * one. This is sometimes by the system when setting up an upstream connection
561 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900562 *
563 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
564 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
565 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700566 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900567 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700568 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900569
Robert Greenwalt42acef32009-08-12 16:08:25 -0700570 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800571 * A High Priority Mobile data connection. This network type uses the
572 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900573 * is different.
574 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900575 * @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.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700578 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700579 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700580 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900581
jsh8214deb2010-03-11 15:04:43 -0800582 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900583 * A WiMAX 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.
jsh8214deb2010-03-11 15:04:43 -0800588 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900589 @Deprecated
jsh8214deb2010-03-11 15:04:43 -0800590 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800591
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800592 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900593 * A Bluetooth data connection.
594 *
595 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
596 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
597 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800598 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900599 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800600 public static final int TYPE_BLUETOOTH = 7;
601
Robert Greenwalt60810842011-04-22 15:28:18 -0700602 /**
603 * Dummy data connection. This should not be used on shipping devices.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900604 * @deprecated This is not used any more.
Robert Greenwalt60810842011-04-22 15:28:18 -0700605 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900606 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800607 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800608
Robert Greenwalt60810842011-04-22 15:28:18 -0700609 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900610 * An Ethernet data connection.
611 *
612 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
613 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
614 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt60810842011-04-22 15:28:18 -0700615 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900616 @Deprecated
Robert Greenwalte12aec92011-01-28 14:48:37 -0800617 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700618
Wink Saville9d7d6282011-03-12 14:52:01 -0800619 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800620 * Over the air Administration.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900621 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800622 * {@hide}
623 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900624 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100625 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800626 public static final int TYPE_MOBILE_FOTA = 10;
627
628 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800629 * IP Multimedia Subsystem.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900630 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800631 * {@hide}
632 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900633 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100634 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800635 public static final int TYPE_MOBILE_IMS = 11;
636
637 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800638 * Carrier Branded Services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900639 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800640 * {@hide}
641 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900642 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100643 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800644 public static final int TYPE_MOBILE_CBS = 12;
645
repo syncaea743a2011-07-29 23:55:49 -0700646 /**
647 * A Wi-Fi p2p connection. Only requesting processes will have access to
648 * the peers connected.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900649 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncaea743a2011-07-29 23:55:49 -0700650 * {@hide}
651 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900652 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100653 @UnsupportedAppUsage
repo syncaea743a2011-07-29 23:55:49 -0700654 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800655
Wink Saville5e56bc52013-07-29 15:00:57 -0700656 /**
657 * The network to use for initially attaching to the network
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900658 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville5e56bc52013-07-29 15:00:57 -0700659 * {@hide}
660 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900661 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100662 @UnsupportedAppUsage
Wink Saville5e56bc52013-07-29 15:00:57 -0700663 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700664
Lorenzo Colittie285b432015-04-23 15:32:42 +0900665 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700666 * Emergency PDN connection for emergency services. This
667 * may include IMS and MMS in emergency situations.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900668 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram3e0e3bc2014-06-26 11:03:44 -0700669 * {@hide}
670 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900671 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100672 @UnsupportedAppUsage
Ram3e0e3bc2014-06-26 11:03:44 -0700673 public static final int TYPE_MOBILE_EMERGENCY = 15;
674
Hui Lu1c5624a2014-01-15 11:05:36 -0500675 /**
676 * The network that uses proxy to achieve connectivity.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900677 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu1c5624a2014-01-15 11:05:36 -0500678 * {@hide}
679 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900680 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100681 @UnsupportedAppUsage
Hui Lu1c5624a2014-01-15 11:05:36 -0500682 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700683
Robert Greenwalt8283f882014-07-07 17:09:01 -0700684 /**
685 * A virtual network using one or more native bearers.
686 * It may or may not be providing security services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900687 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700688 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900689 @Deprecated
Robert Greenwalt8283f882014-07-07 17:09:01 -0700690 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500691
Benedict Wong89ce5e32018-11-14 17:40:55 -0800692 /**
693 * A network that is exclusively meant to be used for testing
694 *
695 * @deprecated Use {@link NetworkCapabilities} instead.
696 * @hide
697 */
698 @Deprecated
699 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700700
701 /** {@hide} */
Benedict Wong89ce5e32018-11-14 17:40:55 -0800702 public static final int MAX_RADIO_TYPE = TYPE_TEST;
703
704 /** {@hide} */
705 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706
Hugo Benichi16f0a942017-06-20 14:07:59 +0900707 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
708
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800709 /**
710 * If you want to set the default network preference,you can directly
711 * change the networkAttributes array in framework's config.xml.
712 *
713 * @deprecated Since we support so many more networks now, the single
714 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800715 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800716 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800717 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800718 * from an App.
719 */
720 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
722
Jeff Sharkey625239a2012-09-26 22:03:49 -0700723 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700724 * @hide
725 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900726 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700727
Paul Jensen5d59e782014-07-11 12:28:19 -0400728 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900729 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
730 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean4d660112018-06-04 16:52:49 +0900731 * registered from those that were already unregistered.
Hugo Benichi31c176d2017-06-17 13:14:12 +0900732 * @hide
733 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900734 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900735 new NetworkRequest.Builder().clearCapabilities().build();
736
737 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400738 * A NetID indicating no Network is selected.
739 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
740 * @hide
741 */
742 public static final int NETID_UNSET = 0;
743
Erik Kline4d092232017-10-30 15:29:44 +0900744 /**
745 * Private DNS Mode values.
746 *
747 * The "private_dns_mode" global setting stores a String value which is
748 * expected to be one of the following.
749 */
750
751 /**
752 * @hide
753 */
754 public static final String PRIVATE_DNS_MODE_OFF = "off";
755 /**
756 * @hide
757 */
758 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
759 /**
760 * @hide
761 */
762 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
763 /**
764 * The default Private DNS mode.
765 *
766 * This may change from release to release or may become dependent upon
767 * the capabilities of the underlying platform.
768 *
769 * @hide
770 */
Erik Kline19841792018-05-16 16:41:57 +0900771 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline4d092232017-10-30 15:29:44 +0900772
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100773 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700774 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500775 /**
776 * A kludge to facilitate static access where a Context pointer isn't available, like in the
777 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
778 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
779 * methods that take a Context argument.
780 */
781 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900783 private final Context mContext;
784
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800785 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800786 private INetworkPolicyManager mNPManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800787
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800788 /**
789 * Tests if a given integer represents a valid network type.
790 * @param networkType the type to be tested
791 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400792 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
793 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800794 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700795 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700796 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900797 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 }
799
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800800 /**
801 * Returns a non-localized string representing a given network type.
802 * ONLY used for debugging output.
803 * @param type the type needing naming
804 * @return a String for the given type, or a string version of the type ("87")
805 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900806 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800807 * {@hide}
808 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900809 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100810 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700811 public static String getNetworkTypeName(int type) {
812 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900813 case TYPE_NONE:
814 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700815 case TYPE_MOBILE:
816 return "MOBILE";
817 case TYPE_WIFI:
818 return "WIFI";
819 case TYPE_MOBILE_MMS:
820 return "MOBILE_MMS";
821 case TYPE_MOBILE_SUPL:
822 return "MOBILE_SUPL";
823 case TYPE_MOBILE_DUN:
824 return "MOBILE_DUN";
825 case TYPE_MOBILE_HIPRI:
826 return "MOBILE_HIPRI";
827 case TYPE_WIMAX:
828 return "WIMAX";
829 case TYPE_BLUETOOTH:
830 return "BLUETOOTH";
831 case TYPE_DUMMY:
832 return "DUMMY";
833 case TYPE_ETHERNET:
834 return "ETHERNET";
835 case TYPE_MOBILE_FOTA:
836 return "MOBILE_FOTA";
837 case TYPE_MOBILE_IMS:
838 return "MOBILE_IMS";
839 case TYPE_MOBILE_CBS:
840 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700841 case TYPE_WIFI_P2P:
842 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700843 case TYPE_MOBILE_IA:
844 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700845 case TYPE_MOBILE_EMERGENCY:
846 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500847 case TYPE_PROXY:
848 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900849 case TYPE_VPN:
850 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700851 default:
852 return Integer.toString(type);
853 }
854 }
855
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800856 /**
857 * Checks if a given type uses the cellular data connection.
858 * This should be replaced in the future by a network property.
859 * @param networkType the type to check
860 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900861 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800862 * {@hide}
863 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900864 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100865 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700866 public static boolean isNetworkTypeMobile(int networkType) {
867 switch (networkType) {
868 case TYPE_MOBILE:
869 case TYPE_MOBILE_MMS:
870 case TYPE_MOBILE_SUPL:
871 case TYPE_MOBILE_DUN:
872 case TYPE_MOBILE_HIPRI:
873 case TYPE_MOBILE_FOTA:
874 case TYPE_MOBILE_IMS:
875 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700876 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700877 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700878 return true;
879 default:
880 return false;
881 }
882 }
883
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800884 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700885 * Checks if the given network type is backed by a Wi-Fi radio.
886 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900887 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700888 * @hide
889 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900890 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700891 public static boolean isNetworkTypeWifi(int networkType) {
892 switch (networkType) {
893 case TYPE_WIFI:
894 case TYPE_WIFI_P2P:
895 return true;
896 default:
897 return false;
898 }
899 }
900
901 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800902 * Specifies the preferred network type. When the device has more
903 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800904 *
905 * @param preference the network type to prefer over all others. It is
906 * unspecified what happens to the old preferred network in the
907 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700908 * @deprecated Functionality has been removed as it no longer makes sense,
909 * with many more than two networks - we'd need an array to express
910 * preference. Instead we use dynamic network properties of
911 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800912 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700913 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
916
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800917 /**
918 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800919 *
920 * @return an integer representing the preferred network type
921 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700922 * @deprecated Functionality has been removed as it no longer makes sense,
923 * with many more than two networks - we'd need an array to express
924 * preference. Instead we use dynamic network properties of
925 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800926 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700927 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600928 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700930 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
932
Scott Main671644c2011-10-06 19:02:28 -0700933 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800934 * Returns details about the currently active default data network. When
935 * connected, this network is the default route for outgoing connections.
936 * You should always check {@link NetworkInfo#isConnected()} before initiating
937 * network traffic. This may return {@code null} when there is no default
938 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900939 * Note that if the default network is a VPN, this method will return the
940 * NetworkInfo for one of its underlying networks instead, or null if the
941 * VPN agent did not specify any. Apps interested in learning about VPNs
942 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800943 *
944 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500945 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800946 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700947 */
junyulai3822c8a2018-12-13 12:47:51 +0800948 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600949 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900950 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 public NetworkInfo getActiveNetworkInfo() {
952 try {
953 return mService.getActiveNetworkInfo();
954 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700955 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 }
957 }
958
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800959 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500960 * Returns a {@link Network} object corresponding to the currently active
961 * default data network. In the event that the current active default data
962 * network disconnects, the returned {@code Network} object will no longer
963 * be usable. This will return {@code null} when there is no default
964 * network.
965 *
966 * @return a {@link Network} object for the current default network or
967 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500968 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600969 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900970 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -0500971 public Network getActiveNetwork() {
972 try {
973 return mService.getActiveNetwork();
974 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700975 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500976 }
977 }
978
979 /**
Robin Leed2baf792016-03-24 12:07:00 +0000980 * Returns a {@link Network} object corresponding to the currently active
981 * default data network for a specific UID. In the event that the default data
982 * network disconnects, the returned {@code Network} object will no longer
983 * be usable. This will return {@code null} when there is no default
984 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +0000985 *
986 * @return a {@link Network} object for the current default network for the
987 * given UID or {@code null} if no default network is currently active
988 *
989 * @hide
990 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600991 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900992 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +0000993 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600994 return getActiveNetworkForUid(uid, false);
995 }
996
997 /** {@hide} */
998 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +0000999 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001000 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001001 } catch (RemoteException e) {
1002 throw e.rethrowFromSystemServer();
1003 }
1004 }
1005
1006 /**
Charles He36738632017-05-15 17:07:18 +01001007 * Checks if a VPN app supports always-on mode.
1008 *
1009 * In order to support the always-on feature, an app has to
1010 * <ul>
1011 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +01001012 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
1013 * meta-data field.
Charles He36738632017-05-15 17:07:18 +01001014 * </ul>
1015 *
1016 * @param userId The identifier of the user for whom the VPN app is installed.
1017 * @param vpnPackage The canonical package name of the VPN app.
1018 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
1019 * @hide
1020 */
1021 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1022 try {
1023 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1024 } catch (RemoteException e) {
1025 throw e.rethrowFromSystemServer();
1026 }
1027 }
1028
1029 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001030 * Configures an always-on VPN connection through a specific application.
1031 * This connection is automatically granted and persisted after a reboot.
1032 *
1033 * <p>The designated package should declare a {@link VpnService} in its
1034 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1035 * otherwise the call will fail.
1036 *
1037 * @param userId The identifier of the user to set an always-on VPN for.
1038 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1039 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001040 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1041 * {@code false} otherwise.
Pavel Grafova462bcb2019-01-25 08:50:06 +00001042 * @param lockdownWhitelist The list of packages that are allowed to access network directly
1043 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
1044 * this method must be called when a package that should be whitelisted is installed or
1045 * uninstalled.
Robin Lee244ce8e2016-01-05 18:03:46 +00001046 * @return {@code true} if the package is set as always-on VPN controller;
1047 * {@code false} otherwise.
1048 * @hide
1049 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001050 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leedc679712016-05-03 13:23:03 +01001051 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001052 boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001053 try {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001054 return mService.setAlwaysOnVpnPackage(
1055 userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
Robin Lee244ce8e2016-01-05 18:03:46 +00001056 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001057 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001058 }
1059 }
1060
Pavel Grafova462bcb2019-01-25 08:50:06 +00001061 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001062 * Returns the package name of the currently set always-on VPN application.
1063 * If there is no always-on VPN set, or the VPN is provided by the system instead
1064 * of by an app, {@code null} will be returned.
1065 *
1066 * @return Package name of VPN controller responsible for always-on VPN,
1067 * or {@code null} if none is set.
1068 * @hide
1069 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001070 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee244ce8e2016-01-05 18:03:46 +00001071 public String getAlwaysOnVpnPackageForUser(int userId) {
1072 try {
1073 return mService.getAlwaysOnVpnPackage(userId);
1074 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001075 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001076 }
1077 }
1078
1079 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001080 * @return whether always-on VPN is in lockdown mode.
1081 *
1082 * @hide
1083 **/
1084 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1085 public boolean isVpnLockdownEnabled(int userId) {
1086 try {
1087 return mService.isVpnLockdownEnabled(userId);
1088 } catch (RemoteException e) {
1089 throw e.rethrowFromSystemServer();
1090 }
1091
1092 }
1093
1094 /**
1095 * @return the list of packages that are allowed to access network when always-on VPN is in
1096 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1097 *
1098 * @hide
1099 **/
1100 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1101 public List<String> getVpnLockdownWhitelist(int userId) {
1102 try {
1103 return mService.getVpnLockdownWhitelist(userId);
1104 } catch (RemoteException e) {
1105 throw e.rethrowFromSystemServer();
1106 }
1107 }
1108
1109 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001110 * Returns details about the currently active default data network
1111 * for a given uid. This is for internal use only to avoid spying
1112 * other apps.
1113 *
1114 * @return a {@link NetworkInfo} object for the current default network
1115 * for the given uid or {@code null} if no default network is
1116 * available for the specified uid.
1117 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001118 * {@hide}
1119 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001120 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001121 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001122 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001123 return getActiveNetworkInfoForUid(uid, false);
1124 }
1125
1126 /** {@hide} */
1127 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001128 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001129 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001130 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001131 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001132 }
1133 }
1134
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001135 /**
1136 * Returns connection status information about a particular
1137 * network type.
1138 *
1139 * @param networkType integer specifying which networkType in
1140 * which you're interested.
1141 * @return a {@link NetworkInfo} object for the requested
1142 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001143 * supported by the device. If {@code networkType} is
1144 * TYPE_VPN and a VPN is active for the calling app,
1145 * then this method will try to return one of the
1146 * underlying networks for the VPN or null if the
1147 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001148 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001149 * @deprecated This method does not support multiple connected networks
1150 * of the same type. Use {@link #getAllNetworks} and
1151 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001152 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001153 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001154 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001155 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 public NetworkInfo getNetworkInfo(int networkType) {
1157 try {
1158 return mService.getNetworkInfo(networkType);
1159 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001160 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 }
1162 }
1163
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001164 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001165 * Returns connection status information about a particular
1166 * Network.
1167 *
1168 * @param network {@link Network} specifying which network
1169 * in which you're interested.
1170 * @return a {@link NetworkInfo} object for the requested
1171 * network or {@code null} if the {@code Network}
1172 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001173 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001174 */
junyulai3822c8a2018-12-13 12:47:51 +08001175 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001176 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001177 @Nullable
1178 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001179 return getNetworkInfoForUid(network, Process.myUid(), false);
1180 }
1181
1182 /** {@hide} */
1183 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001184 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001185 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001186 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001187 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001188 }
1189 }
1190
1191 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001192 * Returns connection status information about all network
1193 * types supported by the device.
1194 *
1195 * @return an array of {@link NetworkInfo} objects. Check each
1196 * {@link NetworkInfo#getType} for which type each applies.
1197 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001198 * @deprecated This method does not support multiple connected networks
1199 * of the same type. Use {@link #getAllNetworks} and
1200 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001201 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001202 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001203 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001204 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 public NetworkInfo[] getAllNetworkInfo() {
1206 try {
1207 return mService.getAllNetworkInfo();
1208 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001209 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211 }
1212
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001213 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001214 * Returns the {@link Network} object currently serving a given type, or
1215 * null if the given type is not connected.
1216 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001217 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001218 * @deprecated This method does not support multiple connected networks
1219 * of the same type. Use {@link #getAllNetworks} and
1220 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001221 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001222 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001223 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001224 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001225 public Network getNetworkForType(int networkType) {
1226 try {
1227 return mService.getNetworkForType(networkType);
1228 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001229 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001230 }
1231 }
1232
1233 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001234 * Returns an array of all {@link Network} currently tracked by the
1235 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001236 *
1237 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001238 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001239 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001240 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001241 public Network[] getAllNetworks() {
1242 try {
1243 return mService.getAllNetworks();
1244 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001245 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001246 }
1247 }
1248
1249 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001250 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001251 * the Networks that applications run by the given user will use by default.
1252 * @hide
1253 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001254 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001255 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1256 try {
1257 return mService.getDefaultNetworkCapabilitiesForUser(userId);
1258 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001259 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001260 }
1261 }
1262
1263 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001264 * Returns the IP information for the current default network.
1265 *
1266 * @return a {@link LinkProperties} object describing the IP info
1267 * for the current default network, or {@code null} if there
1268 * is no current default network.
1269 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001270 * {@hide}
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001271 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1272 * value of {@link #getActiveNetwork()} instead. In particular,
1273 * this method will return non-null LinkProperties even if the
1274 * app is blocked by policy from using this network.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001275 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001276 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001277 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001278 public LinkProperties getActiveLinkProperties() {
1279 try {
1280 return mService.getActiveLinkProperties();
1281 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001282 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001283 }
1284 }
1285
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001286 /**
1287 * Returns the IP information for a given network type.
1288 *
1289 * @param networkType the network type of interest.
1290 * @return a {@link LinkProperties} object describing the IP info
1291 * for the given networkType, or {@code null} if there is
1292 * no current default network.
1293 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001294 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001295 * @deprecated This method does not support multiple connected networks
1296 * of the same type. Use {@link #getAllNetworks},
1297 * {@link #getNetworkInfo(android.net.Network)}, and
1298 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001299 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001300 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001301 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001302 @UnsupportedAppUsage
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001303 public LinkProperties getLinkProperties(int networkType) {
1304 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001305 return mService.getLinkPropertiesForType(networkType);
1306 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001307 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001308 }
1309 }
1310
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001311 /**
1312 * Get the {@link LinkProperties} for the given {@link Network}. This
1313 * will return {@code null} if the network is unknown.
1314 *
1315 * @param network The {@link Network} object identifying the network in question.
1316 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001317 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001318 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001319 @Nullable
1320 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001321 try {
1322 return mService.getLinkProperties(network);
1323 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001324 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001325 }
1326 }
1327
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001328 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001329 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001330 * will return {@code null} if the network is unknown.
1331 *
1332 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001333 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001334 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001335 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001336 @Nullable
1337 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001338 try {
1339 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001340 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001341 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001342 }
1343 }
1344
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001345 /**
Udam Sainib7c24872016-01-04 12:16:14 -08001346 * Gets the URL that should be used for resolving whether a captive portal is present.
1347 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1348 * portal is present.
1349 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1350 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1351 *
1352 * @hide
1353 */
1354 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07001355 @RequiresPermission(android.Manifest.permission.LOCAL_MAC_ADDRESS)
Udam Sainib7c24872016-01-04 12:16:14 -08001356 public String getCaptivePortalServerUrl() {
1357 try {
1358 return mService.getCaptivePortalServerUrl();
1359 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001360 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001361 }
1362 }
1363
1364 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 * Tells the underlying networking system that the caller wants to
1366 * begin using the named feature. The interpretation of {@code feature}
1367 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001368 *
1369 * <p>This method requires the caller to hold either the
1370 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1371 * or the ability to modify system settings as determined by
1372 * {@link android.provider.Settings.System#canWrite}.</p>
1373 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 * @param networkType specifies which network the request pertains to
1375 * @param feature the name of the feature to be used
1376 * @return an integer value representing the outcome of the request.
1377 * The interpretation of this value is specific to each networking
1378 * implementation+feature combination, except that the value {@code -1}
1379 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001380 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001381 * @deprecated Deprecated in favor of the cleaner
1382 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001383 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001384 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001385 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001387 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001389 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001390 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1391 if (netCap == null) {
1392 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1393 feature);
1394 return PhoneConstants.APN_REQUEST_FAILED;
1395 }
1396
1397 NetworkRequest request = null;
1398 synchronized (sLegacyRequests) {
1399 LegacyRequest l = sLegacyRequests.get(netCap);
1400 if (l != null) {
1401 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1402 renewRequestLocked(l);
1403 if (l.currentNetwork != null) {
1404 return PhoneConstants.APN_ALREADY_ACTIVE;
1405 } else {
1406 return PhoneConstants.APN_REQUEST_STARTED;
1407 }
1408 }
1409
1410 request = requestNetworkForFeatureLocked(netCap);
1411 }
1412 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001413 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001414 return PhoneConstants.APN_REQUEST_STARTED;
1415 } else {
1416 Log.d(TAG, " request Failed");
1417 return PhoneConstants.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419 }
1420
1421 /**
1422 * Tells the underlying networking system that the caller is finished
1423 * using the named feature. The interpretation of {@code feature}
1424 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001425 *
1426 * <p>This method requires the caller to hold either the
1427 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1428 * or the ability to modify system settings as determined by
1429 * {@link android.provider.Settings.System#canWrite}.</p>
1430 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 * @param networkType specifies which network the request pertains to
1432 * @param feature the name of the feature that is no longer needed
1433 * @return an integer value representing the outcome of the request.
1434 * The interpretation of this value is specific to each networking
1435 * implementation+feature combination, except that the value {@code -1}
1436 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001437 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001438 * @deprecated Deprecated in favor of the cleaner
1439 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001440 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001441 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001442 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001444 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001446 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001447 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1448 if (netCap == null) {
1449 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1450 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 return -1;
1452 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001453
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001454 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001455 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001456 }
1457 return 1;
1458 }
1459
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001460 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001461 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1462 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001463 switch (feature) {
1464 case "enableCBS":
1465 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1466 case "enableDUN":
1467 case "enableDUNAlways":
1468 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1469 case "enableFOTA":
1470 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1471 case "enableHIPRI":
1472 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1473 case "enableIMS":
1474 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1475 case "enableMMS":
1476 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1477 case "enableSUPL":
1478 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1479 default:
1480 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001481 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001482 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1483 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001484 }
1485 return null;
1486 }
1487
Robert Greenwalt06314e42014-10-29 14:04:06 -07001488 /**
1489 * Guess what the network request was trying to say so that the resulting
1490 * network is accessible via the legacy (deprecated) API such as
1491 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001492 *
1493 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001494 * capability but ignore things such as networkSpecifier.
1495 * If the request has more than one transport or capability it doesn't
1496 * match the old legacy requests (they selected only single transport/capability)
1497 * so this function cannot map the request to a single legacy type and
1498 * the resulting network will not be available to the legacy APIs.
1499 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001500 * This code is only called from the requestNetwork API (L and above).
1501 *
1502 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1503 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1504 * do this for SUPL requests, which are the only ones that we know need it. If
1505 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1506 * compatibility we can send them:
1507 *
1508 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1509 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1510 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001511 * TODO - This should be removed when the legacy APIs are removed.
1512 */
Ye Wenb87875e2014-07-21 14:19:01 -07001513 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1514 if (netCap == null) {
1515 return TYPE_NONE;
1516 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001517
Ye Wenb87875e2014-07-21 14:19:01 -07001518 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1519 return TYPE_NONE;
1520 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001521
Lifu Tang30f95a72016-01-07 23:20:38 -08001522 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001523 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1524 // NOTE: if this causes app breakage, we should not just comment out this early return;
1525 // instead, we should make this early return conditional on the requesting app's target
1526 // SDK version, as described in the comment above.
1527 return TYPE_NONE;
1528 }
1529
Robert Greenwalt06314e42014-10-29 14:04:06 -07001530 String type = null;
1531 int result = TYPE_NONE;
1532
Ye Wenb87875e2014-07-21 14:19:01 -07001533 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001534 type = "enableCBS";
1535 result = TYPE_MOBILE_CBS;
1536 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1537 type = "enableIMS";
1538 result = TYPE_MOBILE_IMS;
1539 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1540 type = "enableFOTA";
1541 result = TYPE_MOBILE_FOTA;
1542 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1543 type = "enableDUN";
1544 result = TYPE_MOBILE_DUN;
1545 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001546 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001547 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001548 // back out this hack for mms as they no longer need this and it's causing
1549 // device slowdowns - b/23350688 (note, supl still needs this)
1550 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1551 // type = "enableMMS";
1552 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001553 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1554 type = "enableHIPRI";
1555 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001556 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001557 if (type != null) {
1558 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1559 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1560 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001561 }
1562 }
1563 return TYPE_NONE;
1564 }
1565
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001566 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001567 if (netCap == null) return TYPE_NONE;
1568 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1569 return TYPE_MOBILE_CBS;
1570 }
1571 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1572 return TYPE_MOBILE_IMS;
1573 }
1574 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1575 return TYPE_MOBILE_FOTA;
1576 }
1577 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1578 return TYPE_MOBILE_DUN;
1579 }
1580 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1581 return TYPE_MOBILE_SUPL;
1582 }
1583 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1584 return TYPE_MOBILE_MMS;
1585 }
1586 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1587 return TYPE_MOBILE_HIPRI;
1588 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001589 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1590 return TYPE_WIFI_P2P;
1591 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001592 return TYPE_NONE;
1593 }
1594
1595 private static class LegacyRequest {
1596 NetworkCapabilities networkCapabilities;
1597 NetworkRequest networkRequest;
1598 int expireSequenceNumber;
1599 Network currentNetwork;
1600 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001601
1602 private void clearDnsBinding() {
1603 if (currentNetwork != null) {
1604 currentNetwork = null;
1605 setProcessDefaultNetworkForHostResolution(null);
1606 }
1607 }
1608
Robert Greenwalt6078b502014-06-11 16:05:07 -07001609 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001610 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001611 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001612 currentNetwork = network;
1613 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001614 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001615 }
1616 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001617 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001618 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001619 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1620 }
1621 };
1622 }
1623
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001624 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001625 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1626 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001627
1628 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1629 synchronized (sLegacyRequests) {
1630 LegacyRequest l = sLegacyRequests.get(netCap);
1631 if (l != null) return l.networkRequest;
1632 }
1633 return null;
1634 }
1635
1636 private void renewRequestLocked(LegacyRequest l) {
1637 l.expireSequenceNumber++;
1638 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1639 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1640 }
1641
1642 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1643 int ourSeqNum = -1;
1644 synchronized (sLegacyRequests) {
1645 LegacyRequest l = sLegacyRequests.get(netCap);
1646 if (l == null) return;
1647 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001648 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001649 }
1650 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1651 }
1652
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001653 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001654 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1655 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001656 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001657 try {
1658 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001659 } catch (RemoteException e) {
1660 throw e.rethrowFromSystemServer();
1661 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001662 LegacyRequest l = new LegacyRequest();
1663 l.networkCapabilities = netCap;
1664 l.delay = delay;
1665 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001666 l.networkRequest = sendRequestForNetwork(
1667 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001668 if (l.networkRequest == null) return null;
1669 sLegacyRequests.put(netCap, l);
1670 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1671 return l.networkRequest;
1672 }
1673
1674 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1675 if (delay >= 0) {
1676 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001677 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001678 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1679 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001680 }
1681 }
1682
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001683 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001684 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1685 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001686 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001687 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001688 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001689 if (l == null) return false;
1690 unregisterNetworkCallback(l.networkCallback);
1691 l.clearDnsBinding();
1692 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694
Erik Kline35bf06c2017-01-26 18:08:28 +09001695 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1696 static {
1697 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1698 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1699 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1700 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1701 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1702 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1703 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1704 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1705 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1706 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1707 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1708 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1709 }
1710
1711 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1712 static {
1713 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1714 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1715 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1716 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1717 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1718 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1719 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1720 }
1721
1722 /**
1723 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1724 * instance suitable for registering a request or callback. Throws an
1725 * IllegalArgumentException if no mapping from the legacy type to
1726 * NetworkCapabilities is known.
1727 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001728 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1729 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001730 * @hide
1731 */
1732 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1733 final NetworkCapabilities nc = new NetworkCapabilities();
1734
1735 // Map from type to transports.
1736 final int NOT_FOUND = -1;
1737 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001738 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001739 nc.addTransportType(transport);
1740
1741 // Map from type to capabilities.
1742 nc.addCapability(sLegacyTypeToCapability.get(
1743 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1744 nc.maybeMarkCapabilitiesRestricted();
1745 return nc;
1746 }
1747
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001748 /** @hide */
1749 public static class PacketKeepaliveCallback {
1750 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001751 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001752 public void onStarted() {}
1753 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001754 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001755 public void onStopped() {}
1756 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001757 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001758 public void onError(int error) {}
1759 }
1760
1761 /**
1762 * Allows applications to request that the system periodically send specific packets on their
1763 * behalf, using hardware offload to save battery power.
1764 *
1765 * To request that the system send keepalives, call one of the methods that return a
1766 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1767 * passing in a non-null callback. If the callback is successfully started, the callback's
1768 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1769 * specifying one of the {@code ERROR_*} constants in this class.
1770 *
Chalard Jean4d660112018-06-04 16:52:49 +09001771 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1772 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1773 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001774 *
junyulai48eac1d42018-12-27 17:25:29 +08001775 * @deprecated Use {@link SocketKeepalive} instead.
1776 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001777 * @hide
1778 */
1779 public class PacketKeepalive {
1780
1781 private static final String TAG = "PacketKeepalive";
1782
1783 /** @hide */
1784 public static final int SUCCESS = 0;
1785
1786 /** @hide */
1787 public static final int NO_KEEPALIVE = -1;
1788
1789 /** @hide */
1790 public static final int BINDER_DIED = -10;
1791
1792 /** The specified {@code Network} is not connected. */
1793 public static final int ERROR_INVALID_NETWORK = -20;
1794 /** The specified IP addresses are invalid. For example, the specified source IP address is
1795 * not configured on the specified {@code Network}. */
1796 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1797 /** The requested port is invalid. */
1798 public static final int ERROR_INVALID_PORT = -22;
1799 /** The packet length is invalid (e.g., too long). */
1800 public static final int ERROR_INVALID_LENGTH = -23;
1801 /** The packet transmission interval is invalid (e.g., too short). */
1802 public static final int ERROR_INVALID_INTERVAL = -24;
1803
1804 /** The hardware does not support this request. */
1805 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001806 /** The hardware returned an error. */
1807 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001808
Nathan Harold63dd8132018-02-14 13:09:45 -08001809 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001810 public static final int NATT_PORT = 4500;
1811
Nathan Harold63dd8132018-02-14 13:09:45 -08001812 /** The minimum interval in seconds between keepalive packet transmissions */
1813 public static final int MIN_INTERVAL = 10;
1814
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001815 private final Network mNetwork;
1816 private final PacketKeepaliveCallback mCallback;
1817 private final Looper mLooper;
1818 private final Messenger mMessenger;
1819
1820 private volatile Integer mSlot;
1821
1822 void stopLooper() {
1823 mLooper.quit();
1824 }
1825
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001826 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001827 public void stop() {
1828 try {
1829 mService.stopKeepalive(mNetwork, mSlot);
1830 } catch (RemoteException e) {
1831 Log.e(TAG, "Error stopping packet keepalive: ", e);
1832 stopLooper();
1833 }
1834 }
1835
1836 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001837 Preconditions.checkNotNull(network, "network cannot be null");
1838 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001839 mNetwork = network;
1840 mCallback = callback;
1841 HandlerThread thread = new HandlerThread(TAG);
1842 thread.start();
1843 mLooper = thread.getLooper();
1844 mMessenger = new Messenger(new Handler(mLooper) {
1845 @Override
1846 public void handleMessage(Message message) {
1847 switch (message.what) {
junyulai06835112019-01-03 18:50:15 +08001848 case NetworkAgent.EVENT_SOCKET_KEEPALIVE:
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001849 int error = message.arg2;
1850 try {
1851 if (error == SUCCESS) {
1852 if (mSlot == null) {
1853 mSlot = message.arg1;
1854 mCallback.onStarted();
1855 } else {
1856 mSlot = null;
1857 stopLooper();
1858 mCallback.onStopped();
1859 }
1860 } else {
1861 stopLooper();
1862 mCallback.onError(error);
1863 }
1864 } catch (Exception e) {
1865 Log.e(TAG, "Exception in keepalive callback(" + error + ")", e);
1866 }
1867 break;
1868 default:
1869 Log.e(TAG, "Unhandled message " + Integer.toHexString(message.what));
1870 break;
1871 }
1872 }
1873 });
1874 }
1875 }
1876
1877 /**
1878 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1879 *
junyulai48eac1d42018-12-27 17:25:29 +08001880 * @deprecated Use {@link #createSocketKeepalive} instead.
1881 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001882 * @hide
1883 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001884 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001885 public PacketKeepalive startNattKeepalive(
1886 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1887 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1888 final PacketKeepalive k = new PacketKeepalive(network, callback);
1889 try {
1890 mService.startNattKeepalive(network, intervalSeconds, k.mMessenger, new Binder(),
1891 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1892 } catch (RemoteException e) {
1893 Log.e(TAG, "Error starting packet keepalive: ", e);
1894 k.stopLooper();
1895 return null;
1896 }
1897 return k;
1898 }
1899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 /**
junyulai48eac1d42018-12-27 17:25:29 +08001901 * Request that keepalives be started on a IPsec NAT-T socket.
1902 *
1903 * @param network The {@link Network} the socket is on.
1904 * @param socket The socket that needs to be kept alive.
1905 * @param source The source address of the {@link UdpEncapsulationSocket}.
1906 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1907 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1908 * must run callback sequentially, otherwise the order of callbacks cannot be
1909 * guaranteed.
1910 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1911 * changes. Must be extended by applications that use this API.
1912 *
junyulai352dc2f2019-01-08 20:04:33 +08001913 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1914 * given socket.
junyulai48eac1d42018-12-27 17:25:29 +08001915 **/
1916 public SocketKeepalive createSocketKeepalive(@NonNull Network network,
1917 @NonNull UdpEncapsulationSocket socket,
1918 @NonNull InetAddress source,
1919 @NonNull InetAddress destination,
1920 @NonNull @CallbackExecutor Executor executor,
1921 @NonNull Callback callback) {
junyulai215b8772019-01-15 11:32:44 +08001922 return new NattSocketKeepalive(mService, network, socket.getFileDescriptor(),
1923 socket.getResourceId(), source, destination, executor, callback);
1924 }
1925
1926 /**
1927 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1928 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1929 *
1930 * @param network The {@link Network} the socket is on.
1931 * @param fd The {@link FileDescriptor} that needs to be kept alive. The provided
1932 * {@link FileDescriptor} must be bound to a port and the keepalives will be sent from
1933 * that port.
1934 * @param source The source address of the {@link UdpEncapsulationSocket}.
1935 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1936 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1937 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1938 * must run callback sequentially, otherwise the order of callbacks cannot be
1939 * guaranteed.
1940 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1941 * changes. Must be extended by applications that use this API.
1942 *
junyulai352dc2f2019-01-08 20:04:33 +08001943 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1944 * given socket.
junyulai215b8772019-01-15 11:32:44 +08001945 * @hide
1946 */
1947 @SystemApi
1948 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
1949 public SocketKeepalive createNattKeepalive(@NonNull Network network,
1950 @NonNull FileDescriptor fd,
1951 @NonNull InetAddress source,
1952 @NonNull InetAddress destination,
1953 @NonNull @CallbackExecutor Executor executor,
1954 @NonNull Callback callback) {
1955 return new NattSocketKeepalive(mService, network, fd, INVALID_RESOURCE_ID /* Unused */,
1956 source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08001957 }
1958
1959 /**
junyulai352dc2f2019-01-08 20:04:33 +08001960 * Request that keepalives be started on a TCP socket.
1961 * The socket must be established.
1962 *
1963 * @param network The {@link Network} the socket is on.
1964 * @param socket The socket that needs to be kept alive.
1965 * @param executor The executor on which callback will be invoked. This implementation assumes
1966 * the provided {@link Executor} runs the callbacks in sequence with no
1967 * concurrency. Failing this, no guarantee of correctness can be made. It is
1968 * the responsibility of the caller to ensure the executor provides this
1969 * guarantee. A simple way of creating such an executor is with the standard
1970 * tool {@code Executors.newSingleThreadExecutor}.
1971 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1972 * changes. Must be extended by applications that use this API.
1973 *
1974 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1975 * given socket.
1976 * @hide
1977 */
1978 @SystemApi
1979 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
1980 public SocketKeepalive createSocketKeepalive(@NonNull Network network,
1981 @NonNull Socket socket,
1982 @NonNull Executor executor,
1983 @NonNull Callback callback) {
1984 return new TcpSocketKeepalive(mService, network, socket, executor, callback);
1985 }
1986
1987 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 * Ensure that a network route exists to deliver traffic to the specified
1989 * host via the specified network interface. An attempt to add a route that
1990 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001991 *
1992 * <p>This method requires the caller to hold either the
1993 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1994 * or the ability to modify system settings as determined by
1995 * {@link android.provider.Settings.System#canWrite}.</p>
1996 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 * @param networkType the type of the network over which traffic to the specified
1998 * host is to be routed
1999 * @param hostAddress the IP address of the host to which the route is desired
2000 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002001 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002002 * @deprecated Deprecated in favor of the
2003 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2004 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07002005 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002006 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09002007 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002009 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002011 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002012 }
2013
2014 /**
2015 * Ensure that a network route exists to deliver traffic to the specified
2016 * host via the specified network interface. An attempt to add a route that
2017 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002018 *
2019 * <p>This method requires the caller to hold either the
2020 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2021 * or the ability to modify system settings as determined by
2022 * {@link android.provider.Settings.System#canWrite}.</p>
2023 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002024 * @param networkType the type of the network over which traffic to the specified
2025 * host is to be routed
2026 * @param hostAddress the IP address of the host to which the route is desired
2027 * @return {@code true} on success, {@code false} on failure
2028 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002029 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002030 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002031 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002032 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002033 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002034 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002035 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002037 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002039 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
2041 }
2042
2043 /**
2044 * Returns the value of the setting for background data usage. If false,
2045 * applications should not use the network if the application is not in the
2046 * foreground. Developers should respect this setting, and check the value
2047 * of this before performing any background data operations.
2048 * <p>
2049 * All applications that have background services that use the network
2050 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002051 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002052 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002053 * background data depends on several combined factors, and this method will
2054 * always return {@code true}. Instead, when background data is unavailable,
2055 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002056 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 * @return Whether background data usage is allowed.
2058 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002059 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002061 // assume that background data is allowed; final authority is
2062 // NetworkInfo which may be blocked.
2063 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
2065
2066 /**
2067 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002068 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 * @param allowBackgroundData Whether an application should use data while
2070 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002071 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2073 * @see #getBackgroundDataSetting()
2074 * @hide
2075 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002076 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002077 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002079 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002081
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002082 /** {@hide} */
2083 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002084 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002085 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2086 try {
2087 return mService.getActiveNetworkQuotaInfo();
2088 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002089 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002090 }
2091 }
2092
2093 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002094 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002095 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002096 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002097 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002098 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002099 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002100 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
2101 if (b != null) {
2102 try {
2103 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08002104 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08002105 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
Malcolm Chenb455e722017-11-28 15:57:14 -08002106 boolean retVal = it.isUserDataEnabled(subId);
Wink Saville36ffb042014-12-05 11:10:30 -08002107 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2108 + " retVal=" + retVal);
2109 return retVal;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002110 } catch (RemoteException e) {
2111 throw e.rethrowFromSystemServer();
2112 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002113 }
Wink Saville36ffb042014-12-05 11:10:30 -08002114 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002115 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002116 }
2117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002119 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002120 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002121 */
2122 public interface OnNetworkActiveListener {
2123 /**
2124 * Called on the main thread of the process to report that the current data network
2125 * has become active, and it is now a good time to perform any pending network
2126 * operations. Note that this listener only tells you when the network becomes
2127 * active; if at any other time you want to know whether it is active (and thus okay
2128 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002129 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002130 */
Chalard Jean4d660112018-06-04 16:52:49 +09002131 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002132 }
2133
2134 private INetworkManagementService getNetworkManagementService() {
2135 synchronized (this) {
2136 if (mNMService != null) {
2137 return mNMService;
2138 }
2139 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2140 mNMService = INetworkManagementService.Stub.asInterface(b);
2141 return mNMService;
2142 }
2143 }
2144
2145 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002146 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002147
2148 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002149 * Start listening to reports when the system's default data network is active, meaning it is
2150 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2151 * to determine the current state of the system's default network after registering the
2152 * listener.
2153 * <p>
2154 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002155 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002156 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002157 *
2158 * @param l The listener to be told when the network is active.
2159 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002160 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002161 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2162 @Override
2163 public void onNetworkActive() throws RemoteException {
2164 l.onNetworkActive();
2165 }
2166 };
2167
2168 try {
2169 getNetworkManagementService().registerNetworkActivityListener(rl);
2170 mNetworkActivityListeners.put(l, rl);
2171 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002172 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002173 }
2174 }
2175
2176 /**
2177 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002178 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002179 *
2180 * @param l Previously registered listener.
2181 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002182 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002183 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002184 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002185 try {
2186 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2187 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002188 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002189 }
2190 }
2191
2192 /**
2193 * Return whether the data network is currently active. An active network means that
2194 * it is currently in a high power state for performing data transmission. On some
2195 * types of networks, it may be expensive to move and stay in such a state, so it is
2196 * more power efficient to batch network traffic together when the radio is already in
2197 * this state. This method tells you whether right now is currently a good time to
2198 * initiate network traffic, as the network is already active.
2199 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002200 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002201 try {
2202 return getNetworkManagementService().isNetworkActive();
2203 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002204 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002205 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002206 }
2207
2208 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 * {@hide}
2210 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002211 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002212 mContext = Preconditions.checkNotNull(context, "missing context");
2213 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05002214 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002216
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002217 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002218 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002219 public static ConnectivityManager from(Context context) {
2220 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2221 }
2222
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002223 /** @hide */
2224 public NetworkRequest getDefaultRequest() {
2225 try {
2226 // This is not racy as the default request is final in ConnectivityService.
2227 return mService.getDefaultRequest();
2228 } catch (RemoteException e) {
2229 throw e.rethrowFromSystemServer();
2230 }
2231 }
2232
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002233 /* TODO: These permissions checks don't belong in client-side code. Move them to
2234 * services.jar, possibly in com.android.server.net. */
2235
2236 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002237 public static final void enforceChangePermission(Context context) {
2238 int uid = Binder.getCallingUid();
2239 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2240 .getPackageNameForUid(context, uid), true /* throwException */);
2241 }
2242
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002243 /** {@hide} */
2244 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002245 Preconditions.checkNotNull(context, "Context cannot be null");
2246 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002247
Robert Greenwaltedb47662014-09-16 17:54:19 -07002248 if (context.getResources().getStringArray(
2249 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2250 // Have a provisioning app - must only let system apps (which check this app)
2251 // turn on tethering
2252 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002253 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002254 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002255 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002256 // If callingPkg's uid is not same as Binder.getCallingUid(),
2257 // AppOpsService throws SecurityException.
2258 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2259 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002260 }
2261 }
2262
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002263 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002264 * @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
Paul Jensen72db88e2015-03-10 10:54:12 -04002269 static ConnectivityManager getInstanceOrNull() {
2270 return sInstance;
2271 }
2272
2273 /**
2274 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2275 * situations where a Context pointer is unavailable.
2276 * @hide
2277 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002278 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002279 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002280 private static ConnectivityManager getInstance() {
2281 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002282 throw new IllegalStateException("No ConnectivityManager yet constructed");
2283 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002284 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002285 }
2286
2287 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002288 * Get the set of tetherable, available interfaces. This list is limited by
2289 * device configuration and current interface existence.
2290 *
2291 * @return an array of 0 or more Strings of tetherable interface names.
2292 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002293 * {@hide}
2294 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002295 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002296 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002297 public String[] getTetherableIfaces() {
2298 try {
2299 return mService.getTetherableIfaces();
2300 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002301 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002302 }
2303 }
2304
2305 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002306 * Get the set of tethered interfaces.
2307 *
2308 * @return an array of 0 or more String of currently tethered interface names.
2309 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002310 * {@hide}
2311 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002312 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002313 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002314 public String[] getTetheredIfaces() {
2315 try {
2316 return mService.getTetheredIfaces();
2317 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002318 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002319 }
2320 }
2321
2322 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002323 * Get the set of interface names which attempted to tether but
2324 * failed. Re-attempting to tether may cause them to reset to the Tethered
2325 * state. Alternatively, causing the interface to be destroyed and recreated
2326 * may cause them to reset to the available state.
2327 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2328 * information on the cause of the errors.
2329 *
2330 * @return an array of 0 or more String indicating the interface names
2331 * which failed to tether.
2332 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002333 * {@hide}
2334 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002335 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002336 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002337 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002338 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08002339 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002340 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002341 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002342 }
2343 }
2344
2345 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002346 * Get the set of tethered dhcp ranges.
2347 *
2348 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
2349 * {@hide}
2350 */
2351 public String[] getTetheredDhcpRanges() {
2352 try {
2353 return mService.getTetheredDhcpRanges();
2354 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002355 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002356 }
2357 }
2358
2359 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002360 * Attempt to tether the named interface. This will setup a dhcp server
2361 * on the interface, forward and NAT IP packets and forward DNS requests
2362 * to the best active upstream network interface. Note that if no upstream
2363 * IP network interface is available, dhcp will still run and traffic will be
2364 * allowed between the tethered devices and this device, though upstream net
2365 * access will of course fail until an upstream network interface becomes
2366 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002367 *
2368 * <p>This method requires the caller to hold either the
2369 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2370 * or the ability to modify system settings as determined by
2371 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002372 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002373 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2374 * and WifiStateMachine which need direct access. All other clients should use
2375 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2376 * logic.</p>
2377 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002378 * @param iface the interface name to tether.
2379 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2380 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002381 * {@hide}
2382 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002383 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002384 public int tether(String iface) {
2385 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002386 String pkgName = mContext.getOpPackageName();
2387 Log.i(TAG, "tether caller:" + pkgName);
2388 return mService.tether(iface, pkgName);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002389 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002390 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002391 }
2392 }
2393
2394 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002395 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002396 *
2397 * <p>This method requires the caller to hold either the
2398 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2399 * or the ability to modify system settings as determined by
2400 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002401 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002402 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2403 * and WifiStateMachine which need direct access. All other clients should use
2404 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2405 * logic.</p>
2406 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002407 * @param iface the interface name to untether.
2408 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2409 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002410 * {@hide}
2411 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002412 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002413 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002414 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002415 String pkgName = mContext.getOpPackageName();
2416 Log.i(TAG, "untether caller:" + pkgName);
2417 return mService.untether(iface, pkgName);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002418 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002419 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002420 }
2421 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002422
2423 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002424 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002425 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002426 * due to device configuration.
2427 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002428 * <p>If this app does not have permission to use this API, it will always
2429 * return false rather than throw an exception.</p>
2430 *
2431 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2432 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2433 *
2434 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2435 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2436 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002437 * @return a boolean - {@code true} indicating Tethering is supported.
2438 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002439 * {@hide}
2440 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002441 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002442 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2443 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002444 public boolean isTetheringSupported() {
Chalard Jean8f76fc32017-09-26 15:45:18 +09002445 String pkgName = mContext.getOpPackageName();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002446 try {
Udam Saini0e94c362017-06-07 12:06:28 -07002447 return mService.isTetheringSupported(pkgName);
Chalard Jean8f76fc32017-09-26 15:45:18 +09002448 } catch (SecurityException e) {
2449 // This API is not available to this caller, but for backward-compatibility
2450 // this will just return false instead of throwing.
2451 return false;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002452 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002453 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002454 }
2455 }
2456
2457 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002458 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2459 * @hide
2460 */
2461 @SystemApi
2462 public static abstract class OnStartTetheringCallback {
2463 /**
2464 * Called when tethering has been successfully started.
2465 */
Chalard Jean4d660112018-06-04 16:52:49 +09002466 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002467
2468 /**
2469 * Called when starting tethering failed.
2470 */
Chalard Jean4d660112018-06-04 16:52:49 +09002471 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002472 }
2473
2474 /**
2475 * Convenient overload for
2476 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2477 * handler to run on the current thread's {@link Looper}.
2478 * @hide
2479 */
2480 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07002481 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002482 public void startTethering(int type, boolean showProvisioningUi,
2483 final OnStartTetheringCallback callback) {
2484 startTethering(type, showProvisioningUi, callback, null);
2485 }
2486
2487 /**
2488 * Runs tether provisioning for the given type if needed and then starts tethering if
2489 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2490 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2491 * schedules tether provisioning re-checks if appropriate.
2492 *
2493 * @param type The type of tethering to start. Must be one of
2494 * {@link ConnectivityManager.TETHERING_WIFI},
2495 * {@link ConnectivityManager.TETHERING_USB}, or
2496 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2497 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2498 * is one. This should be true the first time this function is called and also any time
2499 * the user can see this UI. It gives users information from their carrier about the
2500 * check failing and how they can sign up for tethering if possible.
2501 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2502 * of the result of trying to tether.
2503 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2504 * @hide
2505 */
2506 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002507 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002508 public void startTethering(int type, boolean showProvisioningUi,
2509 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002510 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002511
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002512 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2513 @Override
2514 protected void onReceiveResult(int resultCode, Bundle resultData) {
2515 if (resultCode == TETHER_ERROR_NO_ERROR) {
2516 callback.onTetheringStarted();
2517 } else {
2518 callback.onTetheringFailed();
2519 }
2520 }
2521 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002522
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002523 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002524 String pkgName = mContext.getOpPackageName();
2525 Log.i(TAG, "startTethering caller:" + pkgName);
2526 mService.startTethering(type, wrappedCallback, showProvisioningUi, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002527 } catch (RemoteException e) {
2528 Log.e(TAG, "Exception trying to start tethering.", e);
2529 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2530 }
2531 }
2532
2533 /**
2534 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2535 * applicable.
2536 *
2537 * @param type The type of tethering to stop. Must be one of
2538 * {@link ConnectivityManager.TETHERING_WIFI},
2539 * {@link ConnectivityManager.TETHERING_USB}, or
2540 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2541 * @hide
2542 */
2543 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002544 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002545 public void stopTethering(int type) {
2546 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002547 String pkgName = mContext.getOpPackageName();
2548 Log.i(TAG, "stopTethering caller:" + pkgName);
2549 mService.stopTethering(type, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002550 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002551 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002552 }
2553 }
2554
2555 /**
markchien26299ed2019-02-27 14:56:11 +08002556 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2557 * upstream status.
2558 *
2559 *@hide
2560 */
2561 @SystemApi
2562 public abstract static class OnTetheringEventCallback {
2563
2564 /**
2565 * Called when tethering upstream changed. This can be called multiple times and can be
2566 * called any time.
2567 *
2568 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2569 * have any upstream.
2570 */
2571 public void onUpstreamChanged(@Nullable Network network) {}
2572 }
2573
2574 @GuardedBy("mTetheringEventCallbacks")
2575 private final ArrayMap<OnTetheringEventCallback, ITetheringEventCallback>
2576 mTetheringEventCallbacks = new ArrayMap<>();
2577
2578 /**
2579 * Start listening to tethering change events. Any new added callback will receive the last
2580 * tethering status right away. If callback is registered when tethering loses its upstream or
2581 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2582 * with a null argument. The same callback object cannot be registered twice.
2583 *
2584 * @param executor the executor on which callback will be invoked.
2585 * @param callback the callback to be called when tethering has change events.
2586 * @hide
2587 */
2588 @SystemApi
2589 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2590 public void registerTetheringEventCallback(
2591 @NonNull @CallbackExecutor Executor executor,
2592 @NonNull final OnTetheringEventCallback callback) {
2593 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2594
2595 synchronized (mTetheringEventCallbacks) {
2596 Preconditions.checkArgument(!mTetheringEventCallbacks.containsKey(callback),
2597 "callback was already registered.");
2598 ITetheringEventCallback remoteCallback = new ITetheringEventCallback.Stub() {
2599 @Override
2600 public void onUpstreamChanged(Network network) throws RemoteException {
2601 Binder.withCleanCallingIdentity(() ->
2602 executor.execute(() -> {
2603 callback.onUpstreamChanged(network);
2604 }));
2605 }
2606 };
2607 try {
2608 String pkgName = mContext.getOpPackageName();
2609 Log.i(TAG, "registerTetheringUpstreamCallback:" + pkgName);
2610 mService.registerTetheringEventCallback(remoteCallback, pkgName);
2611 mTetheringEventCallbacks.put(callback, remoteCallback);
2612 } catch (RemoteException e) {
2613 throw e.rethrowFromSystemServer();
2614 }
2615 }
2616 }
2617
2618 /**
2619 * Remove tethering event callback previously registered with
2620 * {@link #registerTetheringEventCallback}.
2621 *
2622 * @param callback previously registered callback.
2623 * @hide
2624 */
2625 @SystemApi
2626 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2627 public void unregisterTetheringEventCallback(
2628 @NonNull final OnTetheringEventCallback callback) {
2629 synchronized (mTetheringEventCallbacks) {
2630 ITetheringEventCallback remoteCallback = mTetheringEventCallbacks.remove(callback);
2631 Preconditions.checkNotNull(remoteCallback, "callback was not registered.");
2632 try {
2633 String pkgName = mContext.getOpPackageName();
2634 Log.i(TAG, "unregisterTetheringEventCallback:" + pkgName);
2635 mService.unregisterTetheringEventCallback(remoteCallback, pkgName);
2636 } catch (RemoteException e) {
2637 throw e.rethrowFromSystemServer();
2638 }
2639 }
2640 }
2641
2642
2643 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002644 * Get the list of regular expressions that define any tetherable
2645 * USB network interfaces. If USB tethering is not supported by the
2646 * device, this list should be empty.
2647 *
2648 * @return an array of 0 or more regular expression Strings defining
2649 * what interfaces are considered tetherable usb interfaces.
2650 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002651 * {@hide}
2652 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002653 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002654 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002655 public String[] getTetherableUsbRegexs() {
2656 try {
2657 return mService.getTetherableUsbRegexs();
2658 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002659 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002660 }
2661 }
2662
2663 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002664 * Get the list of regular expressions that define any tetherable
2665 * Wifi network interfaces. If Wifi tethering is not supported by the
2666 * device, this list should be empty.
2667 *
2668 * @return an array of 0 or more regular expression Strings defining
2669 * what interfaces are considered tetherable wifi interfaces.
2670 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002671 * {@hide}
2672 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002673 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002674 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002675 public String[] getTetherableWifiRegexs() {
2676 try {
2677 return mService.getTetherableWifiRegexs();
2678 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002679 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002680 }
2681 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002682
Danica Chang6fdd0c62010-08-11 14:54:43 -07002683 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002684 * Get the list of regular expressions that define any tetherable
2685 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2686 * device, this list should be empty.
2687 *
2688 * @return an array of 0 or more regular expression Strings defining
2689 * what interfaces are considered tetherable bluetooth interfaces.
2690 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002691 * {@hide}
2692 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002693 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002694 @UnsupportedAppUsage
Danica Chang6fdd0c62010-08-11 14:54:43 -07002695 public String[] getTetherableBluetoothRegexs() {
2696 try {
2697 return mService.getTetherableBluetoothRegexs();
2698 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002699 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002700 }
2701 }
2702
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002703 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002704 * Attempt to both alter the mode of USB and Tethering of USB. A
2705 * utility method to deal with some of the complexity of USB - will
2706 * attempt to switch to Rndis and subsequently tether the resulting
2707 * interface on {@code true} or turn off tethering and switch off
2708 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002709 *
2710 * <p>This method requires the caller to hold either the
2711 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2712 * or the ability to modify system settings as determined by
2713 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002714 *
2715 * @param enable a boolean - {@code true} to enable tethering
2716 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2717 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002718 * {@hide}
2719 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002720 @UnsupportedAppUsage
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002721 public int setUsbTethering(boolean enable) {
2722 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002723 String pkgName = mContext.getOpPackageName();
2724 Log.i(TAG, "setUsbTethering caller:" + pkgName);
2725 return mService.setUsbTethering(enable, pkgName);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002726 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002727 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002728 }
2729 }
2730
Robert Greenwalt5a735062010-03-02 17:25:02 -08002731 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002732 @SystemApi
Robert Greenwalt5a735062010-03-02 17:25:02 -08002733 public static final int TETHER_ERROR_NO_ERROR = 0;
2734 /** {@hide} */
2735 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2736 /** {@hide} */
2737 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2738 /** {@hide} */
2739 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2740 /** {@hide} */
2741 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2742 /** {@hide} */
2743 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2744 /** {@hide} */
2745 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2746 /** {@hide} */
2747 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2748 /** {@hide} */
2749 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2750 /** {@hide} */
2751 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2752 /** {@hide} */
2753 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002754 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002755 @SystemApi
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002756 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +09002757 /** {@hide} */
2758 public static final int TETHER_ERROR_DHCPSERVER_ERROR = 12;
markchienf2731272019-01-16 17:44:13 +08002759 /** {@hide} */
2760 @SystemApi
2761 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002762
2763 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002764 * Get a more detailed error code after a Tethering or Untethering
2765 * request asynchronously failed.
2766 *
2767 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002768 * @return error The error code of the last error tethering or untethering the named
2769 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002770 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002771 * {@hide}
2772 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002773 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002774 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002775 public int getLastTetherError(String iface) {
2776 try {
2777 return mService.getLastTetherError(iface);
2778 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002779 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002780 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002781 }
2782
markchien9554abf2019-03-06 16:25:00 +08002783 /** @hide */
2784 @Retention(RetentionPolicy.SOURCE)
2785 @IntDef(value = {
2786 TETHER_ERROR_NO_ERROR,
2787 TETHER_ERROR_PROVISION_FAILED,
2788 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2789 })
2790 public @interface EntitlementResultCode {
2791 }
2792
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002793 /**
markchien9554abf2019-03-06 16:25:00 +08002794 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchienf2731272019-01-16 17:44:13 +08002795 * entitlement succeeded.
2796 * @hide
2797 */
2798 @SystemApi
markchien9554abf2019-03-06 16:25:00 +08002799 public interface OnTetheringEntitlementResultListener {
2800 /**
2801 * Called to notify entitlement result.
2802 *
2803 * @param resultCode an int value of entitlement result. It may be one of
2804 * {@link #TETHER_ERROR_NO_ERROR},
2805 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2806 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2807 */
2808 void onEntitlementResult(@EntitlementResultCode int resultCode);
2809 }
2810
2811 /**
2812 * @removed
2813 * @deprecated This API would be removed when all of caller has been updated.
2814 * */
2815 @Deprecated
markchienf2731272019-01-16 17:44:13 +08002816 public abstract static class TetheringEntitlementValueListener {
2817 /**
2818 * Called to notify entitlement result.
2819 *
2820 * @param resultCode a int value of entitlement result. It may be one of
2821 * {@link #TETHER_ERROR_NO_ERROR},
2822 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2823 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2824 */
2825 public void onEntitlementResult(int resultCode) {}
2826 }
2827
2828 /**
2829 * Get the last value of the entitlement check on this downstream. If the cached value is
2830 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2831 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2832 * guaranteed that the UI-based entitlement check will complete in any specific time period
2833 * and may in fact never complete. Any successful entitlement check the platform performs for
2834 * any reason will update the cached value.
2835 *
2836 * @param type the downstream type of tethering. Must be one of
2837 * {@link #TETHERING_WIFI},
2838 * {@link #TETHERING_USB}, or
2839 * {@link #TETHERING_BLUETOOTH}.
2840 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchien9554abf2019-03-06 16:25:00 +08002841 * @param executor the executor on which callback will be invoked.
2842 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2843 * notify the caller of the result of entitlement check. The listener may be called zero
2844 * or one time.
markchienf2731272019-01-16 17:44:13 +08002845 * {@hide}
2846 */
2847 @SystemApi
2848 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchien9554abf2019-03-06 16:25:00 +08002849 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2850 @NonNull @CallbackExecutor Executor executor,
2851 @NonNull final OnTetheringEntitlementResultListener listener) {
2852 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2853 ResultReceiver wrappedListener = new ResultReceiver(null) {
2854 @Override
2855 protected void onReceiveResult(int resultCode, Bundle resultData) {
2856 Binder.withCleanCallingIdentity(() ->
2857 executor.execute(() -> {
2858 listener.onEntitlementResult(resultCode);
2859 }));
2860 }
2861 };
2862
2863 try {
2864 String pkgName = mContext.getOpPackageName();
2865 Log.i(TAG, "getLatestTetheringEntitlementResult:" + pkgName);
2866 mService.getLatestTetheringEntitlementResult(type, wrappedListener,
2867 showEntitlementUi, pkgName);
2868 } catch (RemoteException e) {
2869 throw e.rethrowFromSystemServer();
2870 }
2871 }
2872
2873 /**
2874 * @removed
2875 * @deprecated This API would be removed when all of caller has been updated.
2876 * */
2877 @Deprecated
markchienf2731272019-01-16 17:44:13 +08002878 public void getLatestTetheringEntitlementValue(int type, boolean showEntitlementUi,
2879 @NonNull final TetheringEntitlementValueListener listener, @Nullable Handler handler) {
2880 Preconditions.checkNotNull(listener, "TetheringEntitlementValueListener cannot be null.");
2881 ResultReceiver wrappedListener = new ResultReceiver(handler) {
2882 @Override
2883 protected void onReceiveResult(int resultCode, Bundle resultData) {
2884 listener.onEntitlementResult(resultCode);
2885 }
2886 };
2887
2888 try {
2889 String pkgName = mContext.getOpPackageName();
2890 Log.i(TAG, "getLatestTetheringEntitlementValue:" + pkgName);
markchien9554abf2019-03-06 16:25:00 +08002891 mService.getLatestTetheringEntitlementResult(type, wrappedListener,
markchienf2731272019-01-16 17:44:13 +08002892 showEntitlementUi, pkgName);
2893 } catch (RemoteException e) {
2894 throw e.rethrowFromSystemServer();
2895 }
2896 }
2897
2898 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002899 * Report network connectivity status. This is currently used only
2900 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002901 * <p>This method requires the caller to hold the permission
2902 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002903 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002904 * @param networkType The type of network you want to report on
2905 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002906 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002907 * {@hide}
2908 */
2909 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002910 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002911 try {
2912 mService.reportInetCondition(networkType, percentage);
2913 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002914 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002915 }
2916 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002917
2918 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002919 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002920 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002921 * the framework to re-evaluate network connectivity and/or switch to another
2922 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002923 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002924 * @param network The {@link Network} the application was attempting to use
2925 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002926 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2927 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002928 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002929 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002930 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002931 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002932 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002933 // One of these will be ignored because it matches system's current state.
2934 // The other will trigger the necessary reevaluation.
2935 mService.reportNetworkConnectivity(network, true);
2936 mService.reportNetworkConnectivity(network, false);
2937 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002938 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002939 }
2940 }
2941
2942 /**
2943 * Report to the framework whether a network has working connectivity.
2944 * This provides a hint to the system that a particular network is providing
2945 * working connectivity or not. In response the framework may re-evaluate
2946 * the network's connectivity and might take further action thereafter.
2947 *
2948 * @param network The {@link Network} the application was attempting to use
2949 * or {@code null} to indicate the current default network.
2950 * @param hasConnectivity {@code true} if the application was able to successfully access the
2951 * Internet using {@code network} or {@code false} if not.
2952 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002953 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002954 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002955 try {
2956 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002957 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002958 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002959 }
2960 }
2961
2962 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002963 * Set a network-independent global http proxy. This is not normally what you want
2964 * for typical HTTP proxies - they are general network dependent. However if you're
2965 * doing something unusual like general internal filtering this may be useful. On
2966 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002967 *
2968 * @param p A {@link ProxyInfo} object defining the new global
2969 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002970 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002971 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002972 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Jason Monk207900c2014-04-25 15:00:09 -04002973 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002974 try {
2975 mService.setGlobalProxy(p);
2976 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002977 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002978 }
2979 }
2980
2981 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002982 * Retrieve any network-independent global HTTP proxy.
2983 *
Jason Monk207900c2014-04-25 15:00:09 -04002984 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002985 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002986 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002987 */
Jason Monk207900c2014-04-25 15:00:09 -04002988 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002989 try {
2990 return mService.getGlobalProxy();
2991 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002992 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002993 }
2994 }
2995
2996 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002997 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2998 * network-specific HTTP proxy. If {@code network} is null, the
2999 * network-specific proxy returned is the proxy of the default active
3000 * network.
3001 *
3002 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3003 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3004 * or when {@code network} is {@code null},
3005 * the {@code ProxyInfo} for the default active network. Returns
3006 * {@code null} when no proxy applies or the caller doesn't have
3007 * permission to use {@code network}.
3008 * @hide
3009 */
3010 public ProxyInfo getProxyForNetwork(Network network) {
3011 try {
3012 return mService.getProxyForNetwork(network);
3013 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003014 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04003015 }
3016 }
3017
3018 /**
Paul Jensene0bef712014-12-10 15:12:18 -05003019 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3020 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04003021 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05003022 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003023 *
Jason Monk207900c2014-04-25 15:00:09 -04003024 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003025 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07003026 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003027 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05003028 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04003029 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07003030 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003031
3032 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003033 * Returns true if the hardware supports the given network type
3034 * else it returns false. This doesn't indicate we have coverage
3035 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003036 * hardware supports it. For example a GSM phone without a SIM
3037 * should still return {@code true} for mobile data, but a wifi only
3038 * tablet would return {@code false}.
3039 *
3040 * @param networkType The network type we'd like to check
3041 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003042 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003043 * @hide
3044 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003045 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003046 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003047 @UnsupportedAppUsage
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003048 public boolean isNetworkSupported(int networkType) {
3049 try {
3050 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003051 } catch (RemoteException e) {
3052 throw e.rethrowFromSystemServer();
3053 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003054 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003055
3056 /**
3057 * Returns if the currently active data network is metered. A network is
3058 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003059 * that connection due to monetary costs, data limitations or
3060 * battery/performance issues. You should check this before doing large
3061 * data transfers, and warn the user or delay the operation until another
3062 * network is available.
3063 *
3064 * @return {@code true} if large transfers should be avoided, otherwise
3065 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003066 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003067 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003068 public boolean isActiveNetworkMetered() {
3069 try {
3070 return mService.isActiveNetworkMetered();
3071 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003072 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003073 }
3074 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003075
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003076 /**
3077 * If the LockdownVpn mechanism is enabled, updates the vpn
3078 * with a reload of its profile.
3079 *
3080 * @return a boolean with {@code} indicating success
3081 *
3082 * <p>This method can only be called by the system UID
3083 * {@hide}
3084 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003085 public boolean updateLockdownVpn() {
3086 try {
3087 return mService.updateLockdownVpn();
3088 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003089 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003090 }
3091 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07003092
3093 /**
Wink Saville948282b2013-08-29 08:55:16 -07003094 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07003095 *
Wink Savilleab9321d2013-06-29 21:10:57 -07003096 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07003097 *
3098 * @return time out that will be used, maybe less that suggestedTimeOutMs
3099 * -1 if an error.
3100 *
3101 * {@hide}
3102 */
Wink Saville948282b2013-08-29 08:55:16 -07003103 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003104 int timeOutMs = -1;
3105 try {
Wink Saville948282b2013-08-29 08:55:16 -07003106 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07003107 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003108 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07003109 }
3110 return timeOutMs;
3111 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003112
3113 /**
Wink Saville42d4f082013-07-20 20:31:59 -07003114 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003115 * {@hide}
3116 */
3117 public String getMobileProvisioningUrl() {
3118 try {
3119 return mService.getMobileProvisioningUrl();
3120 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003121 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003122 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003123 }
Wink Saville42d4f082013-07-20 20:31:59 -07003124
3125 /**
Wink Saville948282b2013-08-29 08:55:16 -07003126 * Set sign in error notification to visible or in visible
3127 *
Wink Saville948282b2013-08-29 08:55:16 -07003128 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04003129 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07003130 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003131 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07003132 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003133 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003134 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04003135 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07003136 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003137 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07003138 }
3139 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003140
3141 /**
3142 * Set the value for enabling/disabling airplane mode
3143 *
3144 * @param enable whether to enable airplane mode or not
3145 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003146 * @hide
3147 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003148 @RequiresPermission(anyOf = {
3149 android.Manifest.permission.NETWORK_SETTINGS,
3150 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3151 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09003152 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003153 public void setAirplaneMode(boolean enable) {
3154 try {
3155 mService.setAirplaneMode(enable);
3156 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003157 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003158 }
3159 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003160
Chalard Jean05ab6812018-05-02 21:14:54 +09003161 /** {@hide} - returns the factory serial number */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003162 @UnsupportedAppUsage
Chalard Jean05ab6812018-05-02 21:14:54 +09003163 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003164 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003165 return mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003166 } catch (RemoteException e) {
3167 throw e.rethrowFromSystemServer();
3168 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003169 }
3170
3171 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00003172 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Robert Greenwalta67be032014-05-16 15:49:14 -07003173 public void unregisterNetworkFactory(Messenger messenger) {
3174 try {
3175 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003176 } catch (RemoteException e) {
3177 throw e.rethrowFromSystemServer();
3178 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003179 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003180
Chalard Jean05ab6812018-05-02 21:14:54 +09003181 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3182 // of dependent changes that would conflict throughout the automerger graph. Having this
3183 // temporarily helps with the process of going through with all these dependent changes across
3184 // the entire tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05003185 /**
3186 * @hide
3187 * Register a NetworkAgent with ConnectivityService.
3188 * @return NetID corresponding to NetworkAgent.
3189 */
3190 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003191 NetworkCapabilities nc, int score, NetworkMisc misc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003192 return registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3193 NetworkFactory.SerialNumber.NONE);
3194 }
3195
3196 /**
3197 * @hide
3198 * Register a NetworkAgent with ConnectivityService.
3199 * @return NetID corresponding to NetworkAgent.
3200 */
3201 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
3202 NetworkCapabilities nc, int score, NetworkMisc misc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003203 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003204 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3205 factorySerialNumber);
Paul Jensen31a94f42015-02-13 14:18:39 -05003206 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003207 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05003208 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003209 }
3210
Robert Greenwalt9258c642014-03-26 16:47:06 -07003211 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003212 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3213 * changes. Should be extended by applications wanting notifications.
3214 *
3215 * A {@code NetworkCallback} is registered by calling
3216 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3217 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09003218 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09003219 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3220 * A {@code NetworkCallback} should be registered at most once at any time.
3221 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003222 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003223 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003224 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003225 * Called when the framework connects to a new network to evaluate whether it satisfies this
3226 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3227 * callback. There is no guarantee that this new network will satisfy any requests, or that
3228 * the network will stay connected for longer than the time necessary to evaluate it.
3229 * <p>
3230 * Most applications <b>should not</b> act on this callback, and should instead use
3231 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3232 * the framework in properly evaluating the network &mdash; for example, an application that
3233 * can automatically log in to a captive portal without user intervention.
3234 *
3235 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09003236 *
3237 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07003238 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003239 public void onPreCheck(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003240
3241 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003242 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003243 * This callback may be called more than once if the {@link Network} that is
3244 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003245 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003246 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003247 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3248 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08003249 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003250 * @hide
3251 */
3252 public void onAvailable(Network network, NetworkCapabilities networkCapabilities,
junyulai05986c62018-08-07 19:50:45 +08003253 LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003254 // Internally only this method is called when a new network is available, and
3255 // it calls the callback in the same way and order that older versions used
3256 // to call so as not to change the behavior.
3257 onAvailable(network);
3258 if (!networkCapabilities.hasCapability(
3259 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3260 onNetworkSuspended(network);
3261 }
3262 onCapabilitiesChanged(network, networkCapabilities);
3263 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003264 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003265 }
3266
3267 /**
3268 * Called when the framework connects and has declared a new network ready for use.
3269 * This callback may be called more than once if the {@link Network} that is
3270 * satisfying the request changes. This will always immediately be followed by a
3271 * call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} then by a
junyulai05986c62018-08-07 19:50:45 +08003272 * call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call to
3273 * {@link #onBlockedStatusChanged(Network, boolean)}.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003274 *
3275 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003276 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003277 public void onAvailable(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003278
3279 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003280 * Called when the network is about to be disconnected. Often paired with an
Robert Greenwalt6078b502014-06-11 16:05:07 -07003281 * {@link NetworkCallback#onAvailable} call with the new replacement network
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003282 * for graceful handover. This may not be called if we have a hard loss
3283 * (loss without warning). This may be followed by either a
Robert Greenwalt6078b502014-06-11 16:05:07 -07003284 * {@link NetworkCallback#onLost} call or a
3285 * {@link NetworkCallback#onAvailable} call for this network depending
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003286 * on whether we lose or regain it.
3287 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003288 * @param network The {@link Network} that is about to be disconnected.
3289 * @param maxMsToLive The time in ms the framework will attempt to keep the
3290 * network connected. Note that the network may suffer a
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003291 * hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003292 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003293 public void onLosing(Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003294
3295 /**
3296 * Called when the framework has a hard loss of the network or when the
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003297 * graceful failure ends.
3298 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003299 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003300 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003301 public void onLost(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003302
3303 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003304 * Called if no network is found in the timeout time specified in
Etan Cohenddb720a2019-01-08 12:09:18 -08003305 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3306 * requested network request cannot be fulfilled (whether or not a timeout was
3307 * specified). When this callback is invoked the associated
Etan Cohenaebf17e2017-03-01 12:47:28 -08003308 * {@link NetworkRequest} will have already been removed and released, as if
3309 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003310 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003311 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003312
3313 /**
3314 * Called when the network the framework connected to for this request
3315 * changes capabilities but still satisfies the stated need.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003316 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003317 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003318 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3319 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003320 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003321 public void onCapabilitiesChanged(Network network,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003322 NetworkCapabilities networkCapabilities) {}
3323
3324 /**
3325 * Called when the network the framework connected to for this request
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003326 * changes {@link LinkProperties}.
3327 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003328 * @param network The {@link Network} whose link properties have changed.
3329 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003330 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003331 public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003332
Robert Greenwalt8d482522015-06-24 13:23:42 -07003333 /**
3334 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003335 * goes into {@link NetworkInfo.State#SUSPENDED}.
Robert Greenwalt8d482522015-06-24 13:23:42 -07003336 * This generally means that while the TCP connections are still live,
3337 * temporarily network data fails to transfer. Specifically this is used
3338 * on cellular networks to mask temporary outages when driving through
3339 * a tunnel, etc.
3340 * @hide
3341 */
3342 public void onNetworkSuspended(Network network) {}
3343
3344 /**
3345 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003346 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3347 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Robert Greenwalt8d482522015-06-24 13:23:42 -07003348 * @hide
3349 */
3350 public void onNetworkResumed(Network network) {}
3351
junyulai05986c62018-08-07 19:50:45 +08003352 /**
3353 * Called when access to the specified network is blocked or unblocked.
3354 *
3355 * @param network The {@link Network} whose blocked status has changed.
3356 * @param blocked The blocked status of this {@link Network}.
3357 */
3358 public void onBlockedStatusChanged(Network network, boolean blocked) {}
3359
Robert Greenwalt6078b502014-06-11 16:05:07 -07003360 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003361 }
3362
Hugo Benichicb883232017-05-11 13:16:17 +09003363 /**
3364 * Constant error codes used by ConnectivityService to communicate about failures and errors
3365 * across a Binder boundary.
3366 * @hide
3367 */
3368 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003369 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003370 }
3371
3372 /** @hide */
3373 public static class TooManyRequestsException extends RuntimeException {}
3374
3375 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3376 switch (e.errorCode) {
3377 case Errors.TOO_MANY_REQUESTS:
3378 return new TooManyRequestsException();
3379 default:
3380 Log.w(TAG, "Unknown service error code " + e.errorCode);
3381 return new RuntimeException(e);
3382 }
3383 }
3384
Robert Greenwalt9258c642014-03-26 16:47:06 -07003385 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003386 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003387 public static final int CALLBACK_PRECHECK = BASE + 1;
3388 /** @hide */
3389 public static final int CALLBACK_AVAILABLE = BASE + 2;
3390 /** @hide arg1 = TTL */
3391 public static final int CALLBACK_LOSING = BASE + 3;
3392 /** @hide */
3393 public static final int CALLBACK_LOST = BASE + 4;
3394 /** @hide */
3395 public static final int CALLBACK_UNAVAIL = BASE + 5;
3396 /** @hide */
3397 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3398 /** @hide */
3399 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003400 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003401 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003402 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003403 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003404 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003405 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003406 /** @hide */
3407 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003408
Erik Kline57faba92015-11-25 12:49:38 +09003409 /** @hide */
3410 public static String getCallbackName(int whichCallback) {
3411 switch (whichCallback) {
3412 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3413 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3414 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3415 case CALLBACK_LOST: return "CALLBACK_LOST";
3416 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3417 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3418 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003419 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3420 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3421 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003422 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003423 default:
3424 return Integer.toString(whichCallback);
3425 }
3426 }
3427
Robert Greenwalt562cc542014-05-15 18:07:26 -07003428 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003429 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003430 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003431
Hugo Benichid42650f2016-07-06 22:53:17 +09003432 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003433 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003434 }
3435
Hugo Benichi2583ef02017-02-02 17:02:36 +09003436 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003437 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003438 }
3439
Robert Greenwalt9258c642014-03-26 16:47:06 -07003440 @Override
3441 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003442 if (message.what == EXPIRE_LEGACY_REQUEST) {
3443 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3444 return;
3445 }
3446
3447 final NetworkRequest request = getObject(message, NetworkRequest.class);
3448 final Network network = getObject(message, Network.class);
3449 final NetworkCallback callback;
3450 synchronized (sCallbacks) {
3451 callback = sCallbacks.get(request);
3452 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003453 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003454 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003455 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003456 if (callback == null) {
3457 Log.w(TAG, "callback not found for " + getCallbackName(message.what) + " message");
3458 return;
3459 }
3460
Robert Greenwalt9258c642014-03-26 16:47:06 -07003461 switch (message.what) {
3462 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003463 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003464 break;
3465 }
3466 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003467 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3468 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003469 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003470 break;
3471 }
3472 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003473 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003474 break;
3475 }
3476 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003477 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003478 break;
3479 }
3480 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003481 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003482 break;
3483 }
3484 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003485 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3486 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003487 break;
3488 }
3489 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003490 LinkProperties lp = getObject(message, LinkProperties.class);
3491 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003492 break;
3493 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003494 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003495 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003496 break;
3497 }
3498 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003499 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003500 break;
3501 }
junyulai05986c62018-08-07 19:50:45 +08003502 case CALLBACK_BLK_CHANGED: {
3503 boolean blocked = message.arg1 != 0;
3504 callback.onBlockedStatusChanged(network, blocked);
3505 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003506 }
3507 }
3508
Hugo Benichid42650f2016-07-06 22:53:17 +09003509 private <T> T getObject(Message msg, Class<T> c) {
3510 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003511 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003512 }
3513
Hugo Benichi2583ef02017-02-02 17:02:36 +09003514 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003515 synchronized (sCallbacks) {
3516 if (sCallbackHandler == null) {
3517 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003518 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003519 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003520 }
3521 }
3522
Hugo Benichi6f260f32017-02-03 14:18:44 +09003523 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3524 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003525
Hugo Benichi6f260f32017-02-03 14:18:44 +09003526 private static final int LISTEN = 1;
3527 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003528
Hugo Benichi6f260f32017-02-03 14:18:44 +09003529 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3530 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003531 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003532 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003533 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003534 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003535 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003536 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003537 if (callback.networkRequest != null
3538 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003539 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3540 // and requests (http://b/20701525).
3541 Log.e(TAG, "NetworkCallback was already registered");
3542 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003543 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003544 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003545 if (action == LISTEN) {
Hugo Benichid42650f2016-07-06 22:53:17 +09003546 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04003547 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003548 request = mService.requestNetwork(
3549 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04003550 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003551 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003552 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003553 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003554 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003555 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003556 } catch (RemoteException e) {
3557 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003558 } catch (ServiceSpecificException e) {
3559 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003560 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003561 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003562 }
3563
3564 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003565 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003566 *
3567 * This is temporarily public @hide so it can be called by system code that uses the
3568 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
3569 * instead network notifications.
3570 *
3571 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
3572 *
3573 * @hide
3574 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003575 public void requestNetwork(@NonNull NetworkRequest request,
3576 @NonNull NetworkCallback networkCallback, int timeoutMs, int legacyType,
3577 @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003578 CallbackHandler cbHandler = new CallbackHandler(handler);
3579 NetworkCapabilities nc = request.networkCapabilities;
3580 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003581 }
3582
3583 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003584 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003585 *
3586 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003587 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3588 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003589 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003590 * Status of the request can be followed by listening to the various
Robert Greenwalt6078b502014-06-11 16:05:07 -07003591 * callbacks described in {@link NetworkCallback}. The {@link Network}
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003592 * can be used to direct traffic to the network.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003593 * <p>It is presently unsupported to request a network with mutable
3594 * {@link NetworkCapabilities} such as
3595 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3596 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3597 * as these {@code NetworkCapabilities} represent states that a particular
3598 * network may never attain, and whether a network will attain these states
3599 * is unknown prior to bringing up the network so the framework does not
3600 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003601 *
3602 * <p>This method requires the caller to hold either the
3603 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3604 * or the ability to modify system settings as determined by
3605 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003606 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003607 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003608 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3609 * the callback must not be shared - it uniquely specifies this request.
3610 * The callback is invoked on the default internal Handler.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003611 * @throws IllegalArgumentException if {@code request} specifies any mutable
3612 * {@code NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003613 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003614 public void requestNetwork(@NonNull NetworkRequest request,
3615 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003616 requestNetwork(request, networkCallback, getDefaultHandler());
3617 }
3618
3619 /**
3620 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3621 *
3622 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003623 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3624 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003625 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003626 * Status of the request can be followed by listening to the various
3627 * callbacks described in {@link NetworkCallback}. The {@link Network}
3628 * can be used to direct traffic to the network.
3629 * <p>It is presently unsupported to request a network with mutable
3630 * {@link NetworkCapabilities} such as
3631 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3632 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3633 * as these {@code NetworkCapabilities} represent states that a particular
3634 * network may never attain, and whether a network will attain these states
3635 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003636 * know how to go about satisfying a request with these capabilities.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003637 *
3638 * <p>This method requires the caller to hold either the
3639 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3640 * or the ability to modify system settings as determined by
3641 * {@link android.provider.Settings.System#canWrite}.</p>
3642 *
3643 * @param request {@link NetworkRequest} describing this request.
3644 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3645 * the callback must not be shared - it uniquely specifies this request.
3646 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3647 * @throws IllegalArgumentException if {@code request} specifies any mutable
3648 * {@code NetworkCapabilities}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003649 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003650 public void requestNetwork(@NonNull NetworkRequest request,
3651 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003652 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3653 CallbackHandler cbHandler = new CallbackHandler(handler);
3654 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003655 }
3656
3657 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003658 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3659 * by a timeout.
3660 *
3661 * This function behaves identically to the non-timed-out version
3662 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3663 * is not found within the given time (in milliseconds) the
3664 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3665 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3666 * not have to be released if timed-out (it is automatically released). Unregistering a
3667 * request that timed out is not an error.
3668 *
3669 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3670 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3671 * for that purpose. Calling this method will attempt to bring up the requested network.
3672 *
3673 * <p>This method requires the caller to hold either the
3674 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3675 * or the ability to modify system settings as determined by
3676 * {@link android.provider.Settings.System#canWrite}.</p>
3677 *
3678 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003679 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3680 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003681 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3682 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3683 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003684 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003685 public void requestNetwork(@NonNull NetworkRequest request,
3686 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003687 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003688 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003689 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003690 }
3691
Hugo Benichi2583ef02017-02-02 17:02:36 +09003692 /**
3693 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3694 * by a timeout.
3695 *
Chalard Jean4d660112018-06-04 16:52:49 +09003696 * This function behaves identically to the version without timeout, but if a suitable
Hugo Benichi2583ef02017-02-02 17:02:36 +09003697 * network is not found within the given time (in milliseconds) the
Etan Cohenaebf17e2017-03-01 12:47:28 -08003698 * {@link NetworkCallback#onUnavailable} callback is called. The request can still be
3699 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3700 * not have to be released if timed-out (it is automatically released). Unregistering a
3701 * request that timed out is not an error.
3702 *
3703 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3704 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3705 * for that purpose. Calling this method will attempt to bring up the requested network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003706 *
3707 * <p>This method requires the caller to hold either the
3708 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3709 * or the ability to modify system settings as determined by
3710 * {@link android.provider.Settings.System#canWrite}.</p>
3711 *
3712 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003713 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3714 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003715 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003716 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3717 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003718 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003719 public void requestNetwork(@NonNull NetworkRequest request,
3720 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003721 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003722 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3723 CallbackHandler cbHandler = new CallbackHandler(handler);
3724 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003725 }
3726
3727 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003728 * The lookup key for a {@link Network} 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)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003731 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003732 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3733 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003734 */
Erik Kline90e93072014-11-19 12:12:24 +09003735 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003736
3737 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003738 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003739 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003740 * {@link android.content.Intent#getParcelableExtra(String)}.
3741 */
Erik Kline90e93072014-11-19 12:12:24 +09003742 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003743
3744
3745 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003746 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003747 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003748 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003749 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003750 * the request may outlive the calling application and get called back when a suitable
3751 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003752 * <p>
3753 * The operation is an Intent broadcast that goes to a broadcast receiver that
3754 * you registered with {@link Context#registerReceiver} or through the
3755 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3756 * <p>
3757 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003758 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3759 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003760 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003761 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003762 * Intent to reserve the network or it will be released shortly after the Intent
3763 * is processed.
3764 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003765 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003766 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003767 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003768 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003769 * The request may be released normally by calling
3770 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003771 * <p>It is presently unsupported to request a network with either
3772 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3773 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3774 * as these {@code NetworkCapabilities} represent states that a particular
3775 * network may never attain, and whether a network will attain these states
3776 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003777 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003778 *
3779 * <p>This method requires the caller to hold either the
3780 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3781 * or the ability to modify system settings as determined by
3782 * {@link android.provider.Settings.System#canWrite}.</p>
3783 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003784 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003785 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003786 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003787 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003788 * @throws IllegalArgumentException if {@code request} contains either
3789 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3790 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003791 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003792 public void requestNetwork(@NonNull NetworkRequest request,
3793 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003794 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003795 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003796 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003797 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003798 } catch (RemoteException e) {
3799 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003800 } catch (ServiceSpecificException e) {
3801 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003802 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003803 }
3804
3805 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003806 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3807 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003808 * This method has the same behavior as
3809 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003810 * releasing network resources and disconnecting.
3811 *
3812 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3813 * PendingIntent passed to
3814 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3815 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3816 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003817 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003818 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003819 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003820 try {
3821 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003822 } catch (RemoteException e) {
3823 throw e.rethrowFromSystemServer();
3824 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003825 }
3826
Hugo Benichie7678512017-05-09 15:19:01 +09003827 private static void checkPendingIntentNotNull(PendingIntent intent) {
3828 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3829 }
3830
3831 private static void checkCallbackNotNull(NetworkCallback callback) {
3832 Preconditions.checkNotNull(callback, "null NetworkCallback");
3833 }
3834
3835 private static void checkTimeout(int timeoutMs) {
3836 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003837 }
3838
3839 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003840 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003841 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003842 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3843 * called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003844 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003845 * @param request {@link NetworkRequest} describing this request.
3846 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3847 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003848 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003849 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003850 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003851 public void registerNetworkCallback(@NonNull NetworkRequest request,
3852 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003853 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3854 }
3855
3856 /**
3857 * Registers to receive notifications about all networks which satisfy the given
3858 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003859 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3860 * called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003861 *
3862 * @param request {@link NetworkRequest} describing this request.
3863 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3864 * networks change state.
3865 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003866 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003867 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003868 public void registerNetworkCallback(@NonNull NetworkRequest request,
3869 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003870 CallbackHandler cbHandler = new CallbackHandler(handler);
3871 NetworkCapabilities nc = request.networkCapabilities;
3872 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003873 }
3874
3875 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003876 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3877 * {@link NetworkRequest}.
3878 *
3879 * This function behaves identically to the version that takes a NetworkCallback, but instead
3880 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3881 * the request may outlive the calling application and get called back when a suitable
3882 * network is found.
3883 * <p>
3884 * The operation is an Intent broadcast that goes to a broadcast receiver that
3885 * you registered with {@link Context#registerReceiver} or through the
3886 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3887 * <p>
3888 * The operation Intent is delivered with two extras, a {@link Network} typed
3889 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3890 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3891 * the original requests parameters.
3892 * <p>
3893 * If there is already a request for this Intent registered (with the equality of
3894 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3895 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3896 * <p>
3897 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003898 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003899 * @param request {@link NetworkRequest} describing this request.
3900 * @param operation Action to perform when the network is available (corresponds
3901 * to the {@link NetworkCallback#onAvailable} call. Typically
3902 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3903 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003904 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003905 public void registerNetworkCallback(@NonNull NetworkRequest request,
3906 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003907 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003908 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04003909 try {
3910 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003911 } catch (RemoteException e) {
3912 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003913 } catch (ServiceSpecificException e) {
3914 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003915 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003916 }
3917
3918 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003919 * Registers to receive notifications about changes in the system default network. The callbacks
3920 * will continue to be called until either the application exits or
3921 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09003922 *
3923 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3924 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003925 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09003926 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003927 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003928 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003929 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
3930 }
3931
3932 /**
3933 * Registers to receive notifications about changes in the system default network. The callbacks
3934 * will continue to be called until either the application exits or
3935 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003936 *
3937 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3938 * system default network changes.
3939 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003940 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003941 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003942 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
3943 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09003944 // This works because if the NetworkCapabilities are null,
3945 // ConnectivityService takes them from the default request.
3946 //
3947 // Since the capabilities are exactly the same as the default request's
3948 // capabilities, this request is guaranteed, at all times, to be
3949 // satisfied by the same network, if any, that satisfies the default
3950 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003951 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09003952 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
3953 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09003954 }
3955
3956 /**
fengludb571472015-04-21 17:12:05 -07003957 * Requests bandwidth update for a given {@link Network} and returns whether the update request
3958 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
3959 * network connection for updated bandwidth information. The caller will be notified via
3960 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003961 * method assumes that the caller has previously called
3962 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
3963 * changes.
fenglub15e72b2015-03-20 11:29:56 -07003964 *
fengluae519192015-04-27 14:28:04 -07003965 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07003966 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07003967 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003968 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003969 try {
fengludb571472015-04-21 17:12:05 -07003970 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07003971 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003972 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07003973 }
3974 }
3975
3976 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003977 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003978 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
3979 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
3980 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09003981 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
3982 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003983 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09003984 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
3985 * triggering it as soon as this call returns.
3986 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003987 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003988 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003989 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003990 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003991 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003992 final List<NetworkRequest> reqs = new ArrayList<>();
3993 // Find all requests associated to this callback and stop callback triggers immediately.
3994 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
3995 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003996 Preconditions.checkArgument(networkCallback.networkRequest != null,
3997 "NetworkCallback was not registered");
3998 Preconditions.checkArgument(networkCallback.networkRequest != ALREADY_UNREGISTERED,
3999 "NetworkCallback was already unregistered");
Hugo Benichidafed3d2017-03-06 09:17:06 +09004000 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4001 if (e.getValue() == networkCallback) {
4002 reqs.add(e.getKey());
4003 }
4004 }
4005 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4006 for (NetworkRequest r : reqs) {
4007 try {
4008 mService.releaseNetworkRequest(r);
4009 } catch (RemoteException e) {
4010 throw e.rethrowFromSystemServer();
4011 }
4012 // Only remove mapping if rpc was successful.
4013 sCallbacks.remove(r);
4014 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09004015 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004016 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004017 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004018
4019 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004020 * Unregisters a callback previously registered via
4021 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4022 *
4023 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4024 * PendingIntent passed to
4025 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4026 * Cannot be null.
4027 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004028 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09004029 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004030 releaseNetworkRequest(operation);
4031 }
4032
4033 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004034 * Informs the system whether it should switch to {@code network} regardless of whether it is
4035 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4036 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4037 * the system default network regardless of any other network that's currently connected. If
4038 * {@code always} is true, then the choice is remembered, so that the next time the user
4039 * connects to this network, the system will switch to it.
4040 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004041 * @param network The network to accept.
4042 * @param accept Whether to accept the network even if unvalidated.
4043 * @param always Whether to remember this choice in the future.
4044 *
4045 * @hide
4046 */
lucasline252a742019-03-12 13:08:03 +08004047 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004048 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4049 try {
4050 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004051 } catch (RemoteException e) {
4052 throw e.rethrowFromSystemServer();
4053 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004054 }
4055
4056 /**
lucasline252a742019-03-12 13:08:03 +08004057 * Informs the system whether it should consider the network as validated even if it only has
4058 * partial connectivity. If {@code accept} is true, then the network will be considered as
4059 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4060 * is remembered, so that the next time the user connects to this network, the system will
4061 * switch to it.
4062 *
4063 * @param network The network to accept.
4064 * @param accept Whether to consider the network as validated even if it has partial
4065 * connectivity.
4066 * @param always Whether to remember this choice in the future.
4067 *
4068 * @hide
4069 */
4070 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4071 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4072 try {
4073 mService.setAcceptPartialConnectivity(network, accept, always);
4074 } catch (RemoteException e) {
4075 throw e.rethrowFromSystemServer();
4076 }
4077 }
4078
4079 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004080 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4081 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4082 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4083 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4084 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004085 * @param network The network to accept.
4086 *
4087 * @hide
4088 */
lucasline252a742019-03-12 13:08:03 +08004089 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004090 public void setAvoidUnvalidated(Network network) {
4091 try {
4092 mService.setAvoidUnvalidated(network);
4093 } catch (RemoteException e) {
4094 throw e.rethrowFromSystemServer();
4095 }
4096 }
4097
4098 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004099 * Requests that the system open the captive portal app on the specified network.
4100 *
4101 * @param network The network to log into.
4102 *
4103 * @hide
4104 */
4105 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
4106 public void startCaptivePortalApp(Network network) {
4107 try {
4108 mService.startCaptivePortalApp(network);
4109 } catch (RemoteException e) {
4110 throw e.rethrowFromSystemServer();
4111 }
4112 }
4113
4114 /**
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004115 * Requests that the system open the captive portal app with the specified extras.
4116 *
4117 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4118 * corresponding permission.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004119 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004120 * @param appExtras Extras to include in the app start intent.
4121 * @hide
4122 */
4123 @SystemApi
4124 @TestApi
4125 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004126 public void startCaptivePortalApp(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004127 try {
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004128 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004129 } catch (RemoteException e) {
4130 throw e.rethrowFromSystemServer();
4131 }
4132 }
4133
4134 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004135 * Determine whether the device is configured to avoid bad wifi.
4136 * @hide
4137 */
4138 @SystemApi
4139 public boolean getAvoidBadWifi() {
4140 try {
4141 return mService.getAvoidBadWifi();
4142 } catch (RemoteException e) {
4143 throw e.rethrowFromSystemServer();
4144 }
4145 }
4146
4147 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004148 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4149 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09004150 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4151 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004152 *
4153 * An example of such an operation might be a time-sensitive foreground activity, such as a
4154 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4155 */
4156 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4157
4158 /**
4159 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4160 * a backup channel for traffic that is primarily going over another network.
4161 *
4162 * An example might be maintaining backup connections to peers or servers for the purpose of
4163 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4164 * on backup paths should be negligible compared to the traffic on the main path.
4165 */
4166 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4167
4168 /**
4169 * It is acceptable to use metered data to improve network latency and performance.
4170 */
4171 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4172
4173 /**
4174 * Return value to use for unmetered networks. On such networks we currently set all the flags
4175 * to true.
4176 * @hide
4177 */
4178 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4179 MULTIPATH_PREFERENCE_HANDOVER |
4180 MULTIPATH_PREFERENCE_RELIABILITY |
4181 MULTIPATH_PREFERENCE_PERFORMANCE;
4182
4183 /** @hide */
4184 @Retention(RetentionPolicy.SOURCE)
4185 @IntDef(flag = true, value = {
4186 MULTIPATH_PREFERENCE_HANDOVER,
4187 MULTIPATH_PREFERENCE_RELIABILITY,
4188 MULTIPATH_PREFERENCE_PERFORMANCE,
4189 })
4190 public @interface MultipathPreference {
4191 }
4192
4193 /**
4194 * Provides a hint to the calling application on whether it is desirable to use the
4195 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4196 * for multipath data transfer on this network when it is not the system default network.
4197 * Applications desiring to use multipath network protocols should call this method before
4198 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004199 *
4200 * @param network The network on which the application desires to use multipath data.
4201 * If {@code null}, this method will return the a preference that will generally
4202 * apply to metered networks.
4203 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4204 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004205 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004206 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004207 try {
4208 return mService.getMultipathPreference(network);
4209 } catch (RemoteException e) {
4210 throw e.rethrowFromSystemServer();
4211 }
4212 }
4213
4214 /**
Stuart Scott984dc852015-03-30 13:17:11 -07004215 * Resets all connectivity manager settings back to factory defaults.
4216 * @hide
4217 */
4218 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07004219 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07004220 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07004221 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004222 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07004223 }
4224 }
4225
4226 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004227 * Binds the current process to {@code network}. All Sockets created in the future
4228 * (and not explicitly bound via a bound SocketFactory from
4229 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4230 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4231 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4232 * work and all host name resolutions will fail. This is by design so an application doesn't
4233 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4234 * To clear binding pass {@code null} for {@code network}. Using individually bound
4235 * Sockets created by Network.getSocketFactory().createSocket() and
4236 * performing network-specific host name resolutions via
4237 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04004238 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004239 *
4240 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4241 * the current binding.
4242 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4243 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004244 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09004245 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04004246 // instantiated.
4247 return setProcessDefaultNetwork(network);
4248 }
4249
4250 /**
4251 * Binds the current process to {@code network}. All Sockets created in the future
4252 * (and not explicitly bound via a bound SocketFactory from
4253 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4254 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4255 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4256 * work and all host name resolutions will fail. This is by design so an application doesn't
4257 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4258 * To clear binding pass {@code null} for {@code network}. Using individually bound
4259 * Sockets created by Network.getSocketFactory().createSocket() and
4260 * performing network-specific host name resolutions via
4261 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4262 * {@code setProcessDefaultNetwork}.
4263 *
4264 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4265 * the current binding.
4266 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4267 * @deprecated This function can throw {@link IllegalStateException}. Use
4268 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4269 * is a direct replacement.
4270 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004271 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004272 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04004273 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004274 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4275
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09004276 if (netId != NETID_UNSET) {
4277 netId = network.getNetIdForResolv();
Paul Jensenc91b5342014-08-27 12:38:45 -04004278 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004279
4280 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4281 return false;
4282 }
4283
4284 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05004285 // Set HTTP proxy system properties to match network.
4286 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09004287 try {
4288 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4289 } catch (SecurityException e) {
4290 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4291 Log.e(TAG, "Can't set proxy properties", e);
4292 }
Paul Jensenc91b5342014-08-27 12:38:45 -04004293 // Must flush DNS cache as new network may have different DNS resolutions.
4294 InetAddress.clearDnsCache();
4295 // Must flush socket pool as idle sockets will be bound to previous network and may
4296 // cause subsequent fetches to be performed on old network.
4297 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04004298 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004299
4300 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004301 }
4302
4303 /**
4304 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004305 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004306 *
4307 * @return {@code Network} to which this process is bound, or {@code null}.
4308 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004309 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004310 public Network getBoundNetworkForProcess() {
4311 // Forcing callers to call thru non-static function ensures ConnectivityManager
4312 // instantiated.
4313 return getProcessDefaultNetwork();
4314 }
4315
4316 /**
4317 * Returns the {@link Network} currently bound to this process via
4318 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4319 *
4320 * @return {@code Network} to which this process is bound, or {@code null}.
4321 * @deprecated Using this function can lead to other functions throwing
4322 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4323 * {@code getBoundNetworkForProcess} is a direct replacement.
4324 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004325 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004326 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004327 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004328 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004329 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004330 return new Network(netId);
4331 }
4332
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004333 private void unsupportedStartingFrom(int version) {
4334 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004335 // The getApplicationInfo() call we make below is not supported in system context. Let
4336 // the call through here, and rely on the fact that ConnectivityService will refuse to
4337 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004338 return;
4339 }
4340
4341 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4342 throw new UnsupportedOperationException(
4343 "This method is not supported in target SDK version " + version + " and above");
4344 }
4345 }
4346
4347 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4348 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004349 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004350 // remove these exemptions. Note that this check is not secure, and apps can still access these
4351 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4352 // so is unsupported and may break in the future. http://b/22728205
4353 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004354 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004355 }
4356
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004357 /**
4358 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004359 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004360 *
4361 * @param network The {@link Network} to bind host resolutions from the current process to, or
4362 * {@code null} to clear the current binding.
4363 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4364 * @hide
4365 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4366 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004367 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004368 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004369 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004370 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004371 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004372 }
Felipe Leme1b103232016-01-22 09:44:57 -08004373
4374 /**
4375 * Device is not restricting metered network activity while application is running on
4376 * background.
4377 */
4378 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4379
4380 /**
4381 * Device is restricting metered network activity while application is running on background,
4382 * but application is allowed to bypass it.
4383 * <p>
4384 * In this state, application should take action to mitigate metered network access.
4385 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4386 */
4387 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4388
4389 /**
4390 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004391 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004392 * In this state, application should not try to use the network while running on background,
4393 * because it would be denied.
4394 */
4395 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4396
Felipe Leme9778f762016-01-27 14:46:39 -08004397 /**
4398 * A change in the background metered network activity restriction has occurred.
4399 * <p>
4400 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4401 * applies to them.
4402 * <p>
4403 * This is only sent to registered receivers, not manifest receivers.
4404 */
4405 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4406 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4407 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4408
Felipe Lemeecfccea2016-01-25 11:48:04 -08004409 /** @hide */
4410 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004411 @IntDef(flag = false, value = {
4412 RESTRICT_BACKGROUND_STATUS_DISABLED,
4413 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4414 RESTRICT_BACKGROUND_STATUS_ENABLED,
4415 })
Felipe Leme1b103232016-01-22 09:44:57 -08004416 public @interface RestrictBackgroundStatus {
4417 }
4418
4419 private INetworkPolicyManager getNetworkPolicyManager() {
4420 synchronized (this) {
4421 if (mNPManager != null) {
4422 return mNPManager;
4423 }
4424 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4425 .getService(Context.NETWORK_POLICY_SERVICE));
4426 return mNPManager;
4427 }
4428 }
4429
4430 /**
4431 * Determines if the calling application is subject to metered network restrictions while
4432 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004433 *
4434 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4435 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4436 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004437 */
4438 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4439 try {
4440 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4441 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004442 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004443 }
4444 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004445
4446 /**
4447 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004448 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4449 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004450 *
4451 * @return Hash of network watchlist config file. Null if config does not exist.
4452 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004453 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004454 public byte[] getNetworkWatchlistConfigHash() {
4455 try {
4456 return mService.getNetworkWatchlistConfigHash();
4457 } catch (RemoteException e) {
4458 Log.e(TAG, "Unable to get watchlist config hash");
4459 throw e.rethrowFromSystemServer();
4460 }
4461 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004462
4463 /**
4464 * Returns the {@code uid} of the owner of a network connection.
4465 *
4466 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and
4467 * {@code IPPROTO_UDP} currently supported.
4468 * @param local The local {@link InetSocketAddress} of a connection.
4469 * @param remote The remote {@link InetSocketAddress} of a connection.
4470 *
4471 * @return {@code uid} if the connection is found and the app has permission to observe it
4472 * (e.g., if it is associated with the calling VPN app's tunnel) or
4473 * {@link android.os.Process#INVALID_UID} if the connection is not found.
Jeff Vander Stoepb58d3fe2019-02-27 13:31:22 -08004474 * Throws {@link SecurityException} if the caller is not the active VPN for the current user.
4475 * Throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004476 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004477 public int getConnectionOwnerUid(int protocol, @NonNull InetSocketAddress local,
4478 @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004479 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4480 try {
4481 return mService.getConnectionOwnerUid(connectionInfo);
4482 } catch (RemoteException e) {
4483 throw e.rethrowFromSystemServer();
4484 }
4485 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004486
4487 private void printStackTrace() {
4488 if (DEBUG) {
4489 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4490 final StringBuffer sb = new StringBuffer();
4491 for (int i = 3; i < callStack.length; i++) {
4492 final String stackTrace = callStack[i].toString();
4493 if (stackTrace == null || stackTrace.contains("android.os")) {
4494 break;
4495 }
4496 sb.append(" [").append(stackTrace).append("]");
4497 }
4498 Log.d(TAG, "StackLog:" + sb.toString());
4499 }
4500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501}