blob: 1a33166dc15358911c47b3af86e2ea905fc113f8 [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;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080041import android.os.IBinder;
42import android.os.INetworkActivityListener;
43import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070044import android.os.Looper;
45import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070046import android.os.Messenger;
junyulai0c666972019-03-04 22:45:36 +080047import android.os.ParcelFileDescriptor;
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;
junyulai0c666972019-03-04 22:45:36 +080068import java.io.IOException;
69import java.io.UncheckedIOException;
Felipe Leme1b103232016-01-22 09:44:57 -080070import java.lang.annotation.Retention;
71import java.lang.annotation.RetentionPolicy;
Jeremy Kleind42209d2015-12-28 15:11:58 -080072import java.net.InetAddress;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070073import java.net.InetSocketAddress;
junyulai352dc2f2019-01-08 20:04:33 +080074import java.net.Socket;
Hugo Benichidafed3d2017-03-06 09:17:06 +090075import java.util.ArrayList;
Jeremy Kleind42209d2015-12-28 15:11:58 -080076import java.util.HashMap;
Hugo Benichidafed3d2017-03-06 09:17:06 +090077import java.util.List;
78import java.util.Map;
junyulai48eac1d42018-12-27 17:25:29 +080079import java.util.concurrent.Executor;
junyulai7c469172019-01-16 20:23:34 +080080import java.util.concurrent.ExecutorService;
81import java.util.concurrent.Executors;
82import java.util.concurrent.RejectedExecutionException;
Jeremy Kleind42209d2015-12-28 15:11:58 -080083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084/**
85 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060086 * notifies applications when network connectivity changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 * <p>
88 * The primary responsibilities of this class are to:
89 * <ol>
90 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
91 * <li>Send broadcast intents when network connectivity changes</li>
92 * <li>Attempt to "fail over" to another network when connectivity to a network
93 * is lost</li>
94 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
95 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070096 * <li>Provide an API that allows applications to request and select networks for their data
97 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 * </ol>
99 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -0600100@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700101public class ConnectivityManager {
102 private static final String TAG = "ConnectivityManager";
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +0900103 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700106 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 * been established or lost. The NetworkInfo for the affected network is
108 * sent as an extra; it should be consulted to see what kind of
109 * connectivity event occurred.
110 * <p/>
Mark Lu33ec1062016-12-05 10:57:55 -0800111 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
112 * broadcast if they declare the broadcast receiver in their manifest. Apps
113 * will still receive broadcasts if they register their
114 * {@link android.content.BroadcastReceiver} with
115 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
116 * and that context is still valid.
117 * <p/>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 * If this is a connection that was the result of failing over from a
119 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
120 * set to true.
121 * <p/>
122 * For a loss of connectivity, if the connectivity manager is attempting
123 * to connect (or has already connected) to another network, the
124 * NetworkInfo for the new network is also passed as an extra. This lets
125 * any receivers of the broadcast know that they should not necessarily
126 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800127 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 * the failover attempt succeeded (and so there is still overall data
129 * connectivity), or that the failover attempt failed, meaning that all
130 * connectivity has been lost.
131 * <p/>
132 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
133 * is set to {@code true} if there are no connected networks at all.
Chalard Jean054cd162018-02-10 05:33:50 +0900134 *
135 * @deprecated apps should use the more versatile {@link #requestNetwork},
136 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
137 * functions instead for faster and more detailed updates about the network
138 * changes they care about.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800140 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean054cd162018-02-10 05:33:50 +0900141 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 /**
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700145 * A temporary hack until SUPL system can get off the legacy APIS.
146 * They do too many network requests and the long list of apps listening
Chalard Jean4d660112018-06-04 16:52:49 +0900147 * and waking due to the CONNECTIVITY_ACTION broadcast makes it expensive.
148 * Use this broadcast intent instead for SUPL requests.
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700149 * @hide
150 */
151 public static final String CONNECTIVITY_ACTION_SUPL =
152 "android.net.conn.CONNECTIVITY_CHANGE_SUPL";
153
154 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500155 * The device has connected to a network that has presented a captive
156 * portal, which is blocking Internet connectivity. The user was presented
157 * with a notification that network sign in is required,
158 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400159 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500160 * facilitate signing in to the network. This action includes a
161 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
162 * the network presenting the captive portal; all communication with the
163 * captive portal must be done using this {@code Network} object.
164 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400165 * This activity includes a {@link CaptivePortal} extra named
166 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
167 * outcomes of the captive portal sign in to the system:
168 * <ul>
169 * <li> When the app handling this action believes the user has signed in to
170 * the network and the captive portal has been dismissed, the app should
171 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
172 * reevaluate the network. If reevaluation finds the network no longer
173 * subject to a captive portal, the network may become the default active
Chalard Jean4d660112018-06-04 16:52:49 +0900174 * data network.</li>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400175 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500176 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400177 * {@link CaptivePortal#ignoreNetwork}. </li>
178 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500179 */
180 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
181 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
182
183 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 * The lookup key for a {@link NetworkInfo} object. Retrieve with
185 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700186 *
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900187 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
188 * can't accurately represent modern network characteristics.
189 * Please obtain information about networks from the {@link NetworkCapabilities}
190 * or {@link LinkProperties} objects instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700192 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700196 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700197 *
198 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900199 * @deprecated The network type is not rich enough to represent the characteristics
200 * of modern networks. Please use {@link NetworkCapabilities} instead,
201 * in particular the transports.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700202 */
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900203 @Deprecated
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700204 public static final String EXTRA_NETWORK_TYPE = "networkType";
205
206 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 * The lookup key for a boolean that indicates whether a connect event
208 * is for a network to which the connectivity manager was failing over
209 * following a disconnect on another network.
210 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai3822c8a2018-12-13 12:47:51 +0800211 *
212 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 */
junyulai3822c8a2018-12-13 12:47:51 +0800214 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 public static final String EXTRA_IS_FAILOVER = "isFailover";
216 /**
217 * The lookup key for a {@link NetworkInfo} object. This is supplied when
218 * there is another network that it may be possible to connect to. Retrieve with
219 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800220 *
221 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 */
junyulai3822c8a2018-12-13 12:47:51 +0800223 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
225 /**
226 * The lookup key for a boolean that indicates whether there is a
227 * complete lack of connectivity, i.e., no network is available.
228 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
229 */
230 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
231 /**
232 * The lookup key for a string that indicates why an attempt to connect
233 * to a network failed. The string has no particular structure. It is
234 * intended to be used in notifications presented to users. Retrieve
235 * it with {@link android.content.Intent#getStringExtra(String)}.
236 */
237 public static final String EXTRA_REASON = "reason";
238 /**
239 * The lookup key for a string that provides optionally supplied
240 * extra information about the network state. The information
241 * may be passed up from the lower networking layers, and its
242 * meaning may be specific to a particular network type. Retrieve
243 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800244 *
245 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 */
junyulai3822c8a2018-12-13 12:47:51 +0800247 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700249 /**
250 * The lookup key for an int that provides information about
251 * our connection to the internet at large. 0 indicates no connection,
252 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700253 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700254 * {@hide}
255 */
256 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400258 * The lookup key for a {@link CaptivePortal} object included with the
259 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
260 * object can be used to either indicate to the system that the captive
261 * portal has been dismissed or that the user does not want to pursue
262 * signing in to captive portal. Retrieve it with
263 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500264 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400265 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700266
267 /**
268 * Key for passing a URL to the captive portal login activity.
269 */
270 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
271
Paul Jensen25a217c2015-02-27 22:55:47 -0500272 /**
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900273 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
274 * portal login activity.
275 * {@hide}
276 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900277 @SystemApi
278 @TestApi
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900279 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
280 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
281
282 /**
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900283 * Key for passing a user agent string to the captive portal login activity.
284 * {@hide}
285 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900286 @SystemApi
287 @TestApi
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900288 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
289 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
290
291 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700292 * Broadcast action to indicate the change of data activity status
293 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800294 * The network becomes active when data transmission is started, or
295 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700296 * {@hide}
297 */
298 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean4d660112018-06-04 16:52:49 +0900299 public static final String ACTION_DATA_ACTIVITY_CHANGE =
300 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700301 /**
302 * The lookup key for an enum that indicates the network device type on which this data activity
303 * change happens.
304 * {@hide}
305 */
306 public static final String EXTRA_DEVICE_TYPE = "deviceType";
307 /**
308 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
309 * it is actively sending or receiving data and {@code false} means it is idle.
310 * {@hide}
311 */
312 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700313 /**
314 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
315 * {@hide}
316 */
317 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700318
319 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 * Broadcast Action: The setting for background data usage has changed
321 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
322 * <p>
323 * If an application uses the network in the background, it should listen
324 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700325 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800326 * <p>
327 *
328 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
329 * of background data depends on several combined factors, and
330 * this broadcast is no longer sent. Instead, when background
331 * data is unavailable, {@link #getActiveNetworkInfo()} will now
332 * appear disconnected. During first boot after a platform
333 * upgrade, this broadcast will be sent once if
334 * {@link #getBackgroundDataSetting()} was {@code false} before
335 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 */
337 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800338 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
340 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
341
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700342 /**
343 * Broadcast Action: The network connection may not be good
344 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
345 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
346 * the network and it's condition.
347 * @hide
348 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800349 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100350 @UnsupportedAppUsage
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700351 public static final String INET_CONDITION_ACTION =
352 "android.net.conn.INET_CONDITION_ACTION";
353
Robert Greenwalt42acef32009-08-12 16:08:25 -0700354 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800355 * Broadcast Action: A tetherable connection has come or gone.
356 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline8351faa2017-04-17 16:47:23 +0900357 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
358 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800359 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
360 * the current state of tethering. Each include a list of
361 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800362 * @hide
363 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800364 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100365 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800366 public static final String ACTION_TETHER_STATE_CHANGED =
367 "android.net.conn.TETHER_STATE_CHANGED";
368
369 /**
370 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800371 * gives a String[] listing all the interfaces configured for
372 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800373 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100374 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800375 public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800376
377 /**
378 * @hide
Erik Kline8351faa2017-04-17 16:47:23 +0900379 * gives a String[] listing all the interfaces currently in local-only
380 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800381 */
Erik Kline8351faa2017-04-17 16:47:23 +0900382 public static final String EXTRA_ACTIVE_LOCAL_ONLY = "localOnlyArray";
383
384 /**
385 * @hide
386 * gives a String[] listing all the interfaces currently tethered
387 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
388 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100389 @UnsupportedAppUsage
Erik Kline8351faa2017-04-17 16:47:23 +0900390 public static final String EXTRA_ACTIVE_TETHER = "tetherArray";
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800391
392 /**
393 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800394 * gives a String[] listing all the interfaces we tried to tether and
395 * failed. Use {@link #getLastTetherError} to find the error code
396 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800397 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100398 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800399 public static final String EXTRA_ERRORED_TETHER = "erroredArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800400
401 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800402 * Broadcast Action: The captive portal tracker has finished its test.
403 * Sent only while running Setup Wizard, in lieu of showing a user
404 * notification.
405 * @hide
406 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800407 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800408 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
409 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
410 /**
411 * The lookup key for a boolean that indicates whether a captive portal was detected.
412 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
413 * @hide
414 */
415 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
416
417 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900418 * Action used to display a dialog that asks the user whether to connect to a network that is
419 * not validated. This intent is used to start the dialog in settings via startActivity.
420 *
421 * @hide
422 */
423 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
424
425 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900426 * Action used to display a dialog that asks the user whether to avoid a network that is no
427 * longer validated. This intent is used to start the dialog in settings via startActivity.
428 *
429 * @hide
430 */
431 public static final String ACTION_PROMPT_LOST_VALIDATION =
432 "android.net.conn.PROMPT_LOST_VALIDATION";
433
434 /**
lucasline252a742019-03-12 13:08:03 +0800435 * Action used to display a dialog that asks the user whether to stay connected to a network
436 * that has not validated. This intent is used to start the dialog in settings via
437 * startActivity.
438 *
439 * @hide
440 */
441 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
442 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
443
444 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800445 * Invalid tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900446 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800447 * @hide
448 */
449 public static final int TETHERING_INVALID = -1;
450
451 /**
452 * Wifi tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900453 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800454 * @hide
455 */
456 @SystemApi
457 public static final int TETHERING_WIFI = 0;
458
459 /**
460 * USB tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900461 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800462 * @hide
463 */
464 @SystemApi
465 public static final int TETHERING_USB = 1;
466
467 /**
468 * Bluetooth tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900469 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800470 * @hide
471 */
472 @SystemApi
473 public static final int TETHERING_BLUETOOTH = 2;
474
475 /**
Jimmy Chenbcd86d02019-07-15 18:03:23 +0800476 * Wifi P2p tethering type.
477 * Wifi P2p tethering is set through events automatically, and don't
478 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
479 * @hide
480 */
481 public static final int TETHERING_WIFI_P2P = 3;
482
483 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800484 * Extra used for communicating with the TetherService. Includes the type of tethering to
485 * enable if any.
486 * @hide
487 */
488 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
489
490 /**
491 * Extra used for communicating with the TetherService. Includes the type of tethering for
492 * which to cancel provisioning.
493 * @hide
494 */
495 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
496
497 /**
498 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
499 * provisioning.
500 * @hide
501 */
502 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
503
504 /**
505 * Tells the TetherService to run a provision check now.
506 * @hide
507 */
508 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
509
510 /**
511 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
512 * which will receive provisioning results. Can be left empty.
513 * @hide
514 */
515 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
516
517 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800518 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700519 * @hide
520 */
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900521 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700522 public static final int TYPE_NONE = -1;
523
524 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900525 * A Mobile data connection. Devices may support more than one.
526 *
527 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
528 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
529 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700530 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900531 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700532 public static final int TYPE_MOBILE = 0;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900533
Robert Greenwalt42acef32009-08-12 16:08:25 -0700534 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900535 * A WIFI data connection. Devices may support more than one.
536 *
537 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
538 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
539 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700540 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900541 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700542 public static final int TYPE_WIFI = 1;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900543
Robert Greenwalt42acef32009-08-12 16:08:25 -0700544 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800545 * An MMS-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 * Multimedia Messaging Service servers.
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_MMS} 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_MMS = 2;
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 SUPL-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 used by applications needing to talk to the carrier's
561 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900562 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900563 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900564 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900565 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700566 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700567 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700568 public static final int TYPE_MOBILE_SUPL = 3;
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 DUN-specific Mobile data connection. This network type may use the
572 * same network interface as {@link #TYPE_MOBILE} or it may use a different
573 * one. This is sometimes by the system when setting up an upstream connection
574 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900575 *
576 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
577 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
578 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700579 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900580 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700581 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900582
Robert Greenwalt42acef32009-08-12 16:08:25 -0700583 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800584 * A High Priority Mobile data connection. This network type uses the
585 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900586 * is different.
587 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900588 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
589 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
590 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700591 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700592 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700593 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900594
jsh8214deb2010-03-11 15:04:43 -0800595 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900596 * A WiMAX data connection.
597 *
598 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
599 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
600 * appropriate network. {@see NetworkCapabilities} for supported transports.
jsh8214deb2010-03-11 15:04:43 -0800601 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900602 @Deprecated
jsh8214deb2010-03-11 15:04:43 -0800603 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800604
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800605 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900606 * A Bluetooth data connection.
607 *
608 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
609 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
610 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800611 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900612 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800613 public static final int TYPE_BLUETOOTH = 7;
614
Robert Greenwalt60810842011-04-22 15:28:18 -0700615 /**
616 * Dummy data connection. This should not be used on shipping devices.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900617 * @deprecated This is not used any more.
Robert Greenwalt60810842011-04-22 15:28:18 -0700618 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900619 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800620 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800621
Robert Greenwalt60810842011-04-22 15:28:18 -0700622 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900623 * An Ethernet data connection.
624 *
625 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
626 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
627 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt60810842011-04-22 15:28:18 -0700628 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900629 @Deprecated
Robert Greenwalte12aec92011-01-28 14:48:37 -0800630 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700631
Wink Saville9d7d6282011-03-12 14:52:01 -0800632 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800633 * Over the air Administration.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900634 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800635 * {@hide}
636 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900637 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900638 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Saville9d7d6282011-03-12 14:52:01 -0800639 public static final int TYPE_MOBILE_FOTA = 10;
640
641 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800642 * IP Multimedia Subsystem.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900643 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800644 * {@hide}
645 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900646 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100647 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800648 public static final int TYPE_MOBILE_IMS = 11;
649
650 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800651 * Carrier Branded Services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900652 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800653 * {@hide}
654 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900655 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900656 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Saville9d7d6282011-03-12 14:52:01 -0800657 public static final int TYPE_MOBILE_CBS = 12;
658
repo syncaea743a2011-07-29 23:55:49 -0700659 /**
660 * A Wi-Fi p2p connection. Only requesting processes will have access to
661 * the peers connected.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900662 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncaea743a2011-07-29 23:55:49 -0700663 * {@hide}
664 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900665 @Deprecated
Chalard Jean2253ff92019-06-17 19:46:34 +0900666 @UnsupportedAppUsage
repo syncaea743a2011-07-29 23:55:49 -0700667 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800668
Wink Saville5e56bc52013-07-29 15:00:57 -0700669 /**
670 * The network to use for initially attaching to the network
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900671 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville5e56bc52013-07-29 15:00:57 -0700672 * {@hide}
673 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900674 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100675 @UnsupportedAppUsage
Wink Saville5e56bc52013-07-29 15:00:57 -0700676 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700677
Lorenzo Colittie285b432015-04-23 15:32:42 +0900678 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700679 * Emergency PDN connection for emergency services. This
680 * may include IMS and MMS in emergency situations.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900681 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram3e0e3bc2014-06-26 11:03:44 -0700682 * {@hide}
683 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900684 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900685 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram3e0e3bc2014-06-26 11:03:44 -0700686 public static final int TYPE_MOBILE_EMERGENCY = 15;
687
Hui Lu1c5624a2014-01-15 11:05:36 -0500688 /**
689 * The network that uses proxy to achieve connectivity.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900690 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu1c5624a2014-01-15 11:05:36 -0500691 * {@hide}
692 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900693 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100694 @UnsupportedAppUsage
Hui Lu1c5624a2014-01-15 11:05:36 -0500695 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700696
Robert Greenwalt8283f882014-07-07 17:09:01 -0700697 /**
698 * A virtual network using one or more native bearers.
699 * It may or may not be providing security services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900700 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700701 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900702 @Deprecated
Robert Greenwalt8283f882014-07-07 17:09:01 -0700703 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500704
Benedict Wong89ce5e32018-11-14 17:40:55 -0800705 /**
706 * A network that is exclusively meant to be used for testing
707 *
708 * @deprecated Use {@link NetworkCapabilities} instead.
709 * @hide
710 */
711 @Deprecated
712 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700713
714 /** {@hide} */
Benedict Wong89ce5e32018-11-14 17:40:55 -0800715 public static final int MAX_RADIO_TYPE = TYPE_TEST;
716
717 /** {@hide} */
718 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719
Hugo Benichi16f0a942017-06-20 14:07:59 +0900720 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
721
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800722 /**
723 * If you want to set the default network preference,you can directly
724 * change the networkAttributes array in framework's config.xml.
725 *
726 * @deprecated Since we support so many more networks now, the single
727 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800728 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800729 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800730 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800731 * from an App.
732 */
733 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
735
Jeff Sharkey625239a2012-09-26 22:03:49 -0700736 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700737 * @hide
738 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900739 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700740
Paul Jensen5d59e782014-07-11 12:28:19 -0400741 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900742 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
743 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean4d660112018-06-04 16:52:49 +0900744 * registered from those that were already unregistered.
Hugo Benichi31c176d2017-06-17 13:14:12 +0900745 * @hide
746 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900747 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900748 new NetworkRequest.Builder().clearCapabilities().build();
749
750 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400751 * A NetID indicating no Network is selected.
752 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
753 * @hide
754 */
755 public static final int NETID_UNSET = 0;
756
Erik Kline4d092232017-10-30 15:29:44 +0900757 /**
758 * Private DNS Mode values.
759 *
760 * The "private_dns_mode" global setting stores a String value which is
761 * expected to be one of the following.
762 */
763
764 /**
765 * @hide
766 */
767 public static final String PRIVATE_DNS_MODE_OFF = "off";
768 /**
769 * @hide
770 */
771 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
772 /**
773 * @hide
774 */
775 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
776 /**
777 * The default Private DNS mode.
778 *
779 * This may change from release to release or may become dependent upon
780 * the capabilities of the underlying platform.
781 *
782 * @hide
783 */
Erik Kline19841792018-05-16 16:41:57 +0900784 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline4d092232017-10-30 15:29:44 +0900785
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900786 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700787 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500788 /**
789 * A kludge to facilitate static access where a Context pointer isn't available, like in the
790 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
791 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
792 * methods that take a Context argument.
793 */
794 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900796 private final Context mContext;
797
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800798 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800799 private INetworkPolicyManager mNPManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800800
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800801 /**
802 * Tests if a given integer represents a valid network type.
803 * @param networkType the type to be tested
804 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400805 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
806 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800807 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700808 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700809 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900810 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 }
812
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800813 /**
814 * Returns a non-localized string representing a given network type.
815 * ONLY used for debugging output.
816 * @param type the type needing naming
817 * @return a String for the given type, or a string version of the type ("87")
818 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900819 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800820 * {@hide}
821 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900822 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100823 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700824 public static String getNetworkTypeName(int type) {
825 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900826 case TYPE_NONE:
827 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700828 case TYPE_MOBILE:
829 return "MOBILE";
830 case TYPE_WIFI:
831 return "WIFI";
832 case TYPE_MOBILE_MMS:
833 return "MOBILE_MMS";
834 case TYPE_MOBILE_SUPL:
835 return "MOBILE_SUPL";
836 case TYPE_MOBILE_DUN:
837 return "MOBILE_DUN";
838 case TYPE_MOBILE_HIPRI:
839 return "MOBILE_HIPRI";
840 case TYPE_WIMAX:
841 return "WIMAX";
842 case TYPE_BLUETOOTH:
843 return "BLUETOOTH";
844 case TYPE_DUMMY:
845 return "DUMMY";
846 case TYPE_ETHERNET:
847 return "ETHERNET";
848 case TYPE_MOBILE_FOTA:
849 return "MOBILE_FOTA";
850 case TYPE_MOBILE_IMS:
851 return "MOBILE_IMS";
852 case TYPE_MOBILE_CBS:
853 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700854 case TYPE_WIFI_P2P:
855 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700856 case TYPE_MOBILE_IA:
857 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700858 case TYPE_MOBILE_EMERGENCY:
859 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500860 case TYPE_PROXY:
861 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900862 case TYPE_VPN:
863 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700864 default:
865 return Integer.toString(type);
866 }
867 }
868
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800869 /**
870 * Checks if a given type uses the cellular data connection.
871 * This should be replaced in the future by a network property.
872 * @param networkType the type to check
873 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900874 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800875 * {@hide}
876 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900877 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900878 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700879 public static boolean isNetworkTypeMobile(int networkType) {
880 switch (networkType) {
881 case TYPE_MOBILE:
882 case TYPE_MOBILE_MMS:
883 case TYPE_MOBILE_SUPL:
884 case TYPE_MOBILE_DUN:
885 case TYPE_MOBILE_HIPRI:
886 case TYPE_MOBILE_FOTA:
887 case TYPE_MOBILE_IMS:
888 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700889 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700890 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700891 return true;
892 default:
893 return false;
894 }
895 }
896
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800897 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700898 * Checks if the given network type is backed by a Wi-Fi radio.
899 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900900 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700901 * @hide
902 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900903 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700904 public static boolean isNetworkTypeWifi(int networkType) {
905 switch (networkType) {
906 case TYPE_WIFI:
907 case TYPE_WIFI_P2P:
908 return true;
909 default:
910 return false;
911 }
912 }
913
914 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800915 * Specifies the preferred network type. When the device has more
916 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800917 *
918 * @param preference the network type to prefer over all others. It is
919 * unspecified what happens to the old preferred network in the
920 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700921 * @deprecated Functionality has been removed as it no longer makes sense,
922 * with many more than two networks - we'd need an array to express
923 * preference. Instead we use dynamic network properties of
924 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800925 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700926 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 }
929
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800930 /**
931 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800932 *
933 * @return an integer representing the preferred network type
934 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700935 * @deprecated Functionality has been removed as it no longer makes sense,
936 * with many more than two networks - we'd need an array to express
937 * preference. Instead we use dynamic network properties of
938 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800939 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700940 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600941 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700943 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 }
945
Scott Main671644c2011-10-06 19:02:28 -0700946 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800947 * Returns details about the currently active default data network. When
948 * connected, this network is the default route for outgoing connections.
949 * You should always check {@link NetworkInfo#isConnected()} before initiating
950 * network traffic. This may return {@code null} when there is no default
951 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900952 * Note that if the default network is a VPN, this method will return the
953 * NetworkInfo for one of its underlying networks instead, or null if the
954 * VPN agent did not specify any. Apps interested in learning about VPNs
955 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800956 *
957 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500958 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800959 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700960 */
junyulai3822c8a2018-12-13 12:47:51 +0800961 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600962 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900963 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 public NetworkInfo getActiveNetworkInfo() {
965 try {
966 return mService.getActiveNetworkInfo();
967 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700968 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 }
970 }
971
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800972 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500973 * Returns a {@link Network} object corresponding to the currently active
974 * default data network. In the event that the current active default data
975 * network disconnects, the returned {@code Network} object will no longer
976 * be usable. This will return {@code null} when there is no default
977 * network.
978 *
979 * @return a {@link Network} object for the current default network or
980 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500981 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600982 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900983 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -0500984 public Network getActiveNetwork() {
985 try {
986 return mService.getActiveNetwork();
987 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700988 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500989 }
990 }
991
992 /**
Robin Leed2baf792016-03-24 12:07:00 +0000993 * Returns a {@link Network} object corresponding to the currently active
994 * default data network for a specific UID. In the event that the default data
995 * network disconnects, the returned {@code Network} object will no longer
996 * be usable. This will return {@code null} when there is no default
997 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +0000998 *
999 * @return a {@link Network} object for the current default network for the
1000 * given UID or {@code null} if no default network is currently active
1001 *
1002 * @hide
1003 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001004 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001005 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +00001006 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001007 return getActiveNetworkForUid(uid, false);
1008 }
1009
1010 /** {@hide} */
1011 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001012 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001013 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001014 } catch (RemoteException e) {
1015 throw e.rethrowFromSystemServer();
1016 }
1017 }
1018
1019 /**
Charles He36738632017-05-15 17:07:18 +01001020 * Checks if a VPN app supports always-on mode.
1021 *
1022 * In order to support the always-on feature, an app has to
1023 * <ul>
1024 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +01001025 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
1026 * meta-data field.
Charles He36738632017-05-15 17:07:18 +01001027 * </ul>
1028 *
1029 * @param userId The identifier of the user for whom the VPN app is installed.
1030 * @param vpnPackage The canonical package name of the VPN app.
1031 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
1032 * @hide
1033 */
1034 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1035 try {
1036 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1037 } catch (RemoteException e) {
1038 throw e.rethrowFromSystemServer();
1039 }
1040 }
1041
1042 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001043 * Configures an always-on VPN connection through a specific application.
1044 * This connection is automatically granted and persisted after a reboot.
1045 *
1046 * <p>The designated package should declare a {@link VpnService} in its
1047 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1048 * otherwise the call will fail.
1049 *
1050 * @param userId The identifier of the user to set an always-on VPN for.
1051 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1052 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001053 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1054 * {@code false} otherwise.
Pavel Grafova462bcb2019-01-25 08:50:06 +00001055 * @param lockdownWhitelist The list of packages that are allowed to access network directly
1056 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
1057 * this method must be called when a package that should be whitelisted is installed or
1058 * uninstalled.
Robin Lee244ce8e2016-01-05 18:03:46 +00001059 * @return {@code true} if the package is set as always-on VPN controller;
1060 * {@code false} otherwise.
1061 * @hide
1062 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001063 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leedc679712016-05-03 13:23:03 +01001064 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001065 boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001066 try {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001067 return mService.setAlwaysOnVpnPackage(
1068 userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
Robin Lee244ce8e2016-01-05 18:03:46 +00001069 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001070 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001071 }
1072 }
1073
Pavel Grafova462bcb2019-01-25 08:50:06 +00001074 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001075 * Returns the package name of the currently set always-on VPN application.
1076 * If there is no always-on VPN set, or the VPN is provided by the system instead
1077 * of by an app, {@code null} will be returned.
1078 *
1079 * @return Package name of VPN controller responsible for always-on VPN,
1080 * or {@code null} if none is set.
1081 * @hide
1082 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001083 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee244ce8e2016-01-05 18:03:46 +00001084 public String getAlwaysOnVpnPackageForUser(int userId) {
1085 try {
1086 return mService.getAlwaysOnVpnPackage(userId);
1087 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001088 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001089 }
1090 }
1091
1092 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001093 * @return whether always-on VPN is in lockdown mode.
1094 *
1095 * @hide
1096 **/
1097 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1098 public boolean isVpnLockdownEnabled(int userId) {
1099 try {
1100 return mService.isVpnLockdownEnabled(userId);
1101 } catch (RemoteException e) {
1102 throw e.rethrowFromSystemServer();
1103 }
1104
1105 }
1106
1107 /**
1108 * @return the list of packages that are allowed to access network when always-on VPN is in
1109 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1110 *
1111 * @hide
1112 **/
1113 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1114 public List<String> getVpnLockdownWhitelist(int userId) {
1115 try {
1116 return mService.getVpnLockdownWhitelist(userId);
1117 } catch (RemoteException e) {
1118 throw e.rethrowFromSystemServer();
1119 }
1120 }
1121
1122 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001123 * Returns details about the currently active default data network
1124 * for a given uid. This is for internal use only to avoid spying
1125 * other apps.
1126 *
1127 * @return a {@link NetworkInfo} object for the current default network
1128 * for the given uid or {@code null} if no default network is
1129 * available for the specified uid.
1130 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001131 * {@hide}
1132 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001133 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001134 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001135 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001136 return getActiveNetworkInfoForUid(uid, false);
1137 }
1138
1139 /** {@hide} */
1140 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001141 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001142 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001143 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001144 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001145 }
1146 }
1147
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001148 /**
1149 * Returns connection status information about a particular
1150 * network type.
1151 *
1152 * @param networkType integer specifying which networkType in
1153 * which you're interested.
1154 * @return a {@link NetworkInfo} object for the requested
1155 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001156 * supported by the device. If {@code networkType} is
1157 * TYPE_VPN and a VPN is active for the calling app,
1158 * then this method will try to return one of the
1159 * underlying networks for the VPN or null if the
1160 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001161 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001162 * @deprecated This method does not support multiple connected networks
1163 * of the same type. Use {@link #getAllNetworks} and
1164 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001165 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001166 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001167 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001168 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 public NetworkInfo getNetworkInfo(int networkType) {
1170 try {
1171 return mService.getNetworkInfo(networkType);
1172 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001173 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 }
1175 }
1176
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001177 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001178 * Returns connection status information about a particular
1179 * Network.
1180 *
1181 * @param network {@link Network} specifying which network
1182 * in which you're interested.
1183 * @return a {@link NetworkInfo} object for the requested
1184 * network or {@code null} if the {@code Network}
1185 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001186 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001187 */
junyulai3822c8a2018-12-13 12:47:51 +08001188 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001189 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001190 @Nullable
1191 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001192 return getNetworkInfoForUid(network, Process.myUid(), false);
1193 }
1194
1195 /** {@hide} */
1196 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001197 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001198 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001199 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001200 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001201 }
1202 }
1203
1204 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001205 * Returns connection status information about all network
1206 * types supported by the device.
1207 *
1208 * @return an array of {@link NetworkInfo} objects. Check each
1209 * {@link NetworkInfo#getType} for which type each applies.
1210 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001211 * @deprecated This method does not support multiple connected networks
1212 * of the same type. Use {@link #getAllNetworks} and
1213 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001214 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001215 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001216 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001217 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 public NetworkInfo[] getAllNetworkInfo() {
1219 try {
1220 return mService.getAllNetworkInfo();
1221 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001222 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 }
1224 }
1225
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001226 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001227 * Returns the {@link Network} object currently serving a given type, or
1228 * null if the given type is not connected.
1229 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001230 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001231 * @deprecated This method does not support multiple connected networks
1232 * of the same type. Use {@link #getAllNetworks} and
1233 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001234 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001235 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001236 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001237 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001238 public Network getNetworkForType(int networkType) {
1239 try {
1240 return mService.getNetworkForType(networkType);
1241 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001242 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001243 }
1244 }
1245
1246 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001247 * Returns an array of all {@link Network} currently tracked by the
1248 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001249 *
1250 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001251 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001252 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001253 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001254 public Network[] getAllNetworks() {
1255 try {
1256 return mService.getAllNetworks();
1257 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001258 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001259 }
1260 }
1261
1262 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001263 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001264 * the Networks that applications run by the given user will use by default.
1265 * @hide
1266 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001267 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001268 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1269 try {
1270 return mService.getDefaultNetworkCapabilitiesForUser(userId);
1271 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001272 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001273 }
1274 }
1275
1276 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001277 * Returns the IP information for the current default network.
1278 *
1279 * @return a {@link LinkProperties} object describing the IP info
1280 * for the current default network, or {@code null} if there
1281 * is no current default network.
1282 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001283 * {@hide}
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001284 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1285 * value of {@link #getActiveNetwork()} instead. In particular,
1286 * this method will return non-null LinkProperties even if the
1287 * app is blocked by policy from using this network.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001288 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001289 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001290 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001291 public LinkProperties getActiveLinkProperties() {
1292 try {
1293 return mService.getActiveLinkProperties();
1294 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001295 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001296 }
1297 }
1298
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001299 /**
1300 * Returns the IP information for a given network type.
1301 *
1302 * @param networkType the network type of interest.
1303 * @return a {@link LinkProperties} object describing the IP info
1304 * for the given networkType, or {@code null} if there is
1305 * no current default network.
1306 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001307 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001308 * @deprecated This method does not support multiple connected networks
1309 * of the same type. Use {@link #getAllNetworks},
1310 * {@link #getNetworkInfo(android.net.Network)}, and
1311 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001312 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001313 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001314 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09001315 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001316 public LinkProperties getLinkProperties(int networkType) {
1317 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001318 return mService.getLinkPropertiesForType(networkType);
1319 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001320 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001321 }
1322 }
1323
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001324 /**
1325 * Get the {@link LinkProperties} for the given {@link Network}. This
1326 * will return {@code null} if the network is unknown.
1327 *
1328 * @param network The {@link Network} object identifying the network in question.
1329 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001330 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001331 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001332 @Nullable
1333 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001334 try {
1335 return mService.getLinkProperties(network);
1336 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001337 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001338 }
1339 }
1340
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001341 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001342 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001343 * will return {@code null} if the network is unknown.
1344 *
1345 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001346 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001347 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001348 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001349 @Nullable
1350 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001351 try {
1352 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001353 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001354 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001355 }
1356 }
1357
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001358 /**
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001359 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainib7c24872016-01-04 12:16:14 -08001360 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1361 * portal is present.
1362 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1363 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1364 *
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001365 * The system network validation may be using different strategies to detect captive portals,
1366 * so this method does not necessarily return a URL used by the system. It only returns a URL
1367 * that may be relevant for other components trying to detect captive portals.
Udam Sainib7c24872016-01-04 12:16:14 -08001368 * @hide
1369 */
1370 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07001371 @RequiresPermission(android.Manifest.permission.LOCAL_MAC_ADDRESS)
Udam Sainib7c24872016-01-04 12:16:14 -08001372 public String getCaptivePortalServerUrl() {
1373 try {
1374 return mService.getCaptivePortalServerUrl();
1375 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001376 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001377 }
1378 }
1379
1380 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 * Tells the underlying networking system that the caller wants to
1382 * begin using the named feature. The interpretation of {@code feature}
1383 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001384 *
1385 * <p>This method requires the caller to hold either the
1386 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1387 * or the ability to modify system settings as determined by
1388 * {@link android.provider.Settings.System#canWrite}.</p>
1389 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 * @param networkType specifies which network the request pertains to
1391 * @param feature the name of the feature to be used
1392 * @return an integer value representing the outcome of the request.
1393 * The interpretation of this value is specific to each networking
1394 * implementation+feature combination, except that the value {@code -1}
1395 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001396 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001397 * @deprecated Deprecated in favor of the cleaner
1398 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001399 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001400 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001401 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001403 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001405 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001406 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1407 if (netCap == null) {
1408 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1409 feature);
1410 return PhoneConstants.APN_REQUEST_FAILED;
1411 }
1412
1413 NetworkRequest request = null;
1414 synchronized (sLegacyRequests) {
1415 LegacyRequest l = sLegacyRequests.get(netCap);
1416 if (l != null) {
1417 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1418 renewRequestLocked(l);
1419 if (l.currentNetwork != null) {
1420 return PhoneConstants.APN_ALREADY_ACTIVE;
1421 } else {
1422 return PhoneConstants.APN_REQUEST_STARTED;
1423 }
1424 }
1425
1426 request = requestNetworkForFeatureLocked(netCap);
1427 }
1428 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001429 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001430 return PhoneConstants.APN_REQUEST_STARTED;
1431 } else {
1432 Log.d(TAG, " request Failed");
1433 return PhoneConstants.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435 }
1436
1437 /**
1438 * Tells the underlying networking system that the caller is finished
1439 * using the named feature. The interpretation of {@code feature}
1440 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001441 *
1442 * <p>This method requires the caller to hold either the
1443 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1444 * or the ability to modify system settings as determined by
1445 * {@link android.provider.Settings.System#canWrite}.</p>
1446 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 * @param networkType specifies which network the request pertains to
1448 * @param feature the name of the feature that is no longer needed
1449 * @return an integer value representing the outcome of the request.
1450 * The interpretation of this value is specific to each networking
1451 * implementation+feature combination, except that the value {@code -1}
1452 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001453 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001454 * @deprecated Deprecated in favor of the cleaner
1455 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001456 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001457 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001458 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001460 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001462 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001463 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1464 if (netCap == null) {
1465 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1466 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 return -1;
1468 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001469
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001470 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001471 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001472 }
1473 return 1;
1474 }
1475
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001476 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001477 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1478 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001479 switch (feature) {
1480 case "enableCBS":
1481 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1482 case "enableDUN":
1483 case "enableDUNAlways":
1484 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1485 case "enableFOTA":
1486 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1487 case "enableHIPRI":
1488 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1489 case "enableIMS":
1490 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1491 case "enableMMS":
1492 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1493 case "enableSUPL":
1494 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1495 default:
1496 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001497 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001498 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1499 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001500 }
1501 return null;
1502 }
1503
Robert Greenwalt06314e42014-10-29 14:04:06 -07001504 /**
1505 * Guess what the network request was trying to say so that the resulting
1506 * network is accessible via the legacy (deprecated) API such as
1507 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001508 *
1509 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001510 * capability but ignore things such as networkSpecifier.
1511 * If the request has more than one transport or capability it doesn't
1512 * match the old legacy requests (they selected only single transport/capability)
1513 * so this function cannot map the request to a single legacy type and
1514 * the resulting network will not be available to the legacy APIs.
1515 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001516 * This code is only called from the requestNetwork API (L and above).
1517 *
1518 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1519 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1520 * do this for SUPL requests, which are the only ones that we know need it. If
1521 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1522 * compatibility we can send them:
1523 *
1524 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1525 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1526 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001527 * TODO - This should be removed when the legacy APIs are removed.
1528 */
Ye Wenb87875e2014-07-21 14:19:01 -07001529 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1530 if (netCap == null) {
1531 return TYPE_NONE;
1532 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001533
Ye Wenb87875e2014-07-21 14:19:01 -07001534 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1535 return TYPE_NONE;
1536 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001537
Lifu Tang30f95a72016-01-07 23:20:38 -08001538 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001539 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1540 // NOTE: if this causes app breakage, we should not just comment out this early return;
1541 // instead, we should make this early return conditional on the requesting app's target
1542 // SDK version, as described in the comment above.
1543 return TYPE_NONE;
1544 }
1545
Robert Greenwalt06314e42014-10-29 14:04:06 -07001546 String type = null;
1547 int result = TYPE_NONE;
1548
Ye Wenb87875e2014-07-21 14:19:01 -07001549 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001550 type = "enableCBS";
1551 result = TYPE_MOBILE_CBS;
1552 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1553 type = "enableIMS";
1554 result = TYPE_MOBILE_IMS;
1555 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1556 type = "enableFOTA";
1557 result = TYPE_MOBILE_FOTA;
1558 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1559 type = "enableDUN";
1560 result = TYPE_MOBILE_DUN;
1561 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001562 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001563 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001564 // back out this hack for mms as they no longer need this and it's causing
1565 // device slowdowns - b/23350688 (note, supl still needs this)
1566 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1567 // type = "enableMMS";
1568 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001569 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1570 type = "enableHIPRI";
1571 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001572 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001573 if (type != null) {
1574 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1575 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1576 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001577 }
1578 }
1579 return TYPE_NONE;
1580 }
1581
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001582 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001583 if (netCap == null) return TYPE_NONE;
1584 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1585 return TYPE_MOBILE_CBS;
1586 }
1587 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1588 return TYPE_MOBILE_IMS;
1589 }
1590 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1591 return TYPE_MOBILE_FOTA;
1592 }
1593 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1594 return TYPE_MOBILE_DUN;
1595 }
1596 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1597 return TYPE_MOBILE_SUPL;
1598 }
1599 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1600 return TYPE_MOBILE_MMS;
1601 }
1602 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1603 return TYPE_MOBILE_HIPRI;
1604 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001605 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1606 return TYPE_WIFI_P2P;
1607 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001608 return TYPE_NONE;
1609 }
1610
1611 private static class LegacyRequest {
1612 NetworkCapabilities networkCapabilities;
1613 NetworkRequest networkRequest;
1614 int expireSequenceNumber;
1615 Network currentNetwork;
1616 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001617
1618 private void clearDnsBinding() {
1619 if (currentNetwork != null) {
1620 currentNetwork = null;
1621 setProcessDefaultNetworkForHostResolution(null);
1622 }
1623 }
1624
Robert Greenwalt6078b502014-06-11 16:05:07 -07001625 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001626 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001627 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001628 currentNetwork = network;
1629 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001630 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001631 }
1632 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001633 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001634 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001635 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1636 }
1637 };
1638 }
1639
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001640 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001641 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1642 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001643
1644 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1645 synchronized (sLegacyRequests) {
1646 LegacyRequest l = sLegacyRequests.get(netCap);
1647 if (l != null) return l.networkRequest;
1648 }
1649 return null;
1650 }
1651
1652 private void renewRequestLocked(LegacyRequest l) {
1653 l.expireSequenceNumber++;
1654 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1655 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1656 }
1657
1658 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1659 int ourSeqNum = -1;
1660 synchronized (sLegacyRequests) {
1661 LegacyRequest l = sLegacyRequests.get(netCap);
1662 if (l == null) return;
1663 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001664 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001665 }
1666 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1667 }
1668
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001669 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001670 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1671 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001672 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001673 try {
1674 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001675 } catch (RemoteException e) {
1676 throw e.rethrowFromSystemServer();
1677 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001678 LegacyRequest l = new LegacyRequest();
1679 l.networkCapabilities = netCap;
1680 l.delay = delay;
1681 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001682 l.networkRequest = sendRequestForNetwork(
1683 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001684 if (l.networkRequest == null) return null;
1685 sLegacyRequests.put(netCap, l);
1686 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1687 return l.networkRequest;
1688 }
1689
1690 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1691 if (delay >= 0) {
1692 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001693 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001694 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1695 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001696 }
1697 }
1698
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001699 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001700 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1701 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001702 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001703 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001704 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001705 if (l == null) return false;
1706 unregisterNetworkCallback(l.networkCallback);
1707 l.clearDnsBinding();
1708 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
1710
Erik Kline35bf06c2017-01-26 18:08:28 +09001711 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1712 static {
1713 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1714 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1715 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1716 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1717 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1718 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1719 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1720 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1721 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1722 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1723 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1724 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1725 }
1726
1727 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1728 static {
1729 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1730 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1731 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1732 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1733 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1734 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1735 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1736 }
1737
1738 /**
1739 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1740 * instance suitable for registering a request or callback. Throws an
1741 * IllegalArgumentException if no mapping from the legacy type to
1742 * NetworkCapabilities is known.
1743 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001744 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1745 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001746 * @hide
1747 */
1748 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1749 final NetworkCapabilities nc = new NetworkCapabilities();
1750
1751 // Map from type to transports.
1752 final int NOT_FOUND = -1;
1753 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001754 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001755 nc.addTransportType(transport);
1756
1757 // Map from type to capabilities.
1758 nc.addCapability(sLegacyTypeToCapability.get(
1759 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1760 nc.maybeMarkCapabilitiesRestricted();
1761 return nc;
1762 }
1763
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001764 /** @hide */
1765 public static class PacketKeepaliveCallback {
Artur Satayev751e5512019-11-15 19:12:49 +00001766 @UnsupportedAppUsage
1767 public PacketKeepaliveCallback() {
1768 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001769 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001770 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001771 public void onStarted() {}
1772 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001773 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001774 public void onStopped() {}
1775 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001776 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001777 public void onError(int error) {}
1778 }
1779
1780 /**
1781 * Allows applications to request that the system periodically send specific packets on their
1782 * behalf, using hardware offload to save battery power.
1783 *
1784 * To request that the system send keepalives, call one of the methods that return a
1785 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1786 * passing in a non-null callback. If the callback is successfully started, the callback's
1787 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1788 * specifying one of the {@code ERROR_*} constants in this class.
1789 *
Chalard Jean4d660112018-06-04 16:52:49 +09001790 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1791 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1792 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001793 *
junyulai48eac1d42018-12-27 17:25:29 +08001794 * @deprecated Use {@link SocketKeepalive} instead.
1795 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001796 * @hide
1797 */
1798 public class PacketKeepalive {
1799
1800 private static final String TAG = "PacketKeepalive";
1801
1802 /** @hide */
1803 public static final int SUCCESS = 0;
1804
1805 /** @hide */
1806 public static final int NO_KEEPALIVE = -1;
1807
1808 /** @hide */
1809 public static final int BINDER_DIED = -10;
1810
1811 /** The specified {@code Network} is not connected. */
1812 public static final int ERROR_INVALID_NETWORK = -20;
1813 /** The specified IP addresses are invalid. For example, the specified source IP address is
1814 * not configured on the specified {@code Network}. */
1815 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1816 /** The requested port is invalid. */
1817 public static final int ERROR_INVALID_PORT = -22;
1818 /** The packet length is invalid (e.g., too long). */
1819 public static final int ERROR_INVALID_LENGTH = -23;
1820 /** The packet transmission interval is invalid (e.g., too short). */
1821 public static final int ERROR_INVALID_INTERVAL = -24;
1822
1823 /** The hardware does not support this request. */
1824 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001825 /** The hardware returned an error. */
1826 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001827
Nathan Harold63dd8132018-02-14 13:09:45 -08001828 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001829 public static final int NATT_PORT = 4500;
1830
Nathan Harold63dd8132018-02-14 13:09:45 -08001831 /** The minimum interval in seconds between keepalive packet transmissions */
1832 public static final int MIN_INTERVAL = 10;
1833
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001834 private final Network mNetwork;
junyulai7c469172019-01-16 20:23:34 +08001835 private final ISocketKeepaliveCallback mCallback;
1836 private final ExecutorService mExecutor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001837
1838 private volatile Integer mSlot;
1839
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001840 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001841 public void stop() {
1842 try {
junyulai7c469172019-01-16 20:23:34 +08001843 mExecutor.execute(() -> {
1844 try {
1845 if (mSlot != null) {
1846 mService.stopKeepalive(mNetwork, mSlot);
1847 }
1848 } catch (RemoteException e) {
1849 Log.e(TAG, "Error stopping packet keepalive: ", e);
1850 throw e.rethrowFromSystemServer();
1851 }
1852 });
1853 } catch (RejectedExecutionException e) {
1854 // The internal executor has already stopped due to previous event.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001855 }
1856 }
1857
1858 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001859 Preconditions.checkNotNull(network, "network cannot be null");
1860 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001861 mNetwork = network;
junyulai7c469172019-01-16 20:23:34 +08001862 mExecutor = Executors.newSingleThreadExecutor();
1863 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001864 @Override
junyulai7c469172019-01-16 20:23:34 +08001865 public void onStarted(int slot) {
1866 Binder.withCleanCallingIdentity(() ->
1867 mExecutor.execute(() -> {
1868 mSlot = slot;
1869 callback.onStarted();
1870 }));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001871 }
junyulai7c469172019-01-16 20:23:34 +08001872
1873 @Override
1874 public void onStopped() {
1875 Binder.withCleanCallingIdentity(() ->
1876 mExecutor.execute(() -> {
1877 mSlot = null;
1878 callback.onStopped();
1879 }));
1880 mExecutor.shutdown();
1881 }
1882
1883 @Override
1884 public void onError(int error) {
1885 Binder.withCleanCallingIdentity(() ->
1886 mExecutor.execute(() -> {
1887 mSlot = null;
1888 callback.onError(error);
1889 }));
1890 mExecutor.shutdown();
1891 }
1892
1893 @Override
1894 public void onDataReceived() {
1895 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1896 // this callback when data is received.
1897 }
1898 };
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001899 }
1900 }
1901
1902 /**
1903 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1904 *
junyulai48eac1d42018-12-27 17:25:29 +08001905 * @deprecated Use {@link #createSocketKeepalive} instead.
1906 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001907 * @hide
1908 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001909 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001910 public PacketKeepalive startNattKeepalive(
1911 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1912 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1913 final PacketKeepalive k = new PacketKeepalive(network, callback);
1914 try {
junyulai7c469172019-01-16 20:23:34 +08001915 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001916 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1917 } catch (RemoteException e) {
1918 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai7c469172019-01-16 20:23:34 +08001919 throw e.rethrowFromSystemServer();
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001920 }
1921 return k;
1922 }
1923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 /**
junyulai48eac1d42018-12-27 17:25:29 +08001925 * Request that keepalives be started on a IPsec NAT-T socket.
1926 *
1927 * @param network The {@link Network} the socket is on.
1928 * @param socket The socket that needs to be kept alive.
1929 * @param source The source address of the {@link UdpEncapsulationSocket}.
1930 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1931 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1932 * must run callback sequentially, otherwise the order of callbacks cannot be
1933 * guaranteed.
1934 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1935 * changes. Must be extended by applications that use this API.
1936 *
junyulai352dc2f2019-01-08 20:04:33 +08001937 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1938 * given socket.
junyulai48eac1d42018-12-27 17:25:29 +08001939 **/
junyulai0c666972019-03-04 22:45:36 +08001940 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai48eac1d42018-12-27 17:25:29 +08001941 @NonNull UdpEncapsulationSocket socket,
1942 @NonNull InetAddress source,
1943 @NonNull InetAddress destination,
1944 @NonNull @CallbackExecutor Executor executor,
1945 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001946 ParcelFileDescriptor dup;
1947 try {
junyulai15178152019-03-27 11:00:37 +08001948 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1949 // which cannot be obtained by the app process.
junyulai0c666972019-03-04 22:45:36 +08001950 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1951 } catch (IOException ignored) {
1952 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1953 // ERROR_INVALID_SOCKET.
1954 dup = new ParcelFileDescriptor(new FileDescriptor());
1955 }
1956 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1957 destination, executor, callback);
junyulai215b8772019-01-15 11:32:44 +08001958 }
1959
1960 /**
1961 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1962 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1963 *
1964 * @param network The {@link Network} the socket is on.
junyulai0c666972019-03-04 22:45:36 +08001965 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1966 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1967 * from that port.
junyulai215b8772019-01-15 11:32:44 +08001968 * @param source The source address of the {@link UdpEncapsulationSocket}.
1969 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1970 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1971 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1972 * must run callback sequentially, otherwise the order of callbacks cannot be
1973 * guaranteed.
1974 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1975 * changes. Must be extended by applications that use this API.
1976 *
junyulai352dc2f2019-01-08 20:04:33 +08001977 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1978 * given socket.
junyulai215b8772019-01-15 11:32:44 +08001979 * @hide
1980 */
1981 @SystemApi
1982 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08001983 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1984 @NonNull ParcelFileDescriptor pfd,
junyulai215b8772019-01-15 11:32:44 +08001985 @NonNull InetAddress source,
1986 @NonNull InetAddress destination,
1987 @NonNull @CallbackExecutor Executor executor,
1988 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001989 ParcelFileDescriptor dup;
1990 try {
junyulai15178152019-03-27 11:00:37 +08001991 // TODO: Consider remove unnecessary dup.
junyulai0c666972019-03-04 22:45:36 +08001992 dup = pfd.dup();
1993 } catch (IOException ignored) {
1994 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1995 // ERROR_INVALID_SOCKET.
1996 dup = new ParcelFileDescriptor(new FileDescriptor());
1997 }
1998 return new NattSocketKeepalive(mService, network, dup,
1999 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08002000 }
2001
2002 /**
junyulai352dc2f2019-01-08 20:04:33 +08002003 * Request that keepalives be started on a TCP socket.
2004 * The socket must be established.
2005 *
2006 * @param network The {@link Network} the socket is on.
2007 * @param socket The socket that needs to be kept alive.
2008 * @param executor The executor on which callback will be invoked. This implementation assumes
2009 * the provided {@link Executor} runs the callbacks in sequence with no
2010 * concurrency. Failing this, no guarantee of correctness can be made. It is
2011 * the responsibility of the caller to ensure the executor provides this
2012 * guarantee. A simple way of creating such an executor is with the standard
2013 * tool {@code Executors.newSingleThreadExecutor}.
2014 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2015 * changes. Must be extended by applications that use this API.
2016 *
2017 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2018 * given socket.
2019 * @hide
2020 */
2021 @SystemApi
2022 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08002023 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai352dc2f2019-01-08 20:04:33 +08002024 @NonNull Socket socket,
2025 @NonNull Executor executor,
2026 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08002027 ParcelFileDescriptor dup;
2028 try {
2029 dup = ParcelFileDescriptor.fromSocket(socket);
2030 } catch (UncheckedIOException ignored) {
2031 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2032 // ERROR_INVALID_SOCKET.
2033 dup = new ParcelFileDescriptor(new FileDescriptor());
2034 }
2035 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai352dc2f2019-01-08 20:04:33 +08002036 }
2037
2038 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 * Ensure that a network route exists to deliver traffic to the specified
2040 * host via the specified network interface. An attempt to add a route that
2041 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002042 *
2043 * <p>This method requires the caller to hold either the
2044 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2045 * or the ability to modify system settings as determined by
2046 * {@link android.provider.Settings.System#canWrite}.</p>
2047 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 * @param networkType the type of the network over which traffic to the specified
2049 * host is to be routed
2050 * @param hostAddress the IP address of the host to which the route is desired
2051 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002052 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002053 * @deprecated Deprecated in favor of the
2054 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2055 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07002056 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002057 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09002058 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002060 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002062 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002063 }
2064
2065 /**
2066 * Ensure that a network route exists to deliver traffic to the specified
2067 * host via the specified network interface. An attempt to add a route that
2068 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002069 *
2070 * <p>This method requires the caller to hold either the
2071 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2072 * or the ability to modify system settings as determined by
2073 * {@link android.provider.Settings.System#canWrite}.</p>
2074 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002075 * @param networkType the type of the network over which traffic to the specified
2076 * host is to be routed
2077 * @param hostAddress the IP address of the host to which the route is desired
2078 * @return {@code true} on success, {@code false} on failure
2079 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002080 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002081 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002082 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002083 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002084 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002085 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002086 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002088 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002090 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
2093
2094 /**
2095 * Returns the value of the setting for background data usage. If false,
2096 * applications should not use the network if the application is not in the
2097 * foreground. Developers should respect this setting, and check the value
2098 * of this before performing any background data operations.
2099 * <p>
2100 * All applications that have background services that use the network
2101 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002102 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002103 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002104 * background data depends on several combined factors, and this method will
2105 * always return {@code true}. Instead, when background data is unavailable,
2106 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002107 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 * @return Whether background data usage is allowed.
2109 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002110 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002112 // assume that background data is allowed; final authority is
2113 // NetworkInfo which may be blocked.
2114 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 }
2116
2117 /**
2118 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002119 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 * @param allowBackgroundData Whether an application should use data while
2121 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002122 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2124 * @see #getBackgroundDataSetting()
2125 * @hide
2126 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002127 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002128 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002130 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002132
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002133 /** {@hide} */
2134 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002135 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002136 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2137 try {
2138 return mService.getActiveNetworkQuotaInfo();
2139 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002140 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002141 }
2142 }
2143
2144 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002145 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002146 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002147 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002148 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002149 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002150 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002151 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
2152 if (b != null) {
2153 try {
2154 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08002155 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08002156 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
Malcolm Chenb455e722017-11-28 15:57:14 -08002157 boolean retVal = it.isUserDataEnabled(subId);
Wink Saville36ffb042014-12-05 11:10:30 -08002158 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2159 + " retVal=" + retVal);
2160 return retVal;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002161 } catch (RemoteException e) {
2162 throw e.rethrowFromSystemServer();
2163 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002164 }
Wink Saville36ffb042014-12-05 11:10:30 -08002165 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002166 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002167 }
2168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002170 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002171 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002172 */
2173 public interface OnNetworkActiveListener {
2174 /**
2175 * Called on the main thread of the process to report that the current data network
2176 * has become active, and it is now a good time to perform any pending network
2177 * operations. Note that this listener only tells you when the network becomes
2178 * active; if at any other time you want to know whether it is active (and thus okay
2179 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002180 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002181 */
Chalard Jean4d660112018-06-04 16:52:49 +09002182 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002183 }
2184
2185 private INetworkManagementService getNetworkManagementService() {
2186 synchronized (this) {
2187 if (mNMService != null) {
2188 return mNMService;
2189 }
2190 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2191 mNMService = INetworkManagementService.Stub.asInterface(b);
2192 return mNMService;
2193 }
2194 }
2195
2196 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002197 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002198
2199 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002200 * Start listening to reports when the system's default data network is active, meaning it is
2201 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2202 * to determine the current state of the system's default network after registering the
2203 * listener.
2204 * <p>
2205 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002206 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002207 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002208 *
2209 * @param l The listener to be told when the network is active.
2210 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002211 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002212 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2213 @Override
2214 public void onNetworkActive() throws RemoteException {
2215 l.onNetworkActive();
2216 }
2217 };
2218
2219 try {
2220 getNetworkManagementService().registerNetworkActivityListener(rl);
2221 mNetworkActivityListeners.put(l, rl);
2222 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002223 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002224 }
2225 }
2226
2227 /**
2228 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002229 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002230 *
2231 * @param l Previously registered listener.
2232 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002233 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002234 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002235 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002236 try {
2237 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2238 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002239 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002240 }
2241 }
2242
2243 /**
2244 * Return whether the data network is currently active. An active network means that
2245 * it is currently in a high power state for performing data transmission. On some
2246 * types of networks, it may be expensive to move and stay in such a state, so it is
2247 * more power efficient to batch network traffic together when the radio is already in
2248 * this state. This method tells you whether right now is currently a good time to
2249 * initiate network traffic, as the network is already active.
2250 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002251 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002252 try {
2253 return getNetworkManagementService().isNetworkActive();
2254 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002255 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002256 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002257 }
2258
2259 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 * {@hide}
2261 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002262 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002263 mContext = Preconditions.checkNotNull(context, "missing context");
2264 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05002265 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002267
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002268 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002269 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002270 public static ConnectivityManager from(Context context) {
2271 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2272 }
2273
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002274 /** @hide */
2275 public NetworkRequest getDefaultRequest() {
2276 try {
2277 // This is not racy as the default request is final in ConnectivityService.
2278 return mService.getDefaultRequest();
2279 } catch (RemoteException e) {
2280 throw e.rethrowFromSystemServer();
2281 }
2282 }
2283
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002284 /* TODO: These permissions checks don't belong in client-side code. Move them to
2285 * services.jar, possibly in com.android.server.net. */
2286
2287 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002288 public static final void enforceChangePermission(Context context) {
2289 int uid = Binder.getCallingUid();
2290 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2291 .getPackageNameForUid(context, uid), true /* throwException */);
2292 }
2293
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002294 /** {@hide} */
2295 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002296 Preconditions.checkNotNull(context, "Context cannot be null");
2297 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002298
Robert Greenwaltedb47662014-09-16 17:54:19 -07002299 if (context.getResources().getStringArray(
2300 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2301 // Have a provisioning app - must only let system apps (which check this app)
2302 // turn on tethering
2303 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002304 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002305 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002306 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002307 // If callingPkg's uid is not same as Binder.getCallingUid(),
2308 // AppOpsService throws SecurityException.
2309 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2310 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002311 }
2312 }
2313
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002314 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002315 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2316 * situations where a Context pointer is unavailable.
2317 * @hide
2318 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002319 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002320 static ConnectivityManager getInstanceOrNull() {
2321 return sInstance;
2322 }
2323
2324 /**
2325 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2326 * situations where a Context pointer is unavailable.
2327 * @hide
2328 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002329 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002330 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002331 private static ConnectivityManager getInstance() {
2332 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002333 throw new IllegalStateException("No ConnectivityManager yet constructed");
2334 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002335 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002336 }
2337
2338 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002339 * Get the set of tetherable, available interfaces. This list is limited by
2340 * device configuration and current interface existence.
2341 *
2342 * @return an array of 0 or more Strings of tetherable interface names.
2343 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002344 * {@hide}
2345 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002346 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002347 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002348 public String[] getTetherableIfaces() {
2349 try {
2350 return mService.getTetherableIfaces();
2351 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002352 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002353 }
2354 }
2355
2356 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002357 * Get the set of tethered interfaces.
2358 *
2359 * @return an array of 0 or more String of currently tethered interface names.
2360 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002361 * {@hide}
2362 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002363 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002364 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002365 public String[] getTetheredIfaces() {
2366 try {
2367 return mService.getTetheredIfaces();
2368 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002369 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002370 }
2371 }
2372
2373 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002374 * Get the set of interface names which attempted to tether but
2375 * failed. Re-attempting to tether may cause them to reset to the Tethered
2376 * state. Alternatively, causing the interface to be destroyed and recreated
2377 * may cause them to reset to the available state.
2378 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2379 * information on the cause of the errors.
2380 *
2381 * @return an array of 0 or more String indicating the interface names
2382 * which failed to tether.
2383 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002384 * {@hide}
2385 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002386 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002387 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002388 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002389 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08002390 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002391 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002392 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002393 }
2394 }
2395
2396 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002397 * Get the set of tethered dhcp ranges.
2398 *
2399 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
2400 * {@hide}
2401 */
2402 public String[] getTetheredDhcpRanges() {
2403 try {
2404 return mService.getTetheredDhcpRanges();
2405 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002406 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002407 }
2408 }
2409
2410 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002411 * Attempt to tether the named interface. This will setup a dhcp server
2412 * on the interface, forward and NAT IP packets and forward DNS requests
2413 * to the best active upstream network interface. Note that if no upstream
2414 * IP network interface is available, dhcp will still run and traffic will be
2415 * allowed between the tethered devices and this device, though upstream net
2416 * access will of course fail until an upstream network interface becomes
2417 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002418 *
2419 * <p>This method requires the caller to hold either the
2420 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2421 * or the ability to modify system settings as determined by
2422 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002423 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002424 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2425 * and WifiStateMachine which need direct access. All other clients should use
2426 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2427 * logic.</p>
2428 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002429 * @param iface the interface name to tether.
2430 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2431 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002432 * {@hide}
2433 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002434 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002435 public int tether(String iface) {
2436 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002437 String pkgName = mContext.getOpPackageName();
2438 Log.i(TAG, "tether caller:" + pkgName);
2439 return mService.tether(iface, pkgName);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002440 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002441 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002442 }
2443 }
2444
2445 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002446 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002447 *
2448 * <p>This method requires the caller to hold either the
2449 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2450 * or the ability to modify system settings as determined by
2451 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002452 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002453 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2454 * and WifiStateMachine which need direct access. All other clients should use
2455 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2456 * logic.</p>
2457 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002458 * @param iface the interface name to untether.
2459 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2460 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002461 * {@hide}
2462 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002463 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002464 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002465 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002466 String pkgName = mContext.getOpPackageName();
2467 Log.i(TAG, "untether caller:" + pkgName);
2468 return mService.untether(iface, pkgName);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002469 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002470 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002471 }
2472 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002473
2474 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002475 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002476 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002477 * due to device configuration.
2478 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002479 * <p>If this app does not have permission to use this API, it will always
2480 * return false rather than throw an exception.</p>
2481 *
2482 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2483 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2484 *
2485 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2486 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2487 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002488 * @return a boolean - {@code true} indicating Tethering is supported.
2489 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002490 * {@hide}
2491 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002492 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002493 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2494 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002495 public boolean isTetheringSupported() {
Chalard Jean8f76fc32017-09-26 15:45:18 +09002496 String pkgName = mContext.getOpPackageName();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002497 try {
Udam Saini0e94c362017-06-07 12:06:28 -07002498 return mService.isTetheringSupported(pkgName);
Chalard Jean8f76fc32017-09-26 15:45:18 +09002499 } catch (SecurityException e) {
2500 // This API is not available to this caller, but for backward-compatibility
2501 // this will just return false instead of throwing.
2502 return false;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002503 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002504 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002505 }
2506 }
2507
2508 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002509 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2510 * @hide
2511 */
2512 @SystemApi
2513 public static abstract class OnStartTetheringCallback {
2514 /**
2515 * Called when tethering has been successfully started.
2516 */
Chalard Jean4d660112018-06-04 16:52:49 +09002517 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002518
2519 /**
2520 * Called when starting tethering failed.
2521 */
Chalard Jean4d660112018-06-04 16:52:49 +09002522 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002523 }
2524
2525 /**
2526 * Convenient overload for
2527 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2528 * handler to run on the current thread's {@link Looper}.
2529 * @hide
2530 */
2531 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07002532 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002533 public void startTethering(int type, boolean showProvisioningUi,
2534 final OnStartTetheringCallback callback) {
2535 startTethering(type, showProvisioningUi, callback, null);
2536 }
2537
2538 /**
2539 * Runs tether provisioning for the given type if needed and then starts tethering if
2540 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2541 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2542 * schedules tether provisioning re-checks if appropriate.
2543 *
2544 * @param type The type of tethering to start. Must be one of
2545 * {@link ConnectivityManager.TETHERING_WIFI},
2546 * {@link ConnectivityManager.TETHERING_USB}, or
2547 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2548 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2549 * is one. This should be true the first time this function is called and also any time
2550 * the user can see this UI. It gives users information from their carrier about the
2551 * check failing and how they can sign up for tethering if possible.
2552 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2553 * of the result of trying to tether.
2554 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2555 * @hide
2556 */
2557 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002558 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002559 public void startTethering(int type, boolean showProvisioningUi,
2560 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002561 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002562
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002563 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2564 @Override
2565 protected void onReceiveResult(int resultCode, Bundle resultData) {
2566 if (resultCode == TETHER_ERROR_NO_ERROR) {
2567 callback.onTetheringStarted();
2568 } else {
2569 callback.onTetheringFailed();
2570 }
2571 }
2572 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002573
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002574 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002575 String pkgName = mContext.getOpPackageName();
2576 Log.i(TAG, "startTethering caller:" + pkgName);
2577 mService.startTethering(type, wrappedCallback, showProvisioningUi, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002578 } catch (RemoteException e) {
2579 Log.e(TAG, "Exception trying to start tethering.", e);
2580 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2581 }
2582 }
2583
2584 /**
2585 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2586 * applicable.
2587 *
2588 * @param type The type of tethering to stop. Must be one of
2589 * {@link ConnectivityManager.TETHERING_WIFI},
2590 * {@link ConnectivityManager.TETHERING_USB}, or
2591 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2592 * @hide
2593 */
2594 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002595 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002596 public void stopTethering(int type) {
2597 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002598 String pkgName = mContext.getOpPackageName();
2599 Log.i(TAG, "stopTethering caller:" + pkgName);
2600 mService.stopTethering(type, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002601 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002602 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002603 }
2604 }
2605
2606 /**
markchien26299ed2019-02-27 14:56:11 +08002607 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2608 * upstream status.
2609 *
2610 *@hide
2611 */
2612 @SystemApi
2613 public abstract static class OnTetheringEventCallback {
2614
2615 /**
2616 * Called when tethering upstream changed. This can be called multiple times and can be
2617 * called any time.
2618 *
2619 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2620 * have any upstream.
2621 */
2622 public void onUpstreamChanged(@Nullable Network network) {}
2623 }
2624
2625 @GuardedBy("mTetheringEventCallbacks")
2626 private final ArrayMap<OnTetheringEventCallback, ITetheringEventCallback>
2627 mTetheringEventCallbacks = new ArrayMap<>();
2628
2629 /**
2630 * Start listening to tethering change events. Any new added callback will receive the last
markchien9f246bd2019-04-03 10:43:09 +08002631 * tethering status right away. If callback is registered when tethering has no upstream or
markchien26299ed2019-02-27 14:56:11 +08002632 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2633 * with a null argument. The same callback object cannot be registered twice.
2634 *
2635 * @param executor the executor on which callback will be invoked.
2636 * @param callback the callback to be called when tethering has change events.
2637 * @hide
2638 */
2639 @SystemApi
2640 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2641 public void registerTetheringEventCallback(
2642 @NonNull @CallbackExecutor Executor executor,
2643 @NonNull final OnTetheringEventCallback callback) {
2644 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2645
2646 synchronized (mTetheringEventCallbacks) {
2647 Preconditions.checkArgument(!mTetheringEventCallbacks.containsKey(callback),
2648 "callback was already registered.");
2649 ITetheringEventCallback remoteCallback = new ITetheringEventCallback.Stub() {
2650 @Override
2651 public void onUpstreamChanged(Network network) throws RemoteException {
2652 Binder.withCleanCallingIdentity(() ->
2653 executor.execute(() -> {
2654 callback.onUpstreamChanged(network);
2655 }));
2656 }
2657 };
2658 try {
2659 String pkgName = mContext.getOpPackageName();
2660 Log.i(TAG, "registerTetheringUpstreamCallback:" + pkgName);
2661 mService.registerTetheringEventCallback(remoteCallback, pkgName);
2662 mTetheringEventCallbacks.put(callback, remoteCallback);
2663 } catch (RemoteException e) {
2664 throw e.rethrowFromSystemServer();
2665 }
2666 }
2667 }
2668
2669 /**
2670 * Remove tethering event callback previously registered with
2671 * {@link #registerTetheringEventCallback}.
2672 *
2673 * @param callback previously registered callback.
2674 * @hide
2675 */
2676 @SystemApi
2677 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2678 public void unregisterTetheringEventCallback(
2679 @NonNull final OnTetheringEventCallback callback) {
2680 synchronized (mTetheringEventCallbacks) {
2681 ITetheringEventCallback remoteCallback = mTetheringEventCallbacks.remove(callback);
2682 Preconditions.checkNotNull(remoteCallback, "callback was not registered.");
2683 try {
2684 String pkgName = mContext.getOpPackageName();
2685 Log.i(TAG, "unregisterTetheringEventCallback:" + pkgName);
2686 mService.unregisterTetheringEventCallback(remoteCallback, pkgName);
2687 } catch (RemoteException e) {
2688 throw e.rethrowFromSystemServer();
2689 }
2690 }
2691 }
2692
2693
2694 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002695 * Get the list of regular expressions that define any tetherable
2696 * USB network interfaces. If USB tethering is not supported by the
2697 * device, this list should be empty.
2698 *
2699 * @return an array of 0 or more regular expression Strings defining
2700 * what interfaces are considered tetherable usb interfaces.
2701 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002702 * {@hide}
2703 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002704 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002705 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002706 public String[] getTetherableUsbRegexs() {
2707 try {
2708 return mService.getTetherableUsbRegexs();
2709 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002710 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002711 }
2712 }
2713
2714 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002715 * Get the list of regular expressions that define any tetherable
2716 * Wifi network interfaces. If Wifi tethering is not supported by the
2717 * device, this list should be empty.
2718 *
2719 * @return an array of 0 or more regular expression Strings defining
2720 * what interfaces are considered tetherable wifi interfaces.
2721 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002722 * {@hide}
2723 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002724 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002725 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002726 public String[] getTetherableWifiRegexs() {
2727 try {
2728 return mService.getTetherableWifiRegexs();
2729 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002730 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002731 }
2732 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002733
Danica Chang6fdd0c62010-08-11 14:54:43 -07002734 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002735 * Get the list of regular expressions that define any tetherable
2736 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2737 * device, this list should be empty.
2738 *
2739 * @return an array of 0 or more regular expression Strings defining
2740 * what interfaces are considered tetherable bluetooth interfaces.
2741 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002742 * {@hide}
2743 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002744 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002745 @UnsupportedAppUsage
Danica Chang6fdd0c62010-08-11 14:54:43 -07002746 public String[] getTetherableBluetoothRegexs() {
2747 try {
2748 return mService.getTetherableBluetoothRegexs();
2749 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002750 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002751 }
2752 }
2753
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002754 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002755 * Attempt to both alter the mode of USB and Tethering of USB. A
2756 * utility method to deal with some of the complexity of USB - will
2757 * attempt to switch to Rndis and subsequently tether the resulting
2758 * interface on {@code true} or turn off tethering and switch off
2759 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002760 *
2761 * <p>This method requires the caller to hold either the
2762 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2763 * or the ability to modify system settings as determined by
2764 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002765 *
2766 * @param enable a boolean - {@code true} to enable tethering
2767 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2768 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002769 * {@hide}
2770 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002771 @UnsupportedAppUsage
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002772 public int setUsbTethering(boolean enable) {
2773 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002774 String pkgName = mContext.getOpPackageName();
2775 Log.i(TAG, "setUsbTethering caller:" + pkgName);
2776 return mService.setUsbTethering(enable, pkgName);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002777 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002778 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002779 }
2780 }
2781
Robert Greenwalt5a735062010-03-02 17:25:02 -08002782 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002783 @SystemApi
Robert Greenwalt5a735062010-03-02 17:25:02 -08002784 public static final int TETHER_ERROR_NO_ERROR = 0;
2785 /** {@hide} */
2786 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2787 /** {@hide} */
2788 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2789 /** {@hide} */
2790 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2791 /** {@hide} */
2792 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2793 /** {@hide} */
2794 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2795 /** {@hide} */
2796 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2797 /** {@hide} */
2798 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2799 /** {@hide} */
2800 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2801 /** {@hide} */
2802 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2803 /** {@hide} */
2804 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002805 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002806 @SystemApi
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002807 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +09002808 /** {@hide} */
2809 public static final int TETHER_ERROR_DHCPSERVER_ERROR = 12;
markchienf2731272019-01-16 17:44:13 +08002810 /** {@hide} */
2811 @SystemApi
2812 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002813
2814 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002815 * Get a more detailed error code after a Tethering or Untethering
2816 * request asynchronously failed.
2817 *
2818 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002819 * @return error The error code of the last error tethering or untethering the named
2820 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002821 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002822 * {@hide}
2823 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002824 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002825 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002826 public int getLastTetherError(String iface) {
2827 try {
2828 return mService.getLastTetherError(iface);
2829 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002830 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002831 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002832 }
2833
markchien9554abf2019-03-06 16:25:00 +08002834 /** @hide */
2835 @Retention(RetentionPolicy.SOURCE)
2836 @IntDef(value = {
2837 TETHER_ERROR_NO_ERROR,
2838 TETHER_ERROR_PROVISION_FAILED,
2839 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2840 })
2841 public @interface EntitlementResultCode {
2842 }
2843
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002844 /**
markchien9554abf2019-03-06 16:25:00 +08002845 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchienf2731272019-01-16 17:44:13 +08002846 * entitlement succeeded.
2847 * @hide
2848 */
2849 @SystemApi
markchien9554abf2019-03-06 16:25:00 +08002850 public interface OnTetheringEntitlementResultListener {
2851 /**
2852 * Called to notify entitlement result.
2853 *
2854 * @param resultCode an int value of entitlement result. It may be one of
2855 * {@link #TETHER_ERROR_NO_ERROR},
2856 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2857 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2858 */
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002859 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchien9554abf2019-03-06 16:25:00 +08002860 }
2861
2862 /**
markchienf2731272019-01-16 17:44:13 +08002863 * Get the last value of the entitlement check on this downstream. If the cached value is
2864 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2865 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2866 * guaranteed that the UI-based entitlement check will complete in any specific time period
2867 * and may in fact never complete. Any successful entitlement check the platform performs for
2868 * any reason will update the cached value.
2869 *
2870 * @param type the downstream type of tethering. Must be one of
2871 * {@link #TETHERING_WIFI},
2872 * {@link #TETHERING_USB}, or
2873 * {@link #TETHERING_BLUETOOTH}.
2874 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchien9554abf2019-03-06 16:25:00 +08002875 * @param executor the executor on which callback will be invoked.
2876 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2877 * notify the caller of the result of entitlement check. The listener may be called zero
2878 * or one time.
markchienf2731272019-01-16 17:44:13 +08002879 * {@hide}
2880 */
2881 @SystemApi
2882 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchien9554abf2019-03-06 16:25:00 +08002883 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2884 @NonNull @CallbackExecutor Executor executor,
2885 @NonNull final OnTetheringEntitlementResultListener listener) {
2886 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2887 ResultReceiver wrappedListener = new ResultReceiver(null) {
2888 @Override
2889 protected void onReceiveResult(int resultCode, Bundle resultData) {
2890 Binder.withCleanCallingIdentity(() ->
2891 executor.execute(() -> {
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002892 listener.onTetheringEntitlementResult(resultCode);
markchien9554abf2019-03-06 16:25:00 +08002893 }));
2894 }
2895 };
2896
2897 try {
2898 String pkgName = mContext.getOpPackageName();
2899 Log.i(TAG, "getLatestTetheringEntitlementResult:" + pkgName);
2900 mService.getLatestTetheringEntitlementResult(type, wrappedListener,
2901 showEntitlementUi, pkgName);
2902 } catch (RemoteException e) {
2903 throw e.rethrowFromSystemServer();
2904 }
2905 }
2906
2907 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002908 * Report network connectivity status. This is currently used only
2909 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002910 * <p>This method requires the caller to hold the permission
2911 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002912 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002913 * @param networkType The type of network you want to report on
2914 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002915 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002916 * {@hide}
2917 */
2918 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002919 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002920 try {
2921 mService.reportInetCondition(networkType, percentage);
2922 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002923 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002924 }
2925 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002926
2927 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002928 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002929 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002930 * the framework to re-evaluate network connectivity and/or switch to another
2931 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002932 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002933 * @param network The {@link Network} the application was attempting to use
2934 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002935 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2936 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002937 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002938 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002939 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002940 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002941 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002942 // One of these will be ignored because it matches system's current state.
2943 // The other will trigger the necessary reevaluation.
2944 mService.reportNetworkConnectivity(network, true);
2945 mService.reportNetworkConnectivity(network, false);
2946 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002947 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002948 }
2949 }
2950
2951 /**
2952 * Report to the framework whether a network has working connectivity.
2953 * This provides a hint to the system that a particular network is providing
2954 * working connectivity or not. In response the framework may re-evaluate
2955 * the network's connectivity and might take further action thereafter.
2956 *
2957 * @param network The {@link Network} the application was attempting to use
2958 * or {@code null} to indicate the current default network.
2959 * @param hasConnectivity {@code true} if the application was able to successfully access the
2960 * Internet using {@code network} or {@code false} if not.
2961 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002962 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002963 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002964 try {
2965 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002966 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002967 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002968 }
2969 }
2970
2971 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002972 * Set a network-independent global http proxy. This is not normally what you want
2973 * for typical HTTP proxies - they are general network dependent. However if you're
2974 * doing something unusual like general internal filtering this may be useful. On
2975 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002976 *
2977 * @param p A {@link ProxyInfo} object defining the new global
2978 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002979 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002980 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002981 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Jason Monk207900c2014-04-25 15:00:09 -04002982 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002983 try {
2984 mService.setGlobalProxy(p);
2985 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002986 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002987 }
2988 }
2989
2990 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002991 * Retrieve any network-independent global HTTP proxy.
2992 *
Jason Monk207900c2014-04-25 15:00:09 -04002993 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002994 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002995 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002996 */
Jason Monk207900c2014-04-25 15:00:09 -04002997 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002998 try {
2999 return mService.getGlobalProxy();
3000 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003001 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003002 }
3003 }
3004
3005 /**
Paul Jensencee9b512015-05-06 07:32:40 -04003006 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3007 * network-specific HTTP proxy. If {@code network} is null, the
3008 * network-specific proxy returned is the proxy of the default active
3009 * network.
3010 *
3011 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3012 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3013 * or when {@code network} is {@code null},
3014 * the {@code ProxyInfo} for the default active network. Returns
3015 * {@code null} when no proxy applies or the caller doesn't have
3016 * permission to use {@code network}.
3017 * @hide
3018 */
3019 public ProxyInfo getProxyForNetwork(Network network) {
3020 try {
3021 return mService.getProxyForNetwork(network);
3022 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003023 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04003024 }
3025 }
3026
3027 /**
Paul Jensene0bef712014-12-10 15:12:18 -05003028 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3029 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04003030 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05003031 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003032 *
Jason Monk207900c2014-04-25 15:00:09 -04003033 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003034 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07003035 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003036 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05003037 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04003038 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07003039 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003040
3041 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003042 * Returns true if the hardware supports the given network type
3043 * else it returns false. This doesn't indicate we have coverage
3044 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003045 * hardware supports it. For example a GSM phone without a SIM
3046 * should still return {@code true} for mobile data, but a wifi only
3047 * tablet would return {@code false}.
3048 *
3049 * @param networkType The network type we'd like to check
3050 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003051 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003052 * @hide
3053 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003054 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003055 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09003056 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003057 public boolean isNetworkSupported(int networkType) {
3058 try {
3059 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003060 } catch (RemoteException e) {
3061 throw e.rethrowFromSystemServer();
3062 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003063 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003064
3065 /**
3066 * Returns if the currently active data network is metered. A network is
3067 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003068 * that connection due to monetary costs, data limitations or
3069 * battery/performance issues. You should check this before doing large
3070 * data transfers, and warn the user or delay the operation until another
3071 * network is available.
3072 *
3073 * @return {@code true} if large transfers should be avoided, otherwise
3074 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003075 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003076 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003077 public boolean isActiveNetworkMetered() {
3078 try {
3079 return mService.isActiveNetworkMetered();
3080 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003081 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003082 }
3083 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003084
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003085 /**
3086 * If the LockdownVpn mechanism is enabled, updates the vpn
3087 * with a reload of its profile.
3088 *
3089 * @return a boolean with {@code} indicating success
3090 *
3091 * <p>This method can only be called by the system UID
3092 * {@hide}
3093 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003094 public boolean updateLockdownVpn() {
3095 try {
3096 return mService.updateLockdownVpn();
3097 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003098 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003099 }
3100 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07003101
3102 /**
Wink Saville948282b2013-08-29 08:55:16 -07003103 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07003104 *
Wink Savilleab9321d2013-06-29 21:10:57 -07003105 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07003106 *
3107 * @return time out that will be used, maybe less that suggestedTimeOutMs
3108 * -1 if an error.
3109 *
3110 * {@hide}
3111 */
Wink Saville948282b2013-08-29 08:55:16 -07003112 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003113 int timeOutMs = -1;
3114 try {
Wink Saville948282b2013-08-29 08:55:16 -07003115 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07003116 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003117 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07003118 }
3119 return timeOutMs;
3120 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003121
3122 /**
Wink Saville42d4f082013-07-20 20:31:59 -07003123 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003124 * {@hide}
3125 */
3126 public String getMobileProvisioningUrl() {
3127 try {
3128 return mService.getMobileProvisioningUrl();
3129 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003130 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003131 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003132 }
Wink Saville42d4f082013-07-20 20:31:59 -07003133
3134 /**
Wink Saville948282b2013-08-29 08:55:16 -07003135 * Set sign in error notification to visible or in visible
3136 *
Wink Saville948282b2013-08-29 08:55:16 -07003137 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04003138 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07003139 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003140 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07003141 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003142 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003143 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04003144 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07003145 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003146 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07003147 }
3148 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003149
3150 /**
3151 * Set the value for enabling/disabling airplane mode
3152 *
3153 * @param enable whether to enable airplane mode or not
3154 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003155 * @hide
3156 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003157 @RequiresPermission(anyOf = {
3158 android.Manifest.permission.NETWORK_SETTINGS,
3159 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3160 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09003161 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003162 public void setAirplaneMode(boolean enable) {
3163 try {
3164 mService.setAirplaneMode(enable);
3165 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003166 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003167 }
3168 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003169
Chalard Jean05ab6812018-05-02 21:14:54 +09003170 /** {@hide} - returns the factory serial number */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003171 @UnsupportedAppUsage
Chalard Jean05ab6812018-05-02 21:14:54 +09003172 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003173 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003174 return mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003175 } catch (RemoteException e) {
3176 throw e.rethrowFromSystemServer();
3177 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003178 }
3179
3180 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00003181 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Robert Greenwalta67be032014-05-16 15:49:14 -07003182 public void unregisterNetworkFactory(Messenger messenger) {
3183 try {
3184 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003185 } catch (RemoteException e) {
3186 throw e.rethrowFromSystemServer();
3187 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003188 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003189
Chalard Jean05ab6812018-05-02 21:14:54 +09003190 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3191 // of dependent changes that would conflict throughout the automerger graph. Having this
3192 // temporarily helps with the process of going through with all these dependent changes across
3193 // the entire tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05003194 /**
3195 * @hide
3196 * Register a NetworkAgent with ConnectivityService.
3197 * @return NetID corresponding to NetworkAgent.
3198 */
3199 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003200 NetworkCapabilities nc, int score, NetworkMisc misc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003201 return registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3202 NetworkFactory.SerialNumber.NONE);
3203 }
3204
3205 /**
3206 * @hide
3207 * Register a NetworkAgent with ConnectivityService.
3208 * @return NetID corresponding to NetworkAgent.
3209 */
3210 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
3211 NetworkCapabilities nc, int score, NetworkMisc misc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003212 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003213 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3214 factorySerialNumber);
Paul Jensen31a94f42015-02-13 14:18:39 -05003215 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003216 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05003217 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003218 }
3219
Robert Greenwalt9258c642014-03-26 16:47:06 -07003220 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003221 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3222 * changes. Should be extended by applications wanting notifications.
3223 *
3224 * A {@code NetworkCallback} is registered by calling
3225 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3226 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09003227 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09003228 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3229 * A {@code NetworkCallback} should be registered at most once at any time.
3230 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003231 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003232 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003233 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003234 * Called when the framework connects to a new network to evaluate whether it satisfies this
3235 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3236 * callback. There is no guarantee that this new network will satisfy any requests, or that
3237 * the network will stay connected for longer than the time necessary to evaluate it.
3238 * <p>
3239 * Most applications <b>should not</b> act on this callback, and should instead use
3240 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3241 * the framework in properly evaluating the network &mdash; for example, an application that
3242 * can automatically log in to a captive portal without user intervention.
3243 *
3244 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09003245 *
3246 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07003247 */
paulhu3d67f532019-03-22 16:35:06 +08003248 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003249
3250 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003251 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003252 * This callback may be called more than once if the {@link Network} that is
3253 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003254 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003255 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003256 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3257 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08003258 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003259 * @hide
3260 */
paulhu3d67f532019-03-22 16:35:06 +08003261 public void onAvailable(@NonNull Network network,
3262 @NonNull NetworkCapabilities networkCapabilities,
3263 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003264 // Internally only this method is called when a new network is available, and
3265 // it calls the callback in the same way and order that older versions used
3266 // to call so as not to change the behavior.
3267 onAvailable(network);
3268 if (!networkCapabilities.hasCapability(
3269 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3270 onNetworkSuspended(network);
3271 }
3272 onCapabilitiesChanged(network, networkCapabilities);
3273 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003274 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003275 }
3276
3277 /**
3278 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean599ce752019-08-30 16:27:28 +09003279 *
3280 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3281 * be available at the same time, and onAvailable will be called for each of these as they
3282 * appear.
3283 *
3284 * <p>For callbacks registered with {@link #requestNetwork} and
3285 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3286 * is the new best network for this request and is now tracked by this callback ; this
3287 * callback will no longer receive method calls about other networks that may have been
3288 * passed to this method previously. The previously-best network may have disconnected, or
3289 * it may still be around and the newly-best network may simply be better.
3290 *
3291 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3292 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3293 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3294 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3295 *
3296 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3297 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3298 * this callback as this is prone to race conditions (there is no guarantee the objects
3299 * returned by these methods will be current). Instead, wait for a call to
3300 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3301 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3302 * to be well-ordered with respect to other callbacks.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003303 *
3304 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003305 */
paulhu3d67f532019-03-22 16:35:06 +08003306 public void onAvailable(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003307
3308 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003309 * Called when the network is about to be lost, typically because there are no outstanding
3310 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3311 * with the new replacement network for graceful handover. This method is not guaranteed
3312 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3313 * network is suddenly disconnected.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003314 *
Chalard Jean599ce752019-08-30 16:27:28 +09003315 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3316 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3317 * this callback as this is prone to race conditions ; calling these methods while in a
3318 * callback may return an outdated or even a null object.
3319 *
3320 * @param network The {@link Network} that is about to be lost.
3321 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3322 * connected for graceful handover; note that the network may still
3323 * suffer a hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003324 */
paulhu3d67f532019-03-22 16:35:06 +08003325 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003326
3327 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003328 * Called when a network disconnects or otherwise no longer satisfies this request or
3329 * callback.
3330 *
3331 * <p>If the callback was registered with requestNetwork() or
3332 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3333 * returned by onAvailable() when that network is lost and no other network satisfies
3334 * the criteria of the request.
3335 *
3336 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3337 * each network which no longer satisfies the criteria of the callback.
3338 *
3339 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3340 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3341 * this callback as this is prone to race conditions ; calling these methods while in a
3342 * callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003343 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003344 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003345 */
paulhu3d67f532019-03-22 16:35:06 +08003346 public void onLost(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003347
3348 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003349 * Called if no network is found within the timeout time specified in
Etan Cohenddb720a2019-01-08 12:09:18 -08003350 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3351 * requested network request cannot be fulfilled (whether or not a timeout was
3352 * specified). When this callback is invoked the associated
Etan Cohenaebf17e2017-03-01 12:47:28 -08003353 * {@link NetworkRequest} will have already been removed and released, as if
3354 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003355 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003356 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003357
3358 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003359 * Called when the network corresponding to this request changes capabilities but still
3360 * satisfies the requested criteria.
3361 *
3362 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3363 * to be called immediately after {@link #onAvailable}.
3364 *
3365 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3366 * ConnectivityManager methods in this callback as this is prone to race conditions :
3367 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003368 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003369 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003370 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3371 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003372 */
paulhu3d67f532019-03-22 16:35:06 +08003373 public void onCapabilitiesChanged(@NonNull Network network,
3374 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003375
3376 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003377 * Called when the network corresponding to this request changes {@link LinkProperties}.
3378 *
3379 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3380 * to be called immediately after {@link #onAvailable}.
3381 *
3382 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3383 * ConnectivityManager methods in this callback as this is prone to race conditions :
3384 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003385 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003386 * @param network The {@link Network} whose link properties have changed.
3387 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003388 */
paulhu3d67f532019-03-22 16:35:06 +08003389 public void onLinkPropertiesChanged(@NonNull Network network,
3390 @NonNull LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003391
Robert Greenwalt8d482522015-06-24 13:23:42 -07003392 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003393 * Called when the network the framework connected to for this request suspends data
3394 * transmission temporarily.
3395 *
3396 * <p>This generally means that while the TCP connections are still live temporarily
3397 * network data fails to transfer. To give a specific example, this is used on cellular
3398 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3399 * means read operations on sockets on this network will block once the buffers are
3400 * drained, and write operations will block once the buffers are full.
3401 *
3402 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3403 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3404 * this callback as this is prone to race conditions (there is no guarantee the objects
3405 * returned by these methods will be current).
3406 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003407 * @hide
3408 */
paulhu3d67f532019-03-22 16:35:06 +08003409 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003410
3411 /**
3412 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003413 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3414 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean599ce752019-08-30 16:27:28 +09003415
3416 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3417 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3418 * this callback as this is prone to race conditions : calling these methods while in a
3419 * callback may return an outdated or even a null object.
3420 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003421 * @hide
3422 */
paulhu3d67f532019-03-22 16:35:06 +08003423 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003424
junyulai05986c62018-08-07 19:50:45 +08003425 /**
3426 * Called when access to the specified network is blocked or unblocked.
3427 *
Chalard Jean599ce752019-08-30 16:27:28 +09003428 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3429 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3430 * this callback as this is prone to race conditions : calling these methods while in a
3431 * callback may return an outdated or even a null object.
3432 *
junyulai05986c62018-08-07 19:50:45 +08003433 * @param network The {@link Network} whose blocked status has changed.
3434 * @param blocked The blocked status of this {@link Network}.
3435 */
junyulai0c666972019-03-04 22:45:36 +08003436 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai05986c62018-08-07 19:50:45 +08003437
Robert Greenwalt6078b502014-06-11 16:05:07 -07003438 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003439 }
3440
Hugo Benichicb883232017-05-11 13:16:17 +09003441 /**
3442 * Constant error codes used by ConnectivityService to communicate about failures and errors
3443 * across a Binder boundary.
3444 * @hide
3445 */
3446 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003447 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003448 }
3449
3450 /** @hide */
3451 public static class TooManyRequestsException extends RuntimeException {}
3452
3453 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3454 switch (e.errorCode) {
3455 case Errors.TOO_MANY_REQUESTS:
3456 return new TooManyRequestsException();
3457 default:
3458 Log.w(TAG, "Unknown service error code " + e.errorCode);
3459 return new RuntimeException(e);
3460 }
3461 }
3462
Robert Greenwalt9258c642014-03-26 16:47:06 -07003463 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003464 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003465 public static final int CALLBACK_PRECHECK = BASE + 1;
3466 /** @hide */
3467 public static final int CALLBACK_AVAILABLE = BASE + 2;
3468 /** @hide arg1 = TTL */
3469 public static final int CALLBACK_LOSING = BASE + 3;
3470 /** @hide */
3471 public static final int CALLBACK_LOST = BASE + 4;
3472 /** @hide */
3473 public static final int CALLBACK_UNAVAIL = BASE + 5;
3474 /** @hide */
3475 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3476 /** @hide */
3477 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003478 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003479 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003480 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003481 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003482 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003483 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003484 /** @hide */
3485 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003486
Erik Kline57faba92015-11-25 12:49:38 +09003487 /** @hide */
3488 public static String getCallbackName(int whichCallback) {
3489 switch (whichCallback) {
3490 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3491 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3492 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3493 case CALLBACK_LOST: return "CALLBACK_LOST";
3494 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3495 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3496 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003497 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3498 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3499 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003500 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003501 default:
3502 return Integer.toString(whichCallback);
3503 }
3504 }
3505
Robert Greenwalt562cc542014-05-15 18:07:26 -07003506 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003507 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003508 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003509
Hugo Benichid42650f2016-07-06 22:53:17 +09003510 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003511 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003512 }
3513
Hugo Benichi2583ef02017-02-02 17:02:36 +09003514 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003515 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003516 }
3517
Robert Greenwalt9258c642014-03-26 16:47:06 -07003518 @Override
3519 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003520 if (message.what == EXPIRE_LEGACY_REQUEST) {
3521 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3522 return;
3523 }
3524
3525 final NetworkRequest request = getObject(message, NetworkRequest.class);
3526 final Network network = getObject(message, Network.class);
3527 final NetworkCallback callback;
3528 synchronized (sCallbacks) {
3529 callback = sCallbacks.get(request);
Etan Cohen4a62d1d2019-05-21 12:06:04 -07003530 if (callback == null) {
3531 Log.w(TAG,
3532 "callback not found for " + getCallbackName(message.what) + " message");
3533 return;
3534 }
Etan Cohen9b09a162019-04-16 15:07:55 -07003535 if (message.what == CALLBACK_UNAVAIL) {
3536 sCallbacks.remove(request);
3537 callback.networkRequest = ALREADY_UNREGISTERED;
3538 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003539 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003540 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003541 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003542 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003543
Robert Greenwalt9258c642014-03-26 16:47:06 -07003544 switch (message.what) {
3545 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003546 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003547 break;
3548 }
3549 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003550 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3551 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003552 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003553 break;
3554 }
3555 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003556 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003557 break;
3558 }
3559 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003560 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003561 break;
3562 }
3563 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003564 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003565 break;
3566 }
3567 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003568 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3569 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003570 break;
3571 }
3572 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003573 LinkProperties lp = getObject(message, LinkProperties.class);
3574 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003575 break;
3576 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003577 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003578 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003579 break;
3580 }
3581 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003582 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003583 break;
3584 }
junyulai05986c62018-08-07 19:50:45 +08003585 case CALLBACK_BLK_CHANGED: {
3586 boolean blocked = message.arg1 != 0;
3587 callback.onBlockedStatusChanged(network, blocked);
3588 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003589 }
3590 }
3591
Hugo Benichid42650f2016-07-06 22:53:17 +09003592 private <T> T getObject(Message msg, Class<T> c) {
3593 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003594 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003595 }
3596
Hugo Benichi2583ef02017-02-02 17:02:36 +09003597 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003598 synchronized (sCallbacks) {
3599 if (sCallbackHandler == null) {
3600 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003601 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003602 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003603 }
3604 }
3605
Hugo Benichi6f260f32017-02-03 14:18:44 +09003606 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3607 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003608
Hugo Benichi6f260f32017-02-03 14:18:44 +09003609 private static final int LISTEN = 1;
3610 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003611
Hugo Benichi6f260f32017-02-03 14:18:44 +09003612 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3613 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003614 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003615 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003616 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003617 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003618 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003619 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003620 if (callback.networkRequest != null
3621 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003622 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3623 // and requests (http://b/20701525).
3624 Log.e(TAG, "NetworkCallback was already registered");
3625 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003626 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003627 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003628 if (action == LISTEN) {
Hugo Benichid42650f2016-07-06 22:53:17 +09003629 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04003630 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003631 request = mService.requestNetwork(
3632 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04003633 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003634 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003635 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003636 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003637 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003638 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003639 } catch (RemoteException e) {
3640 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003641 } catch (ServiceSpecificException e) {
3642 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003643 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003644 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003645 }
3646
3647 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003648 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003649 *
3650 * This is temporarily public @hide so it can be called by system code that uses the
3651 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
3652 * instead network notifications.
3653 *
3654 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
3655 *
3656 * @hide
3657 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003658 public void requestNetwork(@NonNull NetworkRequest request,
3659 @NonNull NetworkCallback networkCallback, int timeoutMs, int legacyType,
3660 @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003661 CallbackHandler cbHandler = new CallbackHandler(handler);
3662 NetworkCapabilities nc = request.networkCapabilities;
3663 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003664 }
3665
3666 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003667 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003668 *
Chalard Jean599ce752019-08-30 16:27:28 +09003669 * <p>This method will attempt to find the best network that matches the passed
3670 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3671 * criteria. The platform will evaluate which network is the best at its own discretion.
3672 * Throughput, latency, cost per byte, policy, user preference and other considerations
3673 * may be factored in the decision of what is considered the best network.
3674 *
3675 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3676 * matching this request, while always attempting to match the request to a better network if
3677 * possible. If a better match is found, the platform will switch this request to the now-best
3678 * network and inform the app of the newly best network by invoking
3679 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3680 * will not try to maintain any other network than the best one currently matching the request:
3681 * a network not matching any network request may be disconnected at any time.
3682 *
3683 * <p>For example, an application could use this method to obtain a connected cellular network
3684 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3685 * radio to consume additional power. Or, an application could inform the system that it wants
3686 * a network supporting sending MMSes and have the system let it know about the currently best
3687 * MMS-supporting network through the provided {@link NetworkCallback}.
3688 *
3689 * <p>The status of the request can be followed by listening to the various callbacks described
3690 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3691 * used to direct traffic to the network (although accessing some networks may be subject to
3692 * holding specific permissions). Callers will learn about the specific characteristics of the
3693 * network through
3694 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3695 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3696 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3697 * matching the request at any given time; therefore when a better network matching the request
3698 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3699 * with the new network after which no further updates are given about the previously-best
3700 * network, unless it becomes the best again at some later time. All callbacks are invoked
3701 * in order on the same thread, which by default is a thread created by the framework running
3702 * in the app.
3703 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3704 * callbacks are invoked.
3705 *
3706 * <p>This{@link NetworkRequest} will live until released via
3707 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3708 * which point the system may let go of the network at any time.
3709 *
3710 * <p>A version of this method which takes a timeout is
3711 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3712 * wait for a limited amount of time for the network to become unavailable.
3713 *
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003714 * <p>It is presently unsupported to request a network with mutable
3715 * {@link NetworkCapabilities} such as
3716 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3717 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3718 * as these {@code NetworkCapabilities} represent states that a particular
3719 * network may never attain, and whether a network will attain these states
3720 * is unknown prior to bringing up the network so the framework does not
Chalard Jean599ce752019-08-30 16:27:28 +09003721 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003722 *
3723 * <p>This method requires the caller to hold either the
3724 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3725 * or the ability to modify system settings as determined by
3726 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003727 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003728 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003729 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3730 * the callback must not be shared - it uniquely specifies this request.
3731 * The callback is invoked on the default internal Handler.
Chalard Jean92c8b672019-05-13 15:13:58 +09003732 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3733 * @throws SecurityException if missing the appropriate permissions.
3734 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003735 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003736 public void requestNetwork(@NonNull NetworkRequest request,
3737 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003738 requestNetwork(request, networkCallback, getDefaultHandler());
3739 }
3740
3741 /**
3742 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3743 *
Chalard Jean599ce752019-08-30 16:27:28 +09003744 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3745 * but runs all the callbacks on the passed Handler.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003746 *
Chalard Jean599ce752019-08-30 16:27:28 +09003747 * <p>This method has the same permission requirements as
3748 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3749 * the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003750 *
3751 * @param request {@link NetworkRequest} describing this request.
3752 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3753 * the callback must not be shared - it uniquely specifies this request.
3754 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003755 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003756 public void requestNetwork(@NonNull NetworkRequest request,
3757 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003758 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3759 CallbackHandler cbHandler = new CallbackHandler(handler);
3760 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003761 }
3762
3763 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003764 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3765 * by a timeout.
3766 *
3767 * This function behaves identically to the non-timed-out version
3768 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3769 * is not found within the given time (in milliseconds) the
3770 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3771 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3772 * not have to be released if timed-out (it is automatically released). Unregistering a
3773 * request that timed out is not an error.
3774 *
3775 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3776 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3777 * for that purpose. Calling this method will attempt to bring up the requested network.
3778 *
Chalard Jean599ce752019-08-30 16:27:28 +09003779 * <p>This method has the same permission requirements as
3780 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3781 * the same conditions.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003782 *
3783 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003784 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3785 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003786 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3787 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3788 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003789 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003790 public void requestNetwork(@NonNull NetworkRequest request,
3791 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003792 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003793 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003794 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003795 }
3796
Hugo Benichi2583ef02017-02-02 17:02:36 +09003797 /**
3798 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3799 * by a timeout.
3800 *
Chalard Jean599ce752019-08-30 16:27:28 +09003801 * This method behaves identically to
3802 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3803 * on the passed Handler.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003804 *
Chalard Jean599ce752019-08-30 16:27:28 +09003805 * <p>This method has the same permission requirements as
3806 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} and throws the same exceptions
3807 * in the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003808 *
3809 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003810 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3811 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003812 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003813 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3814 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003815 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003816 public void requestNetwork(@NonNull NetworkRequest request,
3817 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003818 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003819 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3820 CallbackHandler cbHandler = new CallbackHandler(handler);
3821 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003822 }
3823
3824 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003825 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003826 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003827 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003828 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003829 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3830 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003831 */
Erik Kline90e93072014-11-19 12:12:24 +09003832 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003833
3834 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003835 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003836 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003837 * {@link android.content.Intent#getParcelableExtra(String)}.
3838 */
Erik Kline90e93072014-11-19 12:12:24 +09003839 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003840
3841
3842 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003843 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003844 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003845 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003846 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003847 * the request may outlive the calling application and get called back when a suitable
3848 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003849 * <p>
3850 * The operation is an Intent broadcast that goes to a broadcast receiver that
3851 * you registered with {@link Context#registerReceiver} or through the
3852 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3853 * <p>
3854 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003855 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3856 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003857 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003858 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003859 * Intent to reserve the network or it will be released shortly after the Intent
3860 * is processed.
3861 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003862 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003863 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003864 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003865 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003866 * The request may be released normally by calling
3867 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003868 * <p>It is presently unsupported to request a network with either
3869 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3870 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3871 * as these {@code NetworkCapabilities} represent states that a particular
3872 * network may never attain, and whether a network will attain these states
3873 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003874 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003875 *
3876 * <p>This method requires the caller to hold either the
3877 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3878 * or the ability to modify system settings as determined by
3879 * {@link android.provider.Settings.System#canWrite}.</p>
3880 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003881 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003882 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003883 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003884 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean92c8b672019-05-13 15:13:58 +09003885 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3886 * @throws SecurityException if missing the appropriate permissions.
3887 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003888 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003889 public void requestNetwork(@NonNull NetworkRequest request,
3890 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003891 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003892 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003893 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003894 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003895 } catch (RemoteException e) {
3896 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003897 } catch (ServiceSpecificException e) {
3898 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003899 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003900 }
3901
3902 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003903 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3904 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003905 * This method has the same behavior as
3906 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003907 * releasing network resources and disconnecting.
3908 *
3909 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3910 * PendingIntent passed to
3911 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3912 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3913 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003914 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003915 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003916 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003917 try {
3918 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003919 } catch (RemoteException e) {
3920 throw e.rethrowFromSystemServer();
3921 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003922 }
3923
Hugo Benichie7678512017-05-09 15:19:01 +09003924 private static void checkPendingIntentNotNull(PendingIntent intent) {
3925 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3926 }
3927
3928 private static void checkCallbackNotNull(NetworkCallback callback) {
3929 Preconditions.checkNotNull(callback, "null NetworkCallback");
3930 }
3931
3932 private static void checkTimeout(int timeoutMs) {
3933 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003934 }
3935
3936 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003937 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003938 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003939 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3940 * called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003941 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003942 * @param request {@link NetworkRequest} describing this request.
3943 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3944 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003945 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003946 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003947 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003948 public void registerNetworkCallback(@NonNull NetworkRequest request,
3949 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003950 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3951 }
3952
3953 /**
3954 * Registers to receive notifications about all networks which satisfy the given
3955 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003956 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3957 * called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003958 *
3959 * @param request {@link NetworkRequest} describing this request.
3960 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3961 * networks change state.
3962 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003963 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003964 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003965 public void registerNetworkCallback(@NonNull NetworkRequest request,
3966 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003967 CallbackHandler cbHandler = new CallbackHandler(handler);
3968 NetworkCapabilities nc = request.networkCapabilities;
3969 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003970 }
3971
3972 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003973 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3974 * {@link NetworkRequest}.
3975 *
3976 * This function behaves identically to the version that takes a NetworkCallback, but instead
3977 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3978 * the request may outlive the calling application and get called back when a suitable
3979 * network is found.
3980 * <p>
3981 * The operation is an Intent broadcast that goes to a broadcast receiver that
3982 * you registered with {@link Context#registerReceiver} or through the
3983 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3984 * <p>
3985 * The operation Intent is delivered with two extras, a {@link Network} typed
3986 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3987 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3988 * the original requests parameters.
3989 * <p>
3990 * If there is already a request for this Intent registered (with the equality of
3991 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3992 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3993 * <p>
3994 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003995 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003996 * @param request {@link NetworkRequest} describing this request.
3997 * @param operation Action to perform when the network is available (corresponds
3998 * to the {@link NetworkCallback#onAvailable} call. Typically
3999 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4000 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004001 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004002 public void registerNetworkCallback(@NonNull NetworkRequest request,
4003 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004004 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004005 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04004006 try {
4007 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004008 } catch (RemoteException e) {
4009 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09004010 } catch (ServiceSpecificException e) {
4011 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004012 }
Paul Jensen694f2b82015-06-17 14:15:39 -04004013 }
4014
4015 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004016 * Registers to receive notifications about changes in the system default network. The callbacks
4017 * will continue to be called until either the application exits or
4018 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09004019 *
4020 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4021 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004022 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09004023 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004024 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004025 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004026 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4027 }
4028
4029 /**
4030 * Registers to receive notifications about changes in the system default network. The callbacks
4031 * will continue to be called until either the application exits or
4032 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004033 *
4034 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4035 * system default network changes.
4036 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004037 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004038 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004039 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4040 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09004041 // This works because if the NetworkCapabilities are null,
4042 // ConnectivityService takes them from the default request.
4043 //
4044 // Since the capabilities are exactly the same as the default request's
4045 // capabilities, this request is guaranteed, at all times, to be
4046 // satisfied by the same network, if any, that satisfies the default
4047 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004048 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09004049 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4050 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09004051 }
4052
4053 /**
fengludb571472015-04-21 17:12:05 -07004054 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4055 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4056 * network connection for updated bandwidth information. The caller will be notified via
4057 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004058 * method assumes that the caller has previously called
4059 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4060 * changes.
fenglub15e72b2015-03-20 11:29:56 -07004061 *
fengluae519192015-04-27 14:28:04 -07004062 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07004063 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07004064 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004065 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004066 try {
fengludb571472015-04-21 17:12:05 -07004067 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07004068 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004069 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07004070 }
4071 }
4072
4073 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09004074 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004075 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4076 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4077 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09004078 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4079 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004080 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09004081 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4082 * triggering it as soon as this call returns.
4083 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07004084 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004085 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004086 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004087 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004088 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09004089 final List<NetworkRequest> reqs = new ArrayList<>();
4090 // Find all requests associated to this callback and stop callback triggers immediately.
4091 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4092 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09004093 Preconditions.checkArgument(networkCallback.networkRequest != null,
4094 "NetworkCallback was not registered");
Etan Cohen9b09a162019-04-16 15:07:55 -07004095 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4096 Log.d(TAG, "NetworkCallback was already unregistered");
4097 return;
4098 }
Hugo Benichidafed3d2017-03-06 09:17:06 +09004099 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4100 if (e.getValue() == networkCallback) {
4101 reqs.add(e.getKey());
4102 }
4103 }
4104 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4105 for (NetworkRequest r : reqs) {
4106 try {
4107 mService.releaseNetworkRequest(r);
4108 } catch (RemoteException e) {
4109 throw e.rethrowFromSystemServer();
4110 }
4111 // Only remove mapping if rpc was successful.
4112 sCallbacks.remove(r);
4113 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09004114 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004115 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004116 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004117
4118 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004119 * Unregisters a callback previously registered via
4120 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4121 *
4122 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4123 * PendingIntent passed to
4124 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4125 * Cannot be null.
4126 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004127 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09004128 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004129 releaseNetworkRequest(operation);
4130 }
4131
4132 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004133 * Informs the system whether it should switch to {@code network} regardless of whether it is
4134 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4135 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4136 * the system default network regardless of any other network that's currently connected. If
4137 * {@code always} is true, then the choice is remembered, so that the next time the user
4138 * connects to this network, the system will switch to it.
4139 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004140 * @param network The network to accept.
4141 * @param accept Whether to accept the network even if unvalidated.
4142 * @param always Whether to remember this choice in the future.
4143 *
4144 * @hide
4145 */
lucasline252a742019-03-12 13:08:03 +08004146 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004147 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4148 try {
4149 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004150 } catch (RemoteException e) {
4151 throw e.rethrowFromSystemServer();
4152 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004153 }
4154
4155 /**
lucasline252a742019-03-12 13:08:03 +08004156 * Informs the system whether it should consider the network as validated even if it only has
4157 * partial connectivity. If {@code accept} is true, then the network will be considered as
4158 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4159 * is remembered, so that the next time the user connects to this network, the system will
4160 * switch to it.
4161 *
4162 * @param network The network to accept.
4163 * @param accept Whether to consider the network as validated even if it has partial
4164 * connectivity.
4165 * @param always Whether to remember this choice in the future.
4166 *
4167 * @hide
4168 */
4169 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4170 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4171 try {
4172 mService.setAcceptPartialConnectivity(network, accept, always);
4173 } catch (RemoteException e) {
4174 throw e.rethrowFromSystemServer();
4175 }
4176 }
4177
4178 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004179 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4180 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4181 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4182 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4183 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004184 * @param network The network to accept.
4185 *
4186 * @hide
4187 */
lucasline252a742019-03-12 13:08:03 +08004188 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004189 public void setAvoidUnvalidated(Network network) {
4190 try {
4191 mService.setAvoidUnvalidated(network);
4192 } catch (RemoteException e) {
4193 throw e.rethrowFromSystemServer();
4194 }
4195 }
4196
4197 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004198 * Requests that the system open the captive portal app on the specified network.
4199 *
4200 * @param network The network to log into.
4201 *
4202 * @hide
4203 */
4204 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
4205 public void startCaptivePortalApp(Network network) {
4206 try {
4207 mService.startCaptivePortalApp(network);
4208 } catch (RemoteException e) {
4209 throw e.rethrowFromSystemServer();
4210 }
4211 }
4212
4213 /**
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004214 * Requests that the system open the captive portal app with the specified extras.
4215 *
4216 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4217 * corresponding permission.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004218 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004219 * @param appExtras Extras to include in the app start intent.
4220 * @hide
4221 */
4222 @SystemApi
4223 @TestApi
4224 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhud9736de2019-03-08 16:35:20 +08004225 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004226 try {
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004227 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004228 } catch (RemoteException e) {
4229 throw e.rethrowFromSystemServer();
4230 }
4231 }
4232
4233 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004234 * Determine whether the device is configured to avoid bad wifi.
4235 * @hide
4236 */
4237 @SystemApi
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004238 @RequiresPermission(anyOf = {
4239 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4240 android.Manifest.permission.NETWORK_STACK})
4241 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004242 try {
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004243 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004244 } catch (RemoteException e) {
4245 throw e.rethrowFromSystemServer();
4246 }
4247 }
4248
4249 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004250 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4251 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09004252 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4253 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004254 *
4255 * An example of such an operation might be a time-sensitive foreground activity, such as a
4256 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4257 */
4258 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4259
4260 /**
4261 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4262 * a backup channel for traffic that is primarily going over another network.
4263 *
4264 * An example might be maintaining backup connections to peers or servers for the purpose of
4265 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4266 * on backup paths should be negligible compared to the traffic on the main path.
4267 */
4268 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4269
4270 /**
4271 * It is acceptable to use metered data to improve network latency and performance.
4272 */
4273 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4274
4275 /**
4276 * Return value to use for unmetered networks. On such networks we currently set all the flags
4277 * to true.
4278 * @hide
4279 */
4280 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4281 MULTIPATH_PREFERENCE_HANDOVER |
4282 MULTIPATH_PREFERENCE_RELIABILITY |
4283 MULTIPATH_PREFERENCE_PERFORMANCE;
4284
4285 /** @hide */
4286 @Retention(RetentionPolicy.SOURCE)
4287 @IntDef(flag = true, value = {
4288 MULTIPATH_PREFERENCE_HANDOVER,
4289 MULTIPATH_PREFERENCE_RELIABILITY,
4290 MULTIPATH_PREFERENCE_PERFORMANCE,
4291 })
4292 public @interface MultipathPreference {
4293 }
4294
4295 /**
4296 * Provides a hint to the calling application on whether it is desirable to use the
4297 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4298 * for multipath data transfer on this network when it is not the system default network.
4299 * Applications desiring to use multipath network protocols should call this method before
4300 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004301 *
4302 * @param network The network on which the application desires to use multipath data.
4303 * If {@code null}, this method will return the a preference that will generally
4304 * apply to metered networks.
4305 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4306 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004307 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004308 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004309 try {
4310 return mService.getMultipathPreference(network);
4311 } catch (RemoteException e) {
4312 throw e.rethrowFromSystemServer();
4313 }
4314 }
4315
4316 /**
Stuart Scott984dc852015-03-30 13:17:11 -07004317 * Resets all connectivity manager settings back to factory defaults.
4318 * @hide
4319 */
4320 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07004321 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07004322 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07004323 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004324 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07004325 }
4326 }
4327
4328 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004329 * Binds the current process to {@code network}. All Sockets created in the future
4330 * (and not explicitly bound via a bound SocketFactory from
4331 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4332 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4333 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4334 * work and all host name resolutions will fail. This is by design so an application doesn't
4335 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4336 * To clear binding pass {@code null} for {@code network}. Using individually bound
4337 * Sockets created by Network.getSocketFactory().createSocket() and
4338 * performing network-specific host name resolutions via
4339 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04004340 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004341 *
4342 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4343 * the current binding.
4344 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4345 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004346 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09004347 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04004348 // instantiated.
4349 return setProcessDefaultNetwork(network);
4350 }
4351
4352 /**
4353 * Binds the current process to {@code network}. All Sockets created in the future
4354 * (and not explicitly bound via a bound SocketFactory from
4355 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4356 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4357 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4358 * work and all host name resolutions will fail. This is by design so an application doesn't
4359 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4360 * To clear binding pass {@code null} for {@code network}. Using individually bound
4361 * Sockets created by Network.getSocketFactory().createSocket() and
4362 * performing network-specific host name resolutions via
4363 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4364 * {@code setProcessDefaultNetwork}.
4365 *
4366 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4367 * the current binding.
4368 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4369 * @deprecated This function can throw {@link IllegalStateException}. Use
4370 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4371 * is a direct replacement.
4372 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004373 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004374 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04004375 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004376 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4377
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09004378 if (netId != NETID_UNSET) {
4379 netId = network.getNetIdForResolv();
Paul Jensenc91b5342014-08-27 12:38:45 -04004380 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004381
4382 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4383 return false;
4384 }
4385
4386 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05004387 // Set HTTP proxy system properties to match network.
4388 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09004389 try {
4390 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4391 } catch (SecurityException e) {
4392 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4393 Log.e(TAG, "Can't set proxy properties", e);
4394 }
Paul Jensenc91b5342014-08-27 12:38:45 -04004395 // Must flush DNS cache as new network may have different DNS resolutions.
4396 InetAddress.clearDnsCache();
4397 // Must flush socket pool as idle sockets will be bound to previous network and may
4398 // cause subsequent fetches to be performed on old network.
4399 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04004400 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004401
4402 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004403 }
4404
4405 /**
4406 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004407 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004408 *
4409 * @return {@code Network} to which this process is bound, or {@code null}.
4410 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004411 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004412 public Network getBoundNetworkForProcess() {
4413 // Forcing callers to call thru non-static function ensures ConnectivityManager
4414 // instantiated.
4415 return getProcessDefaultNetwork();
4416 }
4417
4418 /**
4419 * Returns the {@link Network} currently bound to this process via
4420 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4421 *
4422 * @return {@code Network} to which this process is bound, or {@code null}.
4423 * @deprecated Using this function can lead to other functions throwing
4424 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4425 * {@code getBoundNetworkForProcess} is a direct replacement.
4426 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004427 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004428 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004429 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004430 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004431 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004432 return new Network(netId);
4433 }
4434
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004435 private void unsupportedStartingFrom(int version) {
4436 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004437 // The getApplicationInfo() call we make below is not supported in system context. Let
4438 // the call through here, and rely on the fact that ConnectivityService will refuse to
4439 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004440 return;
4441 }
4442
4443 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4444 throw new UnsupportedOperationException(
4445 "This method is not supported in target SDK version " + version + " and above");
4446 }
4447 }
4448
4449 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4450 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004451 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004452 // remove these exemptions. Note that this check is not secure, and apps can still access these
4453 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4454 // so is unsupported and may break in the future. http://b/22728205
4455 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004456 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004457 }
4458
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004459 /**
4460 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004461 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004462 *
4463 * @param network The {@link Network} to bind host resolutions from the current process to, or
4464 * {@code null} to clear the current binding.
4465 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4466 * @hide
4467 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4468 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004469 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004470 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004471 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004472 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004473 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004474 }
Felipe Leme1b103232016-01-22 09:44:57 -08004475
4476 /**
4477 * Device is not restricting metered network activity while application is running on
4478 * background.
4479 */
4480 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4481
4482 /**
4483 * Device is restricting metered network activity while application is running on background,
4484 * but application is allowed to bypass it.
4485 * <p>
4486 * In this state, application should take action to mitigate metered network access.
4487 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4488 */
4489 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4490
4491 /**
4492 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004493 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004494 * In this state, application should not try to use the network while running on background,
4495 * because it would be denied.
4496 */
4497 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4498
Felipe Leme9778f762016-01-27 14:46:39 -08004499 /**
4500 * A change in the background metered network activity restriction has occurred.
4501 * <p>
4502 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4503 * applies to them.
4504 * <p>
4505 * This is only sent to registered receivers, not manifest receivers.
4506 */
4507 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4508 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4509 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4510
Felipe Lemeecfccea2016-01-25 11:48:04 -08004511 /** @hide */
4512 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004513 @IntDef(flag = false, value = {
4514 RESTRICT_BACKGROUND_STATUS_DISABLED,
4515 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4516 RESTRICT_BACKGROUND_STATUS_ENABLED,
4517 })
Felipe Leme1b103232016-01-22 09:44:57 -08004518 public @interface RestrictBackgroundStatus {
4519 }
4520
4521 private INetworkPolicyManager getNetworkPolicyManager() {
4522 synchronized (this) {
4523 if (mNPManager != null) {
4524 return mNPManager;
4525 }
4526 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4527 .getService(Context.NETWORK_POLICY_SERVICE));
4528 return mNPManager;
4529 }
4530 }
4531
4532 /**
4533 * Determines if the calling application is subject to metered network restrictions while
4534 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004535 *
4536 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4537 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4538 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004539 */
4540 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4541 try {
4542 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4543 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004544 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004545 }
4546 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004547
4548 /**
4549 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004550 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4551 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004552 *
4553 * @return Hash of network watchlist config file. Null if config does not exist.
4554 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004555 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004556 public byte[] getNetworkWatchlistConfigHash() {
4557 try {
4558 return mService.getNetworkWatchlistConfigHash();
4559 } catch (RemoteException e) {
4560 Log.e(TAG, "Unable to get watchlist config hash");
4561 throw e.rethrowFromSystemServer();
4562 }
4563 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004564
4565 /**
4566 * Returns the {@code uid} of the owner of a network connection.
4567 *
4568 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and
4569 * {@code IPPROTO_UDP} currently supported.
4570 * @param local The local {@link InetSocketAddress} of a connection.
4571 * @param remote The remote {@link InetSocketAddress} of a connection.
4572 *
4573 * @return {@code uid} if the connection is found and the app has permission to observe it
4574 * (e.g., if it is associated with the calling VPN app's tunnel) or
4575 * {@link android.os.Process#INVALID_UID} if the connection is not found.
Jeff Vander Stoepb58d3fe2019-02-27 13:31:22 -08004576 * Throws {@link SecurityException} if the caller is not the active VPN for the current user.
4577 * Throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004578 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004579 public int getConnectionOwnerUid(int protocol, @NonNull InetSocketAddress local,
4580 @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004581 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4582 try {
4583 return mService.getConnectionOwnerUid(connectionInfo);
4584 } catch (RemoteException e) {
4585 throw e.rethrowFromSystemServer();
4586 }
4587 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004588
4589 private void printStackTrace() {
4590 if (DEBUG) {
4591 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4592 final StringBuffer sb = new StringBuffer();
4593 for (int i = 3; i < callStack.length; i++) {
4594 final String stackTrace = callStack[i].toString();
4595 if (stackTrace == null || stackTrace.contains("android.os")) {
4596 break;
4597 }
4598 sb.append(" [").append(stackTrace).append("]");
4599 }
4600 Log.d(TAG, "StackLog:" + sb.toString());
4601 }
4602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603}