blob: cfa3934b0caeccc936fa490babe80c40cad90647 [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 {
1766 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001767 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001768 public void onStarted() {}
1769 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001770 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001771 public void onStopped() {}
1772 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001773 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001774 public void onError(int error) {}
1775 }
1776
1777 /**
1778 * Allows applications to request that the system periodically send specific packets on their
1779 * behalf, using hardware offload to save battery power.
1780 *
1781 * To request that the system send keepalives, call one of the methods that return a
1782 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1783 * passing in a non-null callback. If the callback is successfully started, the callback's
1784 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1785 * specifying one of the {@code ERROR_*} constants in this class.
1786 *
Chalard Jean4d660112018-06-04 16:52:49 +09001787 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1788 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1789 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001790 *
junyulai48eac1d42018-12-27 17:25:29 +08001791 * @deprecated Use {@link SocketKeepalive} instead.
1792 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001793 * @hide
1794 */
1795 public class PacketKeepalive {
1796
1797 private static final String TAG = "PacketKeepalive";
1798
1799 /** @hide */
1800 public static final int SUCCESS = 0;
1801
1802 /** @hide */
1803 public static final int NO_KEEPALIVE = -1;
1804
1805 /** @hide */
1806 public static final int BINDER_DIED = -10;
1807
1808 /** The specified {@code Network} is not connected. */
1809 public static final int ERROR_INVALID_NETWORK = -20;
1810 /** The specified IP addresses are invalid. For example, the specified source IP address is
1811 * not configured on the specified {@code Network}. */
1812 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1813 /** The requested port is invalid. */
1814 public static final int ERROR_INVALID_PORT = -22;
1815 /** The packet length is invalid (e.g., too long). */
1816 public static final int ERROR_INVALID_LENGTH = -23;
1817 /** The packet transmission interval is invalid (e.g., too short). */
1818 public static final int ERROR_INVALID_INTERVAL = -24;
1819
1820 /** The hardware does not support this request. */
1821 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001822 /** The hardware returned an error. */
1823 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001824
Nathan Harold63dd8132018-02-14 13:09:45 -08001825 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001826 public static final int NATT_PORT = 4500;
1827
Nathan Harold63dd8132018-02-14 13:09:45 -08001828 /** The minimum interval in seconds between keepalive packet transmissions */
1829 public static final int MIN_INTERVAL = 10;
1830
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001831 private final Network mNetwork;
junyulai7c469172019-01-16 20:23:34 +08001832 private final ISocketKeepaliveCallback mCallback;
1833 private final ExecutorService mExecutor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001834
1835 private volatile Integer mSlot;
1836
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001837 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001838 public void stop() {
1839 try {
junyulai7c469172019-01-16 20:23:34 +08001840 mExecutor.execute(() -> {
1841 try {
1842 if (mSlot != null) {
1843 mService.stopKeepalive(mNetwork, mSlot);
1844 }
1845 } catch (RemoteException e) {
1846 Log.e(TAG, "Error stopping packet keepalive: ", e);
1847 throw e.rethrowFromSystemServer();
1848 }
1849 });
1850 } catch (RejectedExecutionException e) {
1851 // The internal executor has already stopped due to previous event.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001852 }
1853 }
1854
1855 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001856 Preconditions.checkNotNull(network, "network cannot be null");
1857 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001858 mNetwork = network;
junyulai7c469172019-01-16 20:23:34 +08001859 mExecutor = Executors.newSingleThreadExecutor();
1860 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001861 @Override
junyulai7c469172019-01-16 20:23:34 +08001862 public void onStarted(int slot) {
1863 Binder.withCleanCallingIdentity(() ->
1864 mExecutor.execute(() -> {
1865 mSlot = slot;
1866 callback.onStarted();
1867 }));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001868 }
junyulai7c469172019-01-16 20:23:34 +08001869
1870 @Override
1871 public void onStopped() {
1872 Binder.withCleanCallingIdentity(() ->
1873 mExecutor.execute(() -> {
1874 mSlot = null;
1875 callback.onStopped();
1876 }));
1877 mExecutor.shutdown();
1878 }
1879
1880 @Override
1881 public void onError(int error) {
1882 Binder.withCleanCallingIdentity(() ->
1883 mExecutor.execute(() -> {
1884 mSlot = null;
1885 callback.onError(error);
1886 }));
1887 mExecutor.shutdown();
1888 }
1889
1890 @Override
1891 public void onDataReceived() {
1892 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1893 // this callback when data is received.
1894 }
1895 };
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001896 }
1897 }
1898
1899 /**
1900 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1901 *
junyulai48eac1d42018-12-27 17:25:29 +08001902 * @deprecated Use {@link #createSocketKeepalive} instead.
1903 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001904 * @hide
1905 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001906 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001907 public PacketKeepalive startNattKeepalive(
1908 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1909 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1910 final PacketKeepalive k = new PacketKeepalive(network, callback);
1911 try {
junyulai7c469172019-01-16 20:23:34 +08001912 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001913 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1914 } catch (RemoteException e) {
1915 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai7c469172019-01-16 20:23:34 +08001916 throw e.rethrowFromSystemServer();
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001917 }
1918 return k;
1919 }
1920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 /**
junyulai48eac1d42018-12-27 17:25:29 +08001922 * Request that keepalives be started on a IPsec NAT-T socket.
1923 *
1924 * @param network The {@link Network} the socket is on.
1925 * @param socket The socket that needs to be kept alive.
1926 * @param source The source address of the {@link UdpEncapsulationSocket}.
1927 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1928 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1929 * must run callback sequentially, otherwise the order of callbacks cannot be
1930 * guaranteed.
1931 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1932 * changes. Must be extended by applications that use this API.
1933 *
junyulai352dc2f2019-01-08 20:04:33 +08001934 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1935 * given socket.
junyulai48eac1d42018-12-27 17:25:29 +08001936 **/
junyulai0c666972019-03-04 22:45:36 +08001937 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai48eac1d42018-12-27 17:25:29 +08001938 @NonNull UdpEncapsulationSocket socket,
1939 @NonNull InetAddress source,
1940 @NonNull InetAddress destination,
1941 @NonNull @CallbackExecutor Executor executor,
1942 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001943 ParcelFileDescriptor dup;
1944 try {
junyulai15178152019-03-27 11:00:37 +08001945 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1946 // which cannot be obtained by the app process.
junyulai0c666972019-03-04 22:45:36 +08001947 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1948 } catch (IOException ignored) {
1949 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1950 // ERROR_INVALID_SOCKET.
1951 dup = new ParcelFileDescriptor(new FileDescriptor());
1952 }
1953 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1954 destination, executor, callback);
junyulai215b8772019-01-15 11:32:44 +08001955 }
1956
1957 /**
1958 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1959 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1960 *
1961 * @param network The {@link Network} the socket is on.
junyulai0c666972019-03-04 22:45:36 +08001962 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1963 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1964 * from that port.
junyulai215b8772019-01-15 11:32:44 +08001965 * @param source The source address of the {@link UdpEncapsulationSocket}.
1966 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1967 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1968 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1969 * must run callback sequentially, otherwise the order of callbacks cannot be
1970 * guaranteed.
1971 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1972 * changes. Must be extended by applications that use this API.
1973 *
junyulai352dc2f2019-01-08 20:04:33 +08001974 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1975 * given socket.
junyulai215b8772019-01-15 11:32:44 +08001976 * @hide
1977 */
1978 @SystemApi
1979 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08001980 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1981 @NonNull ParcelFileDescriptor pfd,
junyulai215b8772019-01-15 11:32:44 +08001982 @NonNull InetAddress source,
1983 @NonNull InetAddress destination,
1984 @NonNull @CallbackExecutor Executor executor,
1985 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001986 ParcelFileDescriptor dup;
1987 try {
junyulai15178152019-03-27 11:00:37 +08001988 // TODO: Consider remove unnecessary dup.
junyulai0c666972019-03-04 22:45:36 +08001989 dup = pfd.dup();
1990 } catch (IOException ignored) {
1991 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1992 // ERROR_INVALID_SOCKET.
1993 dup = new ParcelFileDescriptor(new FileDescriptor());
1994 }
1995 return new NattSocketKeepalive(mService, network, dup,
1996 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08001997 }
1998
1999 /**
junyulai352dc2f2019-01-08 20:04:33 +08002000 * Request that keepalives be started on a TCP socket.
2001 * The socket must be established.
2002 *
2003 * @param network The {@link Network} the socket is on.
2004 * @param socket The socket that needs to be kept alive.
2005 * @param executor The executor on which callback will be invoked. This implementation assumes
2006 * the provided {@link Executor} runs the callbacks in sequence with no
2007 * concurrency. Failing this, no guarantee of correctness can be made. It is
2008 * the responsibility of the caller to ensure the executor provides this
2009 * guarantee. A simple way of creating such an executor is with the standard
2010 * tool {@code Executors.newSingleThreadExecutor}.
2011 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2012 * changes. Must be extended by applications that use this API.
2013 *
2014 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2015 * given socket.
2016 * @hide
2017 */
2018 @SystemApi
2019 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08002020 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai352dc2f2019-01-08 20:04:33 +08002021 @NonNull Socket socket,
2022 @NonNull Executor executor,
2023 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08002024 ParcelFileDescriptor dup;
2025 try {
2026 dup = ParcelFileDescriptor.fromSocket(socket);
2027 } catch (UncheckedIOException ignored) {
2028 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2029 // ERROR_INVALID_SOCKET.
2030 dup = new ParcelFileDescriptor(new FileDescriptor());
2031 }
2032 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai352dc2f2019-01-08 20:04:33 +08002033 }
2034
2035 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 * Ensure that a network route exists to deliver traffic to the specified
2037 * host via the specified network interface. An attempt to add a route that
2038 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002039 *
2040 * <p>This method requires the caller to hold either the
2041 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2042 * or the ability to modify system settings as determined by
2043 * {@link android.provider.Settings.System#canWrite}.</p>
2044 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 * @param networkType the type of the network over which traffic to the specified
2046 * host is to be routed
2047 * @param hostAddress the IP address of the host to which the route is desired
2048 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002049 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002050 * @deprecated Deprecated in favor of the
2051 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2052 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07002053 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002054 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09002055 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002057 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002059 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002060 }
2061
2062 /**
2063 * Ensure that a network route exists to deliver traffic to the specified
2064 * host via the specified network interface. An attempt to add a route that
2065 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002066 *
2067 * <p>This method requires the caller to hold either the
2068 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2069 * or the ability to modify system settings as determined by
2070 * {@link android.provider.Settings.System#canWrite}.</p>
2071 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002072 * @param networkType the type of the network over which traffic to the specified
2073 * host is to be routed
2074 * @param hostAddress the IP address of the host to which the route is desired
2075 * @return {@code true} on success, {@code false} on failure
2076 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002077 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002078 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002079 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002080 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002081 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002082 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002083 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002085 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002087 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089 }
2090
2091 /**
2092 * Returns the value of the setting for background data usage. If false,
2093 * applications should not use the network if the application is not in the
2094 * foreground. Developers should respect this setting, and check the value
2095 * of this before performing any background data operations.
2096 * <p>
2097 * All applications that have background services that use the network
2098 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002099 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002100 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002101 * background data depends on several combined factors, and this method will
2102 * always return {@code true}. Instead, when background data is unavailable,
2103 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002104 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 * @return Whether background data usage is allowed.
2106 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002107 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002109 // assume that background data is allowed; final authority is
2110 // NetworkInfo which may be blocked.
2111 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 }
2113
2114 /**
2115 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002116 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 * @param allowBackgroundData Whether an application should use data while
2118 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002119 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2121 * @see #getBackgroundDataSetting()
2122 * @hide
2123 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002124 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002125 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002127 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002129
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002130 /** {@hide} */
2131 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002132 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002133 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2134 try {
2135 return mService.getActiveNetworkQuotaInfo();
2136 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002137 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002138 }
2139 }
2140
2141 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002142 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002143 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002144 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002145 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002146 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002147 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002148 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
2149 if (b != null) {
2150 try {
2151 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08002152 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08002153 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
Malcolm Chenb455e722017-11-28 15:57:14 -08002154 boolean retVal = it.isUserDataEnabled(subId);
Wink Saville36ffb042014-12-05 11:10:30 -08002155 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2156 + " retVal=" + retVal);
2157 return retVal;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002158 } catch (RemoteException e) {
2159 throw e.rethrowFromSystemServer();
2160 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002161 }
Wink Saville36ffb042014-12-05 11:10:30 -08002162 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002163 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002164 }
2165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002167 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002168 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002169 */
2170 public interface OnNetworkActiveListener {
2171 /**
2172 * Called on the main thread of the process to report that the current data network
2173 * has become active, and it is now a good time to perform any pending network
2174 * operations. Note that this listener only tells you when the network becomes
2175 * active; if at any other time you want to know whether it is active (and thus okay
2176 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002177 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002178 */
Chalard Jean4d660112018-06-04 16:52:49 +09002179 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002180 }
2181
2182 private INetworkManagementService getNetworkManagementService() {
2183 synchronized (this) {
2184 if (mNMService != null) {
2185 return mNMService;
2186 }
2187 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2188 mNMService = INetworkManagementService.Stub.asInterface(b);
2189 return mNMService;
2190 }
2191 }
2192
2193 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002194 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002195
2196 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002197 * Start listening to reports when the system's default data network is active, meaning it is
2198 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2199 * to determine the current state of the system's default network after registering the
2200 * listener.
2201 * <p>
2202 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002203 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002204 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002205 *
2206 * @param l The listener to be told when the network is active.
2207 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002208 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002209 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2210 @Override
2211 public void onNetworkActive() throws RemoteException {
2212 l.onNetworkActive();
2213 }
2214 };
2215
2216 try {
2217 getNetworkManagementService().registerNetworkActivityListener(rl);
2218 mNetworkActivityListeners.put(l, rl);
2219 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002220 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002221 }
2222 }
2223
2224 /**
2225 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002226 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002227 *
2228 * @param l Previously registered listener.
2229 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002230 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002231 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002232 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002233 try {
2234 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2235 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002236 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002237 }
2238 }
2239
2240 /**
2241 * Return whether the data network is currently active. An active network means that
2242 * it is currently in a high power state for performing data transmission. On some
2243 * types of networks, it may be expensive to move and stay in such a state, so it is
2244 * more power efficient to batch network traffic together when the radio is already in
2245 * this state. This method tells you whether right now is currently a good time to
2246 * initiate network traffic, as the network is already active.
2247 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002248 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002249 try {
2250 return getNetworkManagementService().isNetworkActive();
2251 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002252 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002253 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002254 }
2255
2256 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 * {@hide}
2258 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002259 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002260 mContext = Preconditions.checkNotNull(context, "missing context");
2261 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05002262 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002264
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002265 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002266 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002267 public static ConnectivityManager from(Context context) {
2268 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2269 }
2270
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002271 /** @hide */
2272 public NetworkRequest getDefaultRequest() {
2273 try {
2274 // This is not racy as the default request is final in ConnectivityService.
2275 return mService.getDefaultRequest();
2276 } catch (RemoteException e) {
2277 throw e.rethrowFromSystemServer();
2278 }
2279 }
2280
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002281 /* TODO: These permissions checks don't belong in client-side code. Move them to
2282 * services.jar, possibly in com.android.server.net. */
2283
2284 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002285 public static final void enforceChangePermission(Context context) {
2286 int uid = Binder.getCallingUid();
2287 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2288 .getPackageNameForUid(context, uid), true /* throwException */);
2289 }
2290
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002291 /** {@hide} */
2292 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002293 Preconditions.checkNotNull(context, "Context cannot be null");
2294 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002295
Robert Greenwaltedb47662014-09-16 17:54:19 -07002296 if (context.getResources().getStringArray(
2297 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2298 // Have a provisioning app - must only let system apps (which check this app)
2299 // turn on tethering
2300 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002301 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002302 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002303 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002304 // If callingPkg's uid is not same as Binder.getCallingUid(),
2305 // AppOpsService throws SecurityException.
2306 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2307 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002308 }
2309 }
2310
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002311 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002312 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2313 * situations where a Context pointer is unavailable.
2314 * @hide
2315 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002316 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002317 static ConnectivityManager getInstanceOrNull() {
2318 return sInstance;
2319 }
2320
2321 /**
2322 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2323 * situations where a Context pointer is unavailable.
2324 * @hide
2325 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002326 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002327 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002328 private static ConnectivityManager getInstance() {
2329 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002330 throw new IllegalStateException("No ConnectivityManager yet constructed");
2331 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002332 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002333 }
2334
2335 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002336 * Get the set of tetherable, available interfaces. This list is limited by
2337 * device configuration and current interface existence.
2338 *
2339 * @return an array of 0 or more Strings of tetherable interface names.
2340 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002341 * {@hide}
2342 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002343 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002344 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002345 public String[] getTetherableIfaces() {
2346 try {
2347 return mService.getTetherableIfaces();
2348 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002349 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002350 }
2351 }
2352
2353 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002354 * Get the set of tethered interfaces.
2355 *
2356 * @return an array of 0 or more String of currently tethered interface names.
2357 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002358 * {@hide}
2359 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002360 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002361 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002362 public String[] getTetheredIfaces() {
2363 try {
2364 return mService.getTetheredIfaces();
2365 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002366 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002367 }
2368 }
2369
2370 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002371 * Get the set of interface names which attempted to tether but
2372 * failed. Re-attempting to tether may cause them to reset to the Tethered
2373 * state. Alternatively, causing the interface to be destroyed and recreated
2374 * may cause them to reset to the available state.
2375 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2376 * information on the cause of the errors.
2377 *
2378 * @return an array of 0 or more String indicating the interface names
2379 * which failed to tether.
2380 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002381 * {@hide}
2382 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002383 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002384 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002385 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002386 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08002387 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002388 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002389 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002390 }
2391 }
2392
2393 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002394 * Get the set of tethered dhcp ranges.
2395 *
2396 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
2397 * {@hide}
2398 */
2399 public String[] getTetheredDhcpRanges() {
2400 try {
2401 return mService.getTetheredDhcpRanges();
2402 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002403 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002404 }
2405 }
2406
2407 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002408 * Attempt to tether the named interface. This will setup a dhcp server
2409 * on the interface, forward and NAT IP packets and forward DNS requests
2410 * to the best active upstream network interface. Note that if no upstream
2411 * IP network interface is available, dhcp will still run and traffic will be
2412 * allowed between the tethered devices and this device, though upstream net
2413 * access will of course fail until an upstream network interface becomes
2414 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002415 *
2416 * <p>This method requires the caller to hold either the
2417 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2418 * or the ability to modify system settings as determined by
2419 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002420 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002421 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2422 * and WifiStateMachine which need direct access. All other clients should use
2423 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2424 * logic.</p>
2425 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002426 * @param iface the interface name to tether.
2427 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2428 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002429 * {@hide}
2430 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002431 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002432 public int tether(String iface) {
2433 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002434 String pkgName = mContext.getOpPackageName();
2435 Log.i(TAG, "tether caller:" + pkgName);
2436 return mService.tether(iface, pkgName);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002437 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002438 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002439 }
2440 }
2441
2442 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002443 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002444 *
2445 * <p>This method requires the caller to hold either the
2446 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2447 * or the ability to modify system settings as determined by
2448 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002449 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002450 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2451 * and WifiStateMachine which need direct access. All other clients should use
2452 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2453 * logic.</p>
2454 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002455 * @param iface the interface name to untether.
2456 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2457 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002458 * {@hide}
2459 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002460 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002461 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002462 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002463 String pkgName = mContext.getOpPackageName();
2464 Log.i(TAG, "untether caller:" + pkgName);
2465 return mService.untether(iface, pkgName);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002466 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002467 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002468 }
2469 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002470
2471 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002472 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002473 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002474 * due to device configuration.
2475 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002476 * <p>If this app does not have permission to use this API, it will always
2477 * return false rather than throw an exception.</p>
2478 *
2479 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2480 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2481 *
2482 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2483 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2484 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002485 * @return a boolean - {@code true} indicating Tethering is supported.
2486 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002487 * {@hide}
2488 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002489 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002490 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2491 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002492 public boolean isTetheringSupported() {
Chalard Jean8f76fc32017-09-26 15:45:18 +09002493 String pkgName = mContext.getOpPackageName();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002494 try {
Udam Saini0e94c362017-06-07 12:06:28 -07002495 return mService.isTetheringSupported(pkgName);
Chalard Jean8f76fc32017-09-26 15:45:18 +09002496 } catch (SecurityException e) {
2497 // This API is not available to this caller, but for backward-compatibility
2498 // this will just return false instead of throwing.
2499 return false;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002500 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002501 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002502 }
2503 }
2504
2505 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002506 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2507 * @hide
2508 */
2509 @SystemApi
2510 public static abstract class OnStartTetheringCallback {
2511 /**
2512 * Called when tethering has been successfully started.
2513 */
Chalard Jean4d660112018-06-04 16:52:49 +09002514 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002515
2516 /**
2517 * Called when starting tethering failed.
2518 */
Chalard Jean4d660112018-06-04 16:52:49 +09002519 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002520 }
2521
2522 /**
2523 * Convenient overload for
2524 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2525 * handler to run on the current thread's {@link Looper}.
2526 * @hide
2527 */
2528 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07002529 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002530 public void startTethering(int type, boolean showProvisioningUi,
2531 final OnStartTetheringCallback callback) {
2532 startTethering(type, showProvisioningUi, callback, null);
2533 }
2534
2535 /**
2536 * Runs tether provisioning for the given type if needed and then starts tethering if
2537 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2538 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2539 * schedules tether provisioning re-checks if appropriate.
2540 *
2541 * @param type The type of tethering to start. Must be one of
2542 * {@link ConnectivityManager.TETHERING_WIFI},
2543 * {@link ConnectivityManager.TETHERING_USB}, or
2544 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2545 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2546 * is one. This should be true the first time this function is called and also any time
2547 * the user can see this UI. It gives users information from their carrier about the
2548 * check failing and how they can sign up for tethering if possible.
2549 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2550 * of the result of trying to tether.
2551 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2552 * @hide
2553 */
2554 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002555 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002556 public void startTethering(int type, boolean showProvisioningUi,
2557 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002558 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002559
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002560 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2561 @Override
2562 protected void onReceiveResult(int resultCode, Bundle resultData) {
2563 if (resultCode == TETHER_ERROR_NO_ERROR) {
2564 callback.onTetheringStarted();
2565 } else {
2566 callback.onTetheringFailed();
2567 }
2568 }
2569 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002570
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002571 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002572 String pkgName = mContext.getOpPackageName();
2573 Log.i(TAG, "startTethering caller:" + pkgName);
2574 mService.startTethering(type, wrappedCallback, showProvisioningUi, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002575 } catch (RemoteException e) {
2576 Log.e(TAG, "Exception trying to start tethering.", e);
2577 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2578 }
2579 }
2580
2581 /**
2582 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2583 * applicable.
2584 *
2585 * @param type The type of tethering to stop. Must be one of
2586 * {@link ConnectivityManager.TETHERING_WIFI},
2587 * {@link ConnectivityManager.TETHERING_USB}, or
2588 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2589 * @hide
2590 */
2591 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002592 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002593 public void stopTethering(int type) {
2594 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002595 String pkgName = mContext.getOpPackageName();
2596 Log.i(TAG, "stopTethering caller:" + pkgName);
2597 mService.stopTethering(type, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002598 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002599 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002600 }
2601 }
2602
2603 /**
markchien26299ed2019-02-27 14:56:11 +08002604 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2605 * upstream status.
2606 *
2607 *@hide
2608 */
2609 @SystemApi
2610 public abstract static class OnTetheringEventCallback {
2611
2612 /**
2613 * Called when tethering upstream changed. This can be called multiple times and can be
2614 * called any time.
2615 *
2616 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2617 * have any upstream.
2618 */
2619 public void onUpstreamChanged(@Nullable Network network) {}
2620 }
2621
2622 @GuardedBy("mTetheringEventCallbacks")
2623 private final ArrayMap<OnTetheringEventCallback, ITetheringEventCallback>
2624 mTetheringEventCallbacks = new ArrayMap<>();
2625
2626 /**
2627 * Start listening to tethering change events. Any new added callback will receive the last
markchien9f246bd2019-04-03 10:43:09 +08002628 * tethering status right away. If callback is registered when tethering has no upstream or
markchien26299ed2019-02-27 14:56:11 +08002629 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2630 * with a null argument. The same callback object cannot be registered twice.
2631 *
2632 * @param executor the executor on which callback will be invoked.
2633 * @param callback the callback to be called when tethering has change events.
2634 * @hide
2635 */
2636 @SystemApi
2637 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2638 public void registerTetheringEventCallback(
2639 @NonNull @CallbackExecutor Executor executor,
2640 @NonNull final OnTetheringEventCallback callback) {
2641 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2642
2643 synchronized (mTetheringEventCallbacks) {
2644 Preconditions.checkArgument(!mTetheringEventCallbacks.containsKey(callback),
2645 "callback was already registered.");
2646 ITetheringEventCallback remoteCallback = new ITetheringEventCallback.Stub() {
2647 @Override
2648 public void onUpstreamChanged(Network network) throws RemoteException {
2649 Binder.withCleanCallingIdentity(() ->
2650 executor.execute(() -> {
2651 callback.onUpstreamChanged(network);
2652 }));
2653 }
2654 };
2655 try {
2656 String pkgName = mContext.getOpPackageName();
2657 Log.i(TAG, "registerTetheringUpstreamCallback:" + pkgName);
2658 mService.registerTetheringEventCallback(remoteCallback, pkgName);
2659 mTetheringEventCallbacks.put(callback, remoteCallback);
2660 } catch (RemoteException e) {
2661 throw e.rethrowFromSystemServer();
2662 }
2663 }
2664 }
2665
2666 /**
2667 * Remove tethering event callback previously registered with
2668 * {@link #registerTetheringEventCallback}.
2669 *
2670 * @param callback previously registered callback.
2671 * @hide
2672 */
2673 @SystemApi
2674 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2675 public void unregisterTetheringEventCallback(
2676 @NonNull final OnTetheringEventCallback callback) {
2677 synchronized (mTetheringEventCallbacks) {
2678 ITetheringEventCallback remoteCallback = mTetheringEventCallbacks.remove(callback);
2679 Preconditions.checkNotNull(remoteCallback, "callback was not registered.");
2680 try {
2681 String pkgName = mContext.getOpPackageName();
2682 Log.i(TAG, "unregisterTetheringEventCallback:" + pkgName);
2683 mService.unregisterTetheringEventCallback(remoteCallback, pkgName);
2684 } catch (RemoteException e) {
2685 throw e.rethrowFromSystemServer();
2686 }
2687 }
2688 }
2689
2690
2691 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002692 * Get the list of regular expressions that define any tetherable
2693 * USB network interfaces. If USB tethering is not supported by the
2694 * device, this list should be empty.
2695 *
2696 * @return an array of 0 or more regular expression Strings defining
2697 * what interfaces are considered tetherable usb interfaces.
2698 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002699 * {@hide}
2700 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002701 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002702 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002703 public String[] getTetherableUsbRegexs() {
2704 try {
2705 return mService.getTetherableUsbRegexs();
2706 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002707 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002708 }
2709 }
2710
2711 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002712 * Get the list of regular expressions that define any tetherable
2713 * Wifi network interfaces. If Wifi tethering is not supported by the
2714 * device, this list should be empty.
2715 *
2716 * @return an array of 0 or more regular expression Strings defining
2717 * what interfaces are considered tetherable wifi interfaces.
2718 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002719 * {@hide}
2720 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002721 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002722 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002723 public String[] getTetherableWifiRegexs() {
2724 try {
2725 return mService.getTetherableWifiRegexs();
2726 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002727 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002728 }
2729 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002730
Danica Chang6fdd0c62010-08-11 14:54:43 -07002731 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002732 * Get the list of regular expressions that define any tetherable
2733 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2734 * device, this list should be empty.
2735 *
2736 * @return an array of 0 or more regular expression Strings defining
2737 * what interfaces are considered tetherable bluetooth interfaces.
2738 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002739 * {@hide}
2740 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002741 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002742 @UnsupportedAppUsage
Danica Chang6fdd0c62010-08-11 14:54:43 -07002743 public String[] getTetherableBluetoothRegexs() {
2744 try {
2745 return mService.getTetherableBluetoothRegexs();
2746 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002747 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002748 }
2749 }
2750
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002751 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002752 * Attempt to both alter the mode of USB and Tethering of USB. A
2753 * utility method to deal with some of the complexity of USB - will
2754 * attempt to switch to Rndis and subsequently tether the resulting
2755 * interface on {@code true} or turn off tethering and switch off
2756 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002757 *
2758 * <p>This method requires the caller to hold either the
2759 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2760 * or the ability to modify system settings as determined by
2761 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002762 *
2763 * @param enable a boolean - {@code true} to enable tethering
2764 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2765 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002766 * {@hide}
2767 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002768 @UnsupportedAppUsage
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002769 public int setUsbTethering(boolean enable) {
2770 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002771 String pkgName = mContext.getOpPackageName();
2772 Log.i(TAG, "setUsbTethering caller:" + pkgName);
2773 return mService.setUsbTethering(enable, pkgName);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002774 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002775 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002776 }
2777 }
2778
Robert Greenwalt5a735062010-03-02 17:25:02 -08002779 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002780 @SystemApi
Robert Greenwalt5a735062010-03-02 17:25:02 -08002781 public static final int TETHER_ERROR_NO_ERROR = 0;
2782 /** {@hide} */
2783 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2784 /** {@hide} */
2785 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2786 /** {@hide} */
2787 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2788 /** {@hide} */
2789 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2790 /** {@hide} */
2791 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2792 /** {@hide} */
2793 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2794 /** {@hide} */
2795 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2796 /** {@hide} */
2797 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2798 /** {@hide} */
2799 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2800 /** {@hide} */
2801 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002802 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002803 @SystemApi
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002804 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +09002805 /** {@hide} */
2806 public static final int TETHER_ERROR_DHCPSERVER_ERROR = 12;
markchienf2731272019-01-16 17:44:13 +08002807 /** {@hide} */
2808 @SystemApi
2809 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002810
2811 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002812 * Get a more detailed error code after a Tethering or Untethering
2813 * request asynchronously failed.
2814 *
2815 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002816 * @return error The error code of the last error tethering or untethering the named
2817 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002818 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002819 * {@hide}
2820 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002821 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002822 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002823 public int getLastTetherError(String iface) {
2824 try {
2825 return mService.getLastTetherError(iface);
2826 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002827 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002828 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002829 }
2830
markchien9554abf2019-03-06 16:25:00 +08002831 /** @hide */
2832 @Retention(RetentionPolicy.SOURCE)
2833 @IntDef(value = {
2834 TETHER_ERROR_NO_ERROR,
2835 TETHER_ERROR_PROVISION_FAILED,
2836 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2837 })
2838 public @interface EntitlementResultCode {
2839 }
2840
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002841 /**
markchien9554abf2019-03-06 16:25:00 +08002842 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchienf2731272019-01-16 17:44:13 +08002843 * entitlement succeeded.
2844 * @hide
2845 */
2846 @SystemApi
markchien9554abf2019-03-06 16:25:00 +08002847 public interface OnTetheringEntitlementResultListener {
2848 /**
2849 * Called to notify entitlement result.
2850 *
2851 * @param resultCode an int value of entitlement result. It may be one of
2852 * {@link #TETHER_ERROR_NO_ERROR},
2853 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2854 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2855 */
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002856 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchien9554abf2019-03-06 16:25:00 +08002857 }
2858
2859 /**
markchienf2731272019-01-16 17:44:13 +08002860 * Get the last value of the entitlement check on this downstream. If the cached value is
2861 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2862 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2863 * guaranteed that the UI-based entitlement check will complete in any specific time period
2864 * and may in fact never complete. Any successful entitlement check the platform performs for
2865 * any reason will update the cached value.
2866 *
2867 * @param type the downstream type of tethering. Must be one of
2868 * {@link #TETHERING_WIFI},
2869 * {@link #TETHERING_USB}, or
2870 * {@link #TETHERING_BLUETOOTH}.
2871 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchien9554abf2019-03-06 16:25:00 +08002872 * @param executor the executor on which callback will be invoked.
2873 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2874 * notify the caller of the result of entitlement check. The listener may be called zero
2875 * or one time.
markchienf2731272019-01-16 17:44:13 +08002876 * {@hide}
2877 */
2878 @SystemApi
2879 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchien9554abf2019-03-06 16:25:00 +08002880 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2881 @NonNull @CallbackExecutor Executor executor,
2882 @NonNull final OnTetheringEntitlementResultListener listener) {
2883 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2884 ResultReceiver wrappedListener = new ResultReceiver(null) {
2885 @Override
2886 protected void onReceiveResult(int resultCode, Bundle resultData) {
2887 Binder.withCleanCallingIdentity(() ->
2888 executor.execute(() -> {
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002889 listener.onTetheringEntitlementResult(resultCode);
markchien9554abf2019-03-06 16:25:00 +08002890 }));
2891 }
2892 };
2893
2894 try {
2895 String pkgName = mContext.getOpPackageName();
2896 Log.i(TAG, "getLatestTetheringEntitlementResult:" + pkgName);
2897 mService.getLatestTetheringEntitlementResult(type, wrappedListener,
2898 showEntitlementUi, pkgName);
2899 } catch (RemoteException e) {
2900 throw e.rethrowFromSystemServer();
2901 }
2902 }
2903
2904 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002905 * Report network connectivity status. This is currently used only
2906 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002907 * <p>This method requires the caller to hold the permission
2908 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002909 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002910 * @param networkType The type of network you want to report on
2911 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002912 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002913 * {@hide}
2914 */
2915 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002916 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002917 try {
2918 mService.reportInetCondition(networkType, percentage);
2919 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002920 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002921 }
2922 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002923
2924 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002925 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002926 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002927 * the framework to re-evaluate network connectivity and/or switch to another
2928 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002929 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002930 * @param network The {@link Network} the application was attempting to use
2931 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002932 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2933 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002934 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002935 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002936 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002937 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002938 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002939 // One of these will be ignored because it matches system's current state.
2940 // The other will trigger the necessary reevaluation.
2941 mService.reportNetworkConnectivity(network, true);
2942 mService.reportNetworkConnectivity(network, false);
2943 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002944 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002945 }
2946 }
2947
2948 /**
2949 * Report to the framework whether a network has working connectivity.
2950 * This provides a hint to the system that a particular network is providing
2951 * working connectivity or not. In response the framework may re-evaluate
2952 * the network's connectivity and might take further action thereafter.
2953 *
2954 * @param network The {@link Network} the application was attempting to use
2955 * or {@code null} to indicate the current default network.
2956 * @param hasConnectivity {@code true} if the application was able to successfully access the
2957 * Internet using {@code network} or {@code false} if not.
2958 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002959 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002960 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002961 try {
2962 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002963 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002964 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002965 }
2966 }
2967
2968 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002969 * Set a network-independent global http proxy. This is not normally what you want
2970 * for typical HTTP proxies - they are general network dependent. However if you're
2971 * doing something unusual like general internal filtering this may be useful. On
2972 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002973 *
2974 * @param p A {@link ProxyInfo} object defining the new global
2975 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002976 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002977 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002978 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Jason Monk207900c2014-04-25 15:00:09 -04002979 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002980 try {
2981 mService.setGlobalProxy(p);
2982 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002983 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002984 }
2985 }
2986
2987 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002988 * Retrieve any network-independent global HTTP proxy.
2989 *
Jason Monk207900c2014-04-25 15:00:09 -04002990 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002991 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002992 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002993 */
Jason Monk207900c2014-04-25 15:00:09 -04002994 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002995 try {
2996 return mService.getGlobalProxy();
2997 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002998 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002999 }
3000 }
3001
3002 /**
Paul Jensencee9b512015-05-06 07:32:40 -04003003 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3004 * network-specific HTTP proxy. If {@code network} is null, the
3005 * network-specific proxy returned is the proxy of the default active
3006 * network.
3007 *
3008 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3009 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3010 * or when {@code network} is {@code null},
3011 * the {@code ProxyInfo} for the default active network. Returns
3012 * {@code null} when no proxy applies or the caller doesn't have
3013 * permission to use {@code network}.
3014 * @hide
3015 */
3016 public ProxyInfo getProxyForNetwork(Network network) {
3017 try {
3018 return mService.getProxyForNetwork(network);
3019 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003020 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04003021 }
3022 }
3023
3024 /**
Paul Jensene0bef712014-12-10 15:12:18 -05003025 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3026 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04003027 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05003028 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003029 *
Jason Monk207900c2014-04-25 15:00:09 -04003030 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003031 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07003032 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003033 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05003034 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04003035 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07003036 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003037
3038 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003039 * Returns true if the hardware supports the given network type
3040 * else it returns false. This doesn't indicate we have coverage
3041 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003042 * hardware supports it. For example a GSM phone without a SIM
3043 * should still return {@code true} for mobile data, but a wifi only
3044 * tablet would return {@code false}.
3045 *
3046 * @param networkType The network type we'd like to check
3047 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003048 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003049 * @hide
3050 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003051 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003052 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09003053 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003054 public boolean isNetworkSupported(int networkType) {
3055 try {
3056 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003057 } catch (RemoteException e) {
3058 throw e.rethrowFromSystemServer();
3059 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003060 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003061
3062 /**
3063 * Returns if the currently active data network is metered. A network is
3064 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003065 * that connection due to monetary costs, data limitations or
3066 * battery/performance issues. You should check this before doing large
3067 * data transfers, and warn the user or delay the operation until another
3068 * network is available.
3069 *
3070 * @return {@code true} if large transfers should be avoided, otherwise
3071 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003072 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003073 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003074 public boolean isActiveNetworkMetered() {
3075 try {
3076 return mService.isActiveNetworkMetered();
3077 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003078 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003079 }
3080 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003081
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003082 /**
3083 * If the LockdownVpn mechanism is enabled, updates the vpn
3084 * with a reload of its profile.
3085 *
3086 * @return a boolean with {@code} indicating success
3087 *
3088 * <p>This method can only be called by the system UID
3089 * {@hide}
3090 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003091 public boolean updateLockdownVpn() {
3092 try {
3093 return mService.updateLockdownVpn();
3094 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003095 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003096 }
3097 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07003098
3099 /**
Wink Saville948282b2013-08-29 08:55:16 -07003100 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07003101 *
Wink Savilleab9321d2013-06-29 21:10:57 -07003102 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07003103 *
3104 * @return time out that will be used, maybe less that suggestedTimeOutMs
3105 * -1 if an error.
3106 *
3107 * {@hide}
3108 */
Wink Saville948282b2013-08-29 08:55:16 -07003109 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003110 int timeOutMs = -1;
3111 try {
Wink Saville948282b2013-08-29 08:55:16 -07003112 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07003113 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003114 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07003115 }
3116 return timeOutMs;
3117 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003118
3119 /**
Wink Saville42d4f082013-07-20 20:31:59 -07003120 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003121 * {@hide}
3122 */
3123 public String getMobileProvisioningUrl() {
3124 try {
3125 return mService.getMobileProvisioningUrl();
3126 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003127 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003128 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003129 }
Wink Saville42d4f082013-07-20 20:31:59 -07003130
3131 /**
Wink Saville948282b2013-08-29 08:55:16 -07003132 * Set sign in error notification to visible or in visible
3133 *
Wink Saville948282b2013-08-29 08:55:16 -07003134 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04003135 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07003136 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003137 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07003138 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003139 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003140 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04003141 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07003142 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003143 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07003144 }
3145 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003146
3147 /**
3148 * Set the value for enabling/disabling airplane mode
3149 *
3150 * @param enable whether to enable airplane mode or not
3151 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003152 * @hide
3153 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003154 @RequiresPermission(anyOf = {
3155 android.Manifest.permission.NETWORK_SETTINGS,
3156 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3157 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09003158 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003159 public void setAirplaneMode(boolean enable) {
3160 try {
3161 mService.setAirplaneMode(enable);
3162 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003163 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003164 }
3165 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003166
Chalard Jean05ab6812018-05-02 21:14:54 +09003167 /** {@hide} - returns the factory serial number */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003168 @UnsupportedAppUsage
Chalard Jean05ab6812018-05-02 21:14:54 +09003169 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003170 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003171 return mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003172 } catch (RemoteException e) {
3173 throw e.rethrowFromSystemServer();
3174 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003175 }
3176
3177 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00003178 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Robert Greenwalta67be032014-05-16 15:49:14 -07003179 public void unregisterNetworkFactory(Messenger messenger) {
3180 try {
3181 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003182 } catch (RemoteException e) {
3183 throw e.rethrowFromSystemServer();
3184 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003185 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003186
Chalard Jean05ab6812018-05-02 21:14:54 +09003187 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3188 // of dependent changes that would conflict throughout the automerger graph. Having this
3189 // temporarily helps with the process of going through with all these dependent changes across
3190 // the entire tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05003191 /**
3192 * @hide
3193 * Register a NetworkAgent with ConnectivityService.
3194 * @return NetID corresponding to NetworkAgent.
3195 */
3196 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003197 NetworkCapabilities nc, int score, NetworkMisc misc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003198 return registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3199 NetworkFactory.SerialNumber.NONE);
3200 }
3201
3202 /**
3203 * @hide
3204 * Register a NetworkAgent with ConnectivityService.
3205 * @return NetID corresponding to NetworkAgent.
3206 */
3207 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
3208 NetworkCapabilities nc, int score, NetworkMisc misc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003209 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003210 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3211 factorySerialNumber);
Paul Jensen31a94f42015-02-13 14:18:39 -05003212 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003213 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05003214 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003215 }
3216
Robert Greenwalt9258c642014-03-26 16:47:06 -07003217 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003218 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3219 * changes. Should be extended by applications wanting notifications.
3220 *
3221 * A {@code NetworkCallback} is registered by calling
3222 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3223 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09003224 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09003225 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3226 * A {@code NetworkCallback} should be registered at most once at any time.
3227 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003228 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003229 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003230 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003231 * Called when the framework connects to a new network to evaluate whether it satisfies this
3232 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3233 * callback. There is no guarantee that this new network will satisfy any requests, or that
3234 * the network will stay connected for longer than the time necessary to evaluate it.
3235 * <p>
3236 * Most applications <b>should not</b> act on this callback, and should instead use
3237 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3238 * the framework in properly evaluating the network &mdash; for example, an application that
3239 * can automatically log in to a captive portal without user intervention.
3240 *
3241 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09003242 *
3243 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07003244 */
paulhu3d67f532019-03-22 16:35:06 +08003245 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003246
3247 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003248 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003249 * This callback may be called more than once if the {@link Network} that is
3250 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003251 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003252 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003253 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3254 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08003255 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003256 * @hide
3257 */
paulhu3d67f532019-03-22 16:35:06 +08003258 public void onAvailable(@NonNull Network network,
3259 @NonNull NetworkCapabilities networkCapabilities,
3260 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003261 // Internally only this method is called when a new network is available, and
3262 // it calls the callback in the same way and order that older versions used
3263 // to call so as not to change the behavior.
3264 onAvailable(network);
3265 if (!networkCapabilities.hasCapability(
3266 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3267 onNetworkSuspended(network);
3268 }
3269 onCapabilitiesChanged(network, networkCapabilities);
3270 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003271 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003272 }
3273
3274 /**
3275 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean599ce752019-08-30 16:27:28 +09003276 *
3277 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3278 * be available at the same time, and onAvailable will be called for each of these as they
3279 * appear.
3280 *
3281 * <p>For callbacks registered with {@link #requestNetwork} and
3282 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3283 * is the new best network for this request and is now tracked by this callback ; this
3284 * callback will no longer receive method calls about other networks that may have been
3285 * passed to this method previously. The previously-best network may have disconnected, or
3286 * it may still be around and the newly-best network may simply be better.
3287 *
3288 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3289 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3290 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3291 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3292 *
3293 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3294 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3295 * this callback as this is prone to race conditions (there is no guarantee the objects
3296 * returned by these methods will be current). Instead, wait for a call to
3297 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3298 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3299 * to be well-ordered with respect to other callbacks.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003300 *
3301 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003302 */
paulhu3d67f532019-03-22 16:35:06 +08003303 public void onAvailable(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003304
3305 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003306 * Called when the network is about to be lost, typically because there are no outstanding
3307 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3308 * with the new replacement network for graceful handover. This method is not guaranteed
3309 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3310 * network is suddenly disconnected.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003311 *
Chalard Jean599ce752019-08-30 16:27:28 +09003312 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3313 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3314 * this callback as this is prone to race conditions ; calling these methods while in a
3315 * callback may return an outdated or even a null object.
3316 *
3317 * @param network The {@link Network} that is about to be lost.
3318 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3319 * connected for graceful handover; note that the network may still
3320 * suffer a hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003321 */
paulhu3d67f532019-03-22 16:35:06 +08003322 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003323
3324 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003325 * Called when a network disconnects or otherwise no longer satisfies this request or
3326 * callback.
3327 *
3328 * <p>If the callback was registered with requestNetwork() or
3329 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3330 * returned by onAvailable() when that network is lost and no other network satisfies
3331 * the criteria of the request.
3332 *
3333 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3334 * each network which no longer satisfies the criteria of the callback.
3335 *
3336 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3337 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3338 * this callback as this is prone to race conditions ; calling these methods while in a
3339 * callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003340 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003341 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003342 */
paulhu3d67f532019-03-22 16:35:06 +08003343 public void onLost(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003344
3345 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003346 * Called if no network is found within the timeout time specified in
Etan Cohenddb720a2019-01-08 12:09:18 -08003347 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3348 * requested network request cannot be fulfilled (whether or not a timeout was
3349 * specified). When this callback is invoked the associated
Etan Cohenaebf17e2017-03-01 12:47:28 -08003350 * {@link NetworkRequest} will have already been removed and released, as if
3351 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003352 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003353 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003354
3355 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003356 * Called when the network corresponding to this request changes capabilities but still
3357 * satisfies the requested criteria.
3358 *
3359 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3360 * to be called immediately after {@link #onAvailable}.
3361 *
3362 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3363 * ConnectivityManager methods in this callback as this is prone to race conditions :
3364 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003365 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003366 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003367 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3368 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003369 */
paulhu3d67f532019-03-22 16:35:06 +08003370 public void onCapabilitiesChanged(@NonNull Network network,
3371 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003372
3373 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003374 * Called when the network corresponding to this request changes {@link LinkProperties}.
3375 *
3376 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3377 * to be called immediately after {@link #onAvailable}.
3378 *
3379 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3380 * ConnectivityManager methods in this callback as this is prone to race conditions :
3381 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003382 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003383 * @param network The {@link Network} whose link properties have changed.
3384 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003385 */
paulhu3d67f532019-03-22 16:35:06 +08003386 public void onLinkPropertiesChanged(@NonNull Network network,
3387 @NonNull LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003388
Robert Greenwalt8d482522015-06-24 13:23:42 -07003389 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003390 * Called when the network the framework connected to for this request suspends data
3391 * transmission temporarily.
3392 *
3393 * <p>This generally means that while the TCP connections are still live temporarily
3394 * network data fails to transfer. To give a specific example, this is used on cellular
3395 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3396 * means read operations on sockets on this network will block once the buffers are
3397 * drained, and write operations will block once the buffers are full.
3398 *
3399 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3400 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3401 * this callback as this is prone to race conditions (there is no guarantee the objects
3402 * returned by these methods will be current).
3403 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003404 * @hide
3405 */
paulhu3d67f532019-03-22 16:35:06 +08003406 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003407
3408 /**
3409 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003410 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3411 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean599ce752019-08-30 16:27:28 +09003412
3413 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3414 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3415 * this callback as this is prone to race conditions : calling these methods while in a
3416 * callback may return an outdated or even a null object.
3417 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003418 * @hide
3419 */
paulhu3d67f532019-03-22 16:35:06 +08003420 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003421
junyulai05986c62018-08-07 19:50:45 +08003422 /**
3423 * Called when access to the specified network is blocked or unblocked.
3424 *
Chalard Jean599ce752019-08-30 16:27:28 +09003425 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3426 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3427 * this callback as this is prone to race conditions : calling these methods while in a
3428 * callback may return an outdated or even a null object.
3429 *
junyulai05986c62018-08-07 19:50:45 +08003430 * @param network The {@link Network} whose blocked status has changed.
3431 * @param blocked The blocked status of this {@link Network}.
3432 */
junyulai0c666972019-03-04 22:45:36 +08003433 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai05986c62018-08-07 19:50:45 +08003434
Robert Greenwalt6078b502014-06-11 16:05:07 -07003435 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003436 }
3437
Hugo Benichicb883232017-05-11 13:16:17 +09003438 /**
3439 * Constant error codes used by ConnectivityService to communicate about failures and errors
3440 * across a Binder boundary.
3441 * @hide
3442 */
3443 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003444 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003445 }
3446
3447 /** @hide */
3448 public static class TooManyRequestsException extends RuntimeException {}
3449
3450 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3451 switch (e.errorCode) {
3452 case Errors.TOO_MANY_REQUESTS:
3453 return new TooManyRequestsException();
3454 default:
3455 Log.w(TAG, "Unknown service error code " + e.errorCode);
3456 return new RuntimeException(e);
3457 }
3458 }
3459
Robert Greenwalt9258c642014-03-26 16:47:06 -07003460 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003461 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003462 public static final int CALLBACK_PRECHECK = BASE + 1;
3463 /** @hide */
3464 public static final int CALLBACK_AVAILABLE = BASE + 2;
3465 /** @hide arg1 = TTL */
3466 public static final int CALLBACK_LOSING = BASE + 3;
3467 /** @hide */
3468 public static final int CALLBACK_LOST = BASE + 4;
3469 /** @hide */
3470 public static final int CALLBACK_UNAVAIL = BASE + 5;
3471 /** @hide */
3472 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3473 /** @hide */
3474 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003475 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003476 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003477 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003478 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003479 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003480 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003481 /** @hide */
3482 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003483
Erik Kline57faba92015-11-25 12:49:38 +09003484 /** @hide */
3485 public static String getCallbackName(int whichCallback) {
3486 switch (whichCallback) {
3487 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3488 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3489 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3490 case CALLBACK_LOST: return "CALLBACK_LOST";
3491 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3492 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3493 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003494 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3495 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3496 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003497 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003498 default:
3499 return Integer.toString(whichCallback);
3500 }
3501 }
3502
Robert Greenwalt562cc542014-05-15 18:07:26 -07003503 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003504 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003505 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003506
Hugo Benichid42650f2016-07-06 22:53:17 +09003507 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003508 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003509 }
3510
Hugo Benichi2583ef02017-02-02 17:02:36 +09003511 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003512 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003513 }
3514
Robert Greenwalt9258c642014-03-26 16:47:06 -07003515 @Override
3516 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003517 if (message.what == EXPIRE_LEGACY_REQUEST) {
3518 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3519 return;
3520 }
3521
3522 final NetworkRequest request = getObject(message, NetworkRequest.class);
3523 final Network network = getObject(message, Network.class);
3524 final NetworkCallback callback;
3525 synchronized (sCallbacks) {
3526 callback = sCallbacks.get(request);
Etan Cohen4a62d1d2019-05-21 12:06:04 -07003527 if (callback == null) {
3528 Log.w(TAG,
3529 "callback not found for " + getCallbackName(message.what) + " message");
3530 return;
3531 }
Etan Cohen9b09a162019-04-16 15:07:55 -07003532 if (message.what == CALLBACK_UNAVAIL) {
3533 sCallbacks.remove(request);
3534 callback.networkRequest = ALREADY_UNREGISTERED;
3535 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003536 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003537 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003538 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003539 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003540
Robert Greenwalt9258c642014-03-26 16:47:06 -07003541 switch (message.what) {
3542 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003543 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003544 break;
3545 }
3546 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003547 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3548 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003549 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003550 break;
3551 }
3552 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003553 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003554 break;
3555 }
3556 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003557 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003558 break;
3559 }
3560 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003561 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003562 break;
3563 }
3564 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003565 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3566 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003567 break;
3568 }
3569 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003570 LinkProperties lp = getObject(message, LinkProperties.class);
3571 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003572 break;
3573 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003574 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003575 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003576 break;
3577 }
3578 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003579 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003580 break;
3581 }
junyulai05986c62018-08-07 19:50:45 +08003582 case CALLBACK_BLK_CHANGED: {
3583 boolean blocked = message.arg1 != 0;
3584 callback.onBlockedStatusChanged(network, blocked);
3585 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003586 }
3587 }
3588
Hugo Benichid42650f2016-07-06 22:53:17 +09003589 private <T> T getObject(Message msg, Class<T> c) {
3590 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003591 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003592 }
3593
Hugo Benichi2583ef02017-02-02 17:02:36 +09003594 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003595 synchronized (sCallbacks) {
3596 if (sCallbackHandler == null) {
3597 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003598 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003599 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003600 }
3601 }
3602
Hugo Benichi6f260f32017-02-03 14:18:44 +09003603 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3604 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003605
Hugo Benichi6f260f32017-02-03 14:18:44 +09003606 private static final int LISTEN = 1;
3607 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003608
Hugo Benichi6f260f32017-02-03 14:18:44 +09003609 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3610 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003611 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003612 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003613 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003614 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003615 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003616 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003617 if (callback.networkRequest != null
3618 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003619 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3620 // and requests (http://b/20701525).
3621 Log.e(TAG, "NetworkCallback was already registered");
3622 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003623 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003624 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003625 if (action == LISTEN) {
Hugo Benichid42650f2016-07-06 22:53:17 +09003626 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04003627 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003628 request = mService.requestNetwork(
3629 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04003630 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003631 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003632 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003633 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003634 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003635 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003636 } catch (RemoteException e) {
3637 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003638 } catch (ServiceSpecificException e) {
3639 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003640 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003641 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003642 }
3643
3644 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003645 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003646 *
3647 * This is temporarily public @hide so it can be called by system code that uses the
3648 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
3649 * instead network notifications.
3650 *
3651 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
3652 *
3653 * @hide
3654 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003655 public void requestNetwork(@NonNull NetworkRequest request,
3656 @NonNull NetworkCallback networkCallback, int timeoutMs, int legacyType,
3657 @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003658 CallbackHandler cbHandler = new CallbackHandler(handler);
3659 NetworkCapabilities nc = request.networkCapabilities;
3660 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003661 }
3662
3663 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003664 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003665 *
Chalard Jean599ce752019-08-30 16:27:28 +09003666 * <p>This method will attempt to find the best network that matches the passed
3667 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3668 * criteria. The platform will evaluate which network is the best at its own discretion.
3669 * Throughput, latency, cost per byte, policy, user preference and other considerations
3670 * may be factored in the decision of what is considered the best network.
3671 *
3672 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3673 * matching this request, while always attempting to match the request to a better network if
3674 * possible. If a better match is found, the platform will switch this request to the now-best
3675 * network and inform the app of the newly best network by invoking
3676 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3677 * will not try to maintain any other network than the best one currently matching the request:
3678 * a network not matching any network request may be disconnected at any time.
3679 *
3680 * <p>For example, an application could use this method to obtain a connected cellular network
3681 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3682 * radio to consume additional power. Or, an application could inform the system that it wants
3683 * a network supporting sending MMSes and have the system let it know about the currently best
3684 * MMS-supporting network through the provided {@link NetworkCallback}.
3685 *
3686 * <p>The status of the request can be followed by listening to the various callbacks described
3687 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3688 * used to direct traffic to the network (although accessing some networks may be subject to
3689 * holding specific permissions). Callers will learn about the specific characteristics of the
3690 * network through
3691 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3692 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3693 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3694 * matching the request at any given time; therefore when a better network matching the request
3695 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3696 * with the new network after which no further updates are given about the previously-best
3697 * network, unless it becomes the best again at some later time. All callbacks are invoked
3698 * in order on the same thread, which by default is a thread created by the framework running
3699 * in the app.
3700 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3701 * callbacks are invoked.
3702 *
3703 * <p>This{@link NetworkRequest} will live until released via
3704 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3705 * which point the system may let go of the network at any time.
3706 *
3707 * <p>A version of this method which takes a timeout is
3708 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3709 * wait for a limited amount of time for the network to become unavailable.
3710 *
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003711 * <p>It is presently unsupported to request a network with mutable
3712 * {@link NetworkCapabilities} such as
3713 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3714 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3715 * as these {@code NetworkCapabilities} represent states that a particular
3716 * network may never attain, and whether a network will attain these states
3717 * is unknown prior to bringing up the network so the framework does not
Chalard Jean599ce752019-08-30 16:27:28 +09003718 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003719 *
3720 * <p>This method requires the caller to hold either the
3721 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3722 * or the ability to modify system settings as determined by
3723 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003724 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003725 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003726 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3727 * the callback must not be shared - it uniquely specifies this request.
3728 * The callback is invoked on the default internal Handler.
Chalard Jean92c8b672019-05-13 15:13:58 +09003729 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3730 * @throws SecurityException if missing the appropriate permissions.
3731 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003732 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003733 public void requestNetwork(@NonNull NetworkRequest request,
3734 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003735 requestNetwork(request, networkCallback, getDefaultHandler());
3736 }
3737
3738 /**
3739 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3740 *
Chalard Jean599ce752019-08-30 16:27:28 +09003741 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3742 * but runs all the callbacks on the passed Handler.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003743 *
Chalard Jean599ce752019-08-30 16:27:28 +09003744 * <p>This method has the same permission requirements as
3745 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3746 * the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003747 *
3748 * @param request {@link NetworkRequest} describing this request.
3749 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3750 * the callback must not be shared - it uniquely specifies this request.
3751 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003752 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003753 public void requestNetwork(@NonNull NetworkRequest request,
3754 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003755 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3756 CallbackHandler cbHandler = new CallbackHandler(handler);
3757 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003758 }
3759
3760 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003761 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3762 * by a timeout.
3763 *
3764 * This function behaves identically to the non-timed-out version
3765 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3766 * is not found within the given time (in milliseconds) the
3767 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3768 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3769 * not have to be released if timed-out (it is automatically released). Unregistering a
3770 * request that timed out is not an error.
3771 *
3772 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3773 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3774 * for that purpose. Calling this method will attempt to bring up the requested network.
3775 *
Chalard Jean599ce752019-08-30 16:27:28 +09003776 * <p>This method has the same permission requirements as
3777 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3778 * the same conditions.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003779 *
3780 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003781 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3782 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003783 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3784 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3785 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003786 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003787 public void requestNetwork(@NonNull NetworkRequest request,
3788 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003789 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003790 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003791 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003792 }
3793
Hugo Benichi2583ef02017-02-02 17:02:36 +09003794 /**
3795 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3796 * by a timeout.
3797 *
Chalard Jean599ce752019-08-30 16:27:28 +09003798 * This method behaves identically to
3799 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3800 * on the passed Handler.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003801 *
Chalard Jean599ce752019-08-30 16:27:28 +09003802 * <p>This method has the same permission requirements as
3803 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} and throws the same exceptions
3804 * in the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003805 *
3806 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003807 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3808 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003809 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003810 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3811 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003812 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003813 public void requestNetwork(@NonNull NetworkRequest request,
3814 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003815 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003816 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3817 CallbackHandler cbHandler = new CallbackHandler(handler);
3818 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003819 }
3820
3821 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003822 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003823 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003824 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003825 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003826 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3827 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003828 */
Erik Kline90e93072014-11-19 12:12:24 +09003829 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003830
3831 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003832 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003833 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003834 * {@link android.content.Intent#getParcelableExtra(String)}.
3835 */
Erik Kline90e93072014-11-19 12:12:24 +09003836 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003837
3838
3839 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003840 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003841 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003842 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003843 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003844 * the request may outlive the calling application and get called back when a suitable
3845 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003846 * <p>
3847 * The operation is an Intent broadcast that goes to a broadcast receiver that
3848 * you registered with {@link Context#registerReceiver} or through the
3849 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3850 * <p>
3851 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003852 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3853 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003854 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003855 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003856 * Intent to reserve the network or it will be released shortly after the Intent
3857 * is processed.
3858 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003859 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003860 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003861 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003862 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003863 * The request may be released normally by calling
3864 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003865 * <p>It is presently unsupported to request a network with either
3866 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3867 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3868 * as these {@code NetworkCapabilities} represent states that a particular
3869 * network may never attain, and whether a network will attain these states
3870 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003871 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003872 *
3873 * <p>This method requires the caller to hold either the
3874 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3875 * or the ability to modify system settings as determined by
3876 * {@link android.provider.Settings.System#canWrite}.</p>
3877 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003878 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003879 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003880 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003881 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean92c8b672019-05-13 15:13:58 +09003882 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3883 * @throws SecurityException if missing the appropriate permissions.
3884 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003885 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003886 public void requestNetwork(@NonNull NetworkRequest request,
3887 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003888 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003889 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003890 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003891 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003892 } catch (RemoteException e) {
3893 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003894 } catch (ServiceSpecificException e) {
3895 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003896 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003897 }
3898
3899 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003900 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3901 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003902 * This method has the same behavior as
3903 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003904 * releasing network resources and disconnecting.
3905 *
3906 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3907 * PendingIntent passed to
3908 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3909 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3910 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003911 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003912 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003913 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003914 try {
3915 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003916 } catch (RemoteException e) {
3917 throw e.rethrowFromSystemServer();
3918 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003919 }
3920
Hugo Benichie7678512017-05-09 15:19:01 +09003921 private static void checkPendingIntentNotNull(PendingIntent intent) {
3922 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3923 }
3924
3925 private static void checkCallbackNotNull(NetworkCallback callback) {
3926 Preconditions.checkNotNull(callback, "null NetworkCallback");
3927 }
3928
3929 private static void checkTimeout(int timeoutMs) {
3930 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003931 }
3932
3933 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003934 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003935 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003936 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3937 * called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003938 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003939 * @param request {@link NetworkRequest} describing this request.
3940 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3941 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003942 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003943 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003944 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003945 public void registerNetworkCallback(@NonNull NetworkRequest request,
3946 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003947 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3948 }
3949
3950 /**
3951 * Registers to receive notifications about all networks which satisfy the given
3952 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003953 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3954 * called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003955 *
3956 * @param request {@link NetworkRequest} describing this request.
3957 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3958 * networks change state.
3959 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003960 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003961 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003962 public void registerNetworkCallback(@NonNull NetworkRequest request,
3963 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003964 CallbackHandler cbHandler = new CallbackHandler(handler);
3965 NetworkCapabilities nc = request.networkCapabilities;
3966 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003967 }
3968
3969 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003970 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3971 * {@link NetworkRequest}.
3972 *
3973 * This function behaves identically to the version that takes a NetworkCallback, but instead
3974 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3975 * the request may outlive the calling application and get called back when a suitable
3976 * network is found.
3977 * <p>
3978 * The operation is an Intent broadcast that goes to a broadcast receiver that
3979 * you registered with {@link Context#registerReceiver} or through the
3980 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3981 * <p>
3982 * The operation Intent is delivered with two extras, a {@link Network} typed
3983 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3984 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3985 * the original requests parameters.
3986 * <p>
3987 * If there is already a request for this Intent registered (with the equality of
3988 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3989 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3990 * <p>
3991 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003992 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003993 * @param request {@link NetworkRequest} describing this request.
3994 * @param operation Action to perform when the network is available (corresponds
3995 * to the {@link NetworkCallback#onAvailable} call. Typically
3996 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3997 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003998 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003999 public void registerNetworkCallback(@NonNull NetworkRequest request,
4000 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004001 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004002 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04004003 try {
4004 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004005 } catch (RemoteException e) {
4006 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09004007 } catch (ServiceSpecificException e) {
4008 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004009 }
Paul Jensen694f2b82015-06-17 14:15:39 -04004010 }
4011
4012 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004013 * Registers to receive notifications about changes in the system default network. The callbacks
4014 * will continue to be called until either the application exits or
4015 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09004016 *
4017 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4018 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004019 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09004020 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004021 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004022 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004023 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4024 }
4025
4026 /**
4027 * Registers to receive notifications about changes in the system default network. The callbacks
4028 * will continue to be called until either the application exits or
4029 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004030 *
4031 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4032 * system default network changes.
4033 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004034 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004035 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004036 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4037 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09004038 // This works because if the NetworkCapabilities are null,
4039 // ConnectivityService takes them from the default request.
4040 //
4041 // Since the capabilities are exactly the same as the default request's
4042 // capabilities, this request is guaranteed, at all times, to be
4043 // satisfied by the same network, if any, that satisfies the default
4044 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004045 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09004046 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4047 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09004048 }
4049
4050 /**
fengludb571472015-04-21 17:12:05 -07004051 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4052 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4053 * network connection for updated bandwidth information. The caller will be notified via
4054 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004055 * method assumes that the caller has previously called
4056 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4057 * changes.
fenglub15e72b2015-03-20 11:29:56 -07004058 *
fengluae519192015-04-27 14:28:04 -07004059 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07004060 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07004061 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004062 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004063 try {
fengludb571472015-04-21 17:12:05 -07004064 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07004065 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004066 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07004067 }
4068 }
4069
4070 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09004071 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004072 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4073 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4074 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09004075 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4076 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004077 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09004078 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4079 * triggering it as soon as this call returns.
4080 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07004081 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004082 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004083 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004084 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004085 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09004086 final List<NetworkRequest> reqs = new ArrayList<>();
4087 // Find all requests associated to this callback and stop callback triggers immediately.
4088 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4089 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09004090 Preconditions.checkArgument(networkCallback.networkRequest != null,
4091 "NetworkCallback was not registered");
Etan Cohen9b09a162019-04-16 15:07:55 -07004092 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4093 Log.d(TAG, "NetworkCallback was already unregistered");
4094 return;
4095 }
Hugo Benichidafed3d2017-03-06 09:17:06 +09004096 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4097 if (e.getValue() == networkCallback) {
4098 reqs.add(e.getKey());
4099 }
4100 }
4101 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4102 for (NetworkRequest r : reqs) {
4103 try {
4104 mService.releaseNetworkRequest(r);
4105 } catch (RemoteException e) {
4106 throw e.rethrowFromSystemServer();
4107 }
4108 // Only remove mapping if rpc was successful.
4109 sCallbacks.remove(r);
4110 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09004111 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004112 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004113 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004114
4115 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004116 * Unregisters a callback previously registered via
4117 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4118 *
4119 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4120 * PendingIntent passed to
4121 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4122 * Cannot be null.
4123 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004124 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09004125 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004126 releaseNetworkRequest(operation);
4127 }
4128
4129 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004130 * Informs the system whether it should switch to {@code network} regardless of whether it is
4131 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4132 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4133 * the system default network regardless of any other network that's currently connected. If
4134 * {@code always} is true, then the choice is remembered, so that the next time the user
4135 * connects to this network, the system will switch to it.
4136 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004137 * @param network The network to accept.
4138 * @param accept Whether to accept the network even if unvalidated.
4139 * @param always Whether to remember this choice in the future.
4140 *
4141 * @hide
4142 */
lucasline252a742019-03-12 13:08:03 +08004143 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004144 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4145 try {
4146 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004147 } catch (RemoteException e) {
4148 throw e.rethrowFromSystemServer();
4149 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004150 }
4151
4152 /**
lucasline252a742019-03-12 13:08:03 +08004153 * Informs the system whether it should consider the network as validated even if it only has
4154 * partial connectivity. If {@code accept} is true, then the network will be considered as
4155 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4156 * is remembered, so that the next time the user connects to this network, the system will
4157 * switch to it.
4158 *
4159 * @param network The network to accept.
4160 * @param accept Whether to consider the network as validated even if it has partial
4161 * connectivity.
4162 * @param always Whether to remember this choice in the future.
4163 *
4164 * @hide
4165 */
4166 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4167 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4168 try {
4169 mService.setAcceptPartialConnectivity(network, accept, always);
4170 } catch (RemoteException e) {
4171 throw e.rethrowFromSystemServer();
4172 }
4173 }
4174
4175 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004176 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4177 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4178 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4179 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4180 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004181 * @param network The network to accept.
4182 *
4183 * @hide
4184 */
lucasline252a742019-03-12 13:08:03 +08004185 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004186 public void setAvoidUnvalidated(Network network) {
4187 try {
4188 mService.setAvoidUnvalidated(network);
4189 } catch (RemoteException e) {
4190 throw e.rethrowFromSystemServer();
4191 }
4192 }
4193
4194 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004195 * Requests that the system open the captive portal app on the specified network.
4196 *
4197 * @param network The network to log into.
4198 *
4199 * @hide
4200 */
4201 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
4202 public void startCaptivePortalApp(Network network) {
4203 try {
4204 mService.startCaptivePortalApp(network);
4205 } catch (RemoteException e) {
4206 throw e.rethrowFromSystemServer();
4207 }
4208 }
4209
4210 /**
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004211 * Requests that the system open the captive portal app with the specified extras.
4212 *
4213 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4214 * corresponding permission.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004215 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004216 * @param appExtras Extras to include in the app start intent.
4217 * @hide
4218 */
4219 @SystemApi
4220 @TestApi
4221 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhud9736de2019-03-08 16:35:20 +08004222 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004223 try {
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004224 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004225 } catch (RemoteException e) {
4226 throw e.rethrowFromSystemServer();
4227 }
4228 }
4229
4230 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004231 * Determine whether the device is configured to avoid bad wifi.
4232 * @hide
4233 */
4234 @SystemApi
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004235 @RequiresPermission(anyOf = {
4236 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4237 android.Manifest.permission.NETWORK_STACK})
4238 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004239 try {
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004240 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004241 } catch (RemoteException e) {
4242 throw e.rethrowFromSystemServer();
4243 }
4244 }
4245
4246 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004247 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4248 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09004249 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4250 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004251 *
4252 * An example of such an operation might be a time-sensitive foreground activity, such as a
4253 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4254 */
4255 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4256
4257 /**
4258 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4259 * a backup channel for traffic that is primarily going over another network.
4260 *
4261 * An example might be maintaining backup connections to peers or servers for the purpose of
4262 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4263 * on backup paths should be negligible compared to the traffic on the main path.
4264 */
4265 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4266
4267 /**
4268 * It is acceptable to use metered data to improve network latency and performance.
4269 */
4270 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4271
4272 /**
4273 * Return value to use for unmetered networks. On such networks we currently set all the flags
4274 * to true.
4275 * @hide
4276 */
4277 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4278 MULTIPATH_PREFERENCE_HANDOVER |
4279 MULTIPATH_PREFERENCE_RELIABILITY |
4280 MULTIPATH_PREFERENCE_PERFORMANCE;
4281
4282 /** @hide */
4283 @Retention(RetentionPolicy.SOURCE)
4284 @IntDef(flag = true, value = {
4285 MULTIPATH_PREFERENCE_HANDOVER,
4286 MULTIPATH_PREFERENCE_RELIABILITY,
4287 MULTIPATH_PREFERENCE_PERFORMANCE,
4288 })
4289 public @interface MultipathPreference {
4290 }
4291
4292 /**
4293 * Provides a hint to the calling application on whether it is desirable to use the
4294 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4295 * for multipath data transfer on this network when it is not the system default network.
4296 * Applications desiring to use multipath network protocols should call this method before
4297 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004298 *
4299 * @param network The network on which the application desires to use multipath data.
4300 * If {@code null}, this method will return the a preference that will generally
4301 * apply to metered networks.
4302 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4303 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004304 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004305 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004306 try {
4307 return mService.getMultipathPreference(network);
4308 } catch (RemoteException e) {
4309 throw e.rethrowFromSystemServer();
4310 }
4311 }
4312
4313 /**
Stuart Scott984dc852015-03-30 13:17:11 -07004314 * Resets all connectivity manager settings back to factory defaults.
4315 * @hide
4316 */
4317 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07004318 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07004319 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07004320 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004321 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07004322 }
4323 }
4324
4325 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004326 * Binds the current process to {@code network}. All Sockets created in the future
4327 * (and not explicitly bound via a bound SocketFactory from
4328 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4329 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4330 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4331 * work and all host name resolutions will fail. This is by design so an application doesn't
4332 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4333 * To clear binding pass {@code null} for {@code network}. Using individually bound
4334 * Sockets created by Network.getSocketFactory().createSocket() and
4335 * performing network-specific host name resolutions via
4336 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04004337 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004338 *
4339 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4340 * the current binding.
4341 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4342 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004343 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09004344 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04004345 // instantiated.
4346 return setProcessDefaultNetwork(network);
4347 }
4348
4349 /**
4350 * Binds the current process to {@code network}. All Sockets created in the future
4351 * (and not explicitly bound via a bound SocketFactory from
4352 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4353 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4354 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4355 * work and all host name resolutions will fail. This is by design so an application doesn't
4356 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4357 * To clear binding pass {@code null} for {@code network}. Using individually bound
4358 * Sockets created by Network.getSocketFactory().createSocket() and
4359 * performing network-specific host name resolutions via
4360 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4361 * {@code setProcessDefaultNetwork}.
4362 *
4363 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4364 * the current binding.
4365 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4366 * @deprecated This function can throw {@link IllegalStateException}. Use
4367 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4368 * is a direct replacement.
4369 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004370 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004371 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04004372 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004373 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4374
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09004375 if (netId != NETID_UNSET) {
4376 netId = network.getNetIdForResolv();
Paul Jensenc91b5342014-08-27 12:38:45 -04004377 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004378
4379 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4380 return false;
4381 }
4382
4383 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05004384 // Set HTTP proxy system properties to match network.
4385 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09004386 try {
4387 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4388 } catch (SecurityException e) {
4389 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4390 Log.e(TAG, "Can't set proxy properties", e);
4391 }
Paul Jensenc91b5342014-08-27 12:38:45 -04004392 // Must flush DNS cache as new network may have different DNS resolutions.
4393 InetAddress.clearDnsCache();
4394 // Must flush socket pool as idle sockets will be bound to previous network and may
4395 // cause subsequent fetches to be performed on old network.
4396 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04004397 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004398
4399 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004400 }
4401
4402 /**
4403 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004404 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004405 *
4406 * @return {@code Network} to which this process is bound, or {@code null}.
4407 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004408 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004409 public Network getBoundNetworkForProcess() {
4410 // Forcing callers to call thru non-static function ensures ConnectivityManager
4411 // instantiated.
4412 return getProcessDefaultNetwork();
4413 }
4414
4415 /**
4416 * Returns the {@link Network} currently bound to this process via
4417 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4418 *
4419 * @return {@code Network} to which this process is bound, or {@code null}.
4420 * @deprecated Using this function can lead to other functions throwing
4421 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4422 * {@code getBoundNetworkForProcess} is a direct replacement.
4423 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004424 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004425 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004426 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004427 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004428 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004429 return new Network(netId);
4430 }
4431
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004432 private void unsupportedStartingFrom(int version) {
4433 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004434 // The getApplicationInfo() call we make below is not supported in system context. Let
4435 // the call through here, and rely on the fact that ConnectivityService will refuse to
4436 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004437 return;
4438 }
4439
4440 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4441 throw new UnsupportedOperationException(
4442 "This method is not supported in target SDK version " + version + " and above");
4443 }
4444 }
4445
4446 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4447 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004448 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004449 // remove these exemptions. Note that this check is not secure, and apps can still access these
4450 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4451 // so is unsupported and may break in the future. http://b/22728205
4452 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004453 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004454 }
4455
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004456 /**
4457 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004458 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004459 *
4460 * @param network The {@link Network} to bind host resolutions from the current process to, or
4461 * {@code null} to clear the current binding.
4462 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4463 * @hide
4464 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4465 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004466 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004467 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004468 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004469 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004470 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004471 }
Felipe Leme1b103232016-01-22 09:44:57 -08004472
4473 /**
4474 * Device is not restricting metered network activity while application is running on
4475 * background.
4476 */
4477 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4478
4479 /**
4480 * Device is restricting metered network activity while application is running on background,
4481 * but application is allowed to bypass it.
4482 * <p>
4483 * In this state, application should take action to mitigate metered network access.
4484 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4485 */
4486 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4487
4488 /**
4489 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004490 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004491 * In this state, application should not try to use the network while running on background,
4492 * because it would be denied.
4493 */
4494 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4495
Felipe Leme9778f762016-01-27 14:46:39 -08004496 /**
4497 * A change in the background metered network activity restriction has occurred.
4498 * <p>
4499 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4500 * applies to them.
4501 * <p>
4502 * This is only sent to registered receivers, not manifest receivers.
4503 */
4504 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4505 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4506 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4507
Felipe Lemeecfccea2016-01-25 11:48:04 -08004508 /** @hide */
4509 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004510 @IntDef(flag = false, value = {
4511 RESTRICT_BACKGROUND_STATUS_DISABLED,
4512 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4513 RESTRICT_BACKGROUND_STATUS_ENABLED,
4514 })
Felipe Leme1b103232016-01-22 09:44:57 -08004515 public @interface RestrictBackgroundStatus {
4516 }
4517
4518 private INetworkPolicyManager getNetworkPolicyManager() {
4519 synchronized (this) {
4520 if (mNPManager != null) {
4521 return mNPManager;
4522 }
4523 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4524 .getService(Context.NETWORK_POLICY_SERVICE));
4525 return mNPManager;
4526 }
4527 }
4528
4529 /**
4530 * Determines if the calling application is subject to metered network restrictions while
4531 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004532 *
4533 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4534 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4535 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004536 */
4537 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4538 try {
4539 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4540 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004541 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004542 }
4543 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004544
4545 /**
4546 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004547 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4548 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004549 *
4550 * @return Hash of network watchlist config file. Null if config does not exist.
4551 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004552 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004553 public byte[] getNetworkWatchlistConfigHash() {
4554 try {
4555 return mService.getNetworkWatchlistConfigHash();
4556 } catch (RemoteException e) {
4557 Log.e(TAG, "Unable to get watchlist config hash");
4558 throw e.rethrowFromSystemServer();
4559 }
4560 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004561
4562 /**
4563 * Returns the {@code uid} of the owner of a network connection.
4564 *
4565 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and
4566 * {@code IPPROTO_UDP} currently supported.
4567 * @param local The local {@link InetSocketAddress} of a connection.
4568 * @param remote The remote {@link InetSocketAddress} of a connection.
4569 *
4570 * @return {@code uid} if the connection is found and the app has permission to observe it
4571 * (e.g., if it is associated with the calling VPN app's tunnel) or
4572 * {@link android.os.Process#INVALID_UID} if the connection is not found.
Jeff Vander Stoepb58d3fe2019-02-27 13:31:22 -08004573 * Throws {@link SecurityException} if the caller is not the active VPN for the current user.
4574 * Throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004575 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004576 public int getConnectionOwnerUid(int protocol, @NonNull InetSocketAddress local,
4577 @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004578 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4579 try {
4580 return mService.getConnectionOwnerUid(connectionInfo);
4581 } catch (RemoteException e) {
4582 throw e.rethrowFromSystemServer();
4583 }
4584 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004585
4586 private void printStackTrace() {
4587 if (DEBUG) {
4588 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4589 final StringBuffer sb = new StringBuffer();
4590 for (int i = 3; i < callStack.length; i++) {
4591 final String stackTrace = callStack[i].toString();
4592 if (stackTrace == null || stackTrace.contains("android.os")) {
4593 break;
4594 }
4595 sb.append(" [").append(stackTrace).append("]");
4596 }
4597 Log.d(TAG, "StackLog:" + sb.toString());
4598 }
4599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600}