blob: 3ed51d7f13e45e3b73a7b48f9febf959136b5f30 [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;
markchienae8aa642019-12-16 20:15:20 +080053import android.os.SystemClock;
Jeff Sharkey961e3042011-08-29 16:02:57 -070054import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080055import android.telephony.SubscriptionManager;
Meng Wanga73bed82019-11-18 17:10:00 -080056import android.telephony.TelephonyManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080057import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070058import android.util.Log;
Erik Kline35bf06c2017-01-26 18:08:28 +090059import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
Hugo Benichidafed3d2017-03-06 09:17:06 +090061import com.android.internal.util.Preconditions;
62import com.android.internal.util.Protocol;
Robert Greenwaltafa05c02014-05-21 20:04:36 -070063
Paul Jensenc91b5342014-08-27 12:38:45 -040064import libcore.net.event.NetworkEventDispatcher;
65
junyulai215b8772019-01-15 11:32:44 +080066import java.io.FileDescriptor;
junyulai0c666972019-03-04 22:45:36 +080067import java.io.IOException;
68import java.io.UncheckedIOException;
Felipe Leme1b103232016-01-22 09:44:57 -080069import java.lang.annotation.Retention;
70import java.lang.annotation.RetentionPolicy;
Jeremy Kleind42209d2015-12-28 15:11:58 -080071import java.net.InetAddress;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070072import java.net.InetSocketAddress;
junyulai352dc2f2019-01-08 20:04:33 +080073import java.net.Socket;
Hugo Benichidafed3d2017-03-06 09:17:06 +090074import java.util.ArrayList;
Jeremy Kleind42209d2015-12-28 15:11:58 -080075import java.util.HashMap;
Hugo Benichidafed3d2017-03-06 09:17:06 +090076import java.util.List;
77import java.util.Map;
junyulai48eac1d42018-12-27 17:25:29 +080078import java.util.concurrent.Executor;
junyulai7c469172019-01-16 20:23:34 +080079import java.util.concurrent.ExecutorService;
80import java.util.concurrent.Executors;
81import java.util.concurrent.RejectedExecutionException;
Jeremy Kleind42209d2015-12-28 15:11:58 -080082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083/**
84 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060085 * notifies applications when network connectivity changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 * <p>
87 * The primary responsibilities of this class are to:
88 * <ol>
89 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
90 * <li>Send broadcast intents when network connectivity changes</li>
91 * <li>Attempt to "fail over" to another network when connectivity to a network
92 * is lost</li>
93 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
94 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070095 * <li>Provide an API that allows applications to request and select networks for their data
96 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 * </ol>
98 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060099@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700100public class ConnectivityManager {
101 private static final String TAG = "ConnectivityManager";
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +0900102 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700105 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 * been established or lost. The NetworkInfo for the affected network is
107 * sent as an extra; it should be consulted to see what kind of
108 * connectivity event occurred.
109 * <p/>
Mark Lu33ec1062016-12-05 10:57:55 -0800110 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
111 * broadcast if they declare the broadcast receiver in their manifest. Apps
112 * will still receive broadcasts if they register their
113 * {@link android.content.BroadcastReceiver} with
114 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
115 * and that context is still valid.
116 * <p/>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 * If this is a connection that was the result of failing over from a
118 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
119 * set to true.
120 * <p/>
121 * For a loss of connectivity, if the connectivity manager is attempting
122 * to connect (or has already connected) to another network, the
123 * NetworkInfo for the new network is also passed as an extra. This lets
124 * any receivers of the broadcast know that they should not necessarily
125 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800126 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 * the failover attempt succeeded (and so there is still overall data
128 * connectivity), or that the failover attempt failed, meaning that all
129 * connectivity has been lost.
130 * <p/>
131 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
132 * is set to {@code true} if there are no connected networks at all.
Chalard Jean054cd162018-02-10 05:33:50 +0900133 *
134 * @deprecated apps should use the more versatile {@link #requestNetwork},
135 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
136 * functions instead for faster and more detailed updates about the network
137 * changes they care about.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800139 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean054cd162018-02-10 05:33:50 +0900140 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 /**
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700144 * A temporary hack until SUPL system can get off the legacy APIS.
145 * They do too many network requests and the long list of apps listening
Chalard Jean4d660112018-06-04 16:52:49 +0900146 * and waking due to the CONNECTIVITY_ACTION broadcast makes it expensive.
147 * Use this broadcast intent instead for SUPL requests.
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700148 * @hide
149 */
150 public static final String CONNECTIVITY_ACTION_SUPL =
151 "android.net.conn.CONNECTIVITY_CHANGE_SUPL";
152
153 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500154 * The device has connected to a network that has presented a captive
155 * portal, which is blocking Internet connectivity. The user was presented
156 * with a notification that network sign in is required,
157 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400158 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500159 * facilitate signing in to the network. This action includes a
160 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
161 * the network presenting the captive portal; all communication with the
162 * captive portal must be done using this {@code Network} object.
163 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400164 * This activity includes a {@link CaptivePortal} extra named
165 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
166 * outcomes of the captive portal sign in to the system:
167 * <ul>
168 * <li> When the app handling this action believes the user has signed in to
169 * the network and the captive portal has been dismissed, the app should
170 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
171 * reevaluate the network. If reevaluation finds the network no longer
172 * subject to a captive portal, the network may become the default active
Chalard Jean4d660112018-06-04 16:52:49 +0900173 * data network.</li>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400174 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500175 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400176 * {@link CaptivePortal#ignoreNetwork}. </li>
177 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500178 */
179 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
180 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
181
182 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 * The lookup key for a {@link NetworkInfo} object. Retrieve with
184 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700185 *
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900186 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
187 * can't accurately represent modern network characteristics.
188 * Please obtain information about networks from the {@link NetworkCapabilities}
189 * or {@link LinkProperties} objects instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700191 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700195 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700196 *
197 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900198 * @deprecated The network type is not rich enough to represent the characteristics
199 * of modern networks. Please use {@link NetworkCapabilities} instead,
200 * in particular the transports.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700201 */
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900202 @Deprecated
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700203 public static final String EXTRA_NETWORK_TYPE = "networkType";
204
205 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 * The lookup key for a boolean that indicates whether a connect event
207 * is for a network to which the connectivity manager was failing over
208 * following a disconnect on another network.
209 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai3822c8a2018-12-13 12:47:51 +0800210 *
211 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 */
junyulai3822c8a2018-12-13 12:47:51 +0800213 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 public static final String EXTRA_IS_FAILOVER = "isFailover";
215 /**
216 * The lookup key for a {@link NetworkInfo} object. This is supplied when
217 * there is another network that it may be possible to connect to. Retrieve with
218 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800219 *
220 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 */
junyulai3822c8a2018-12-13 12:47:51 +0800222 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
224 /**
225 * The lookup key for a boolean that indicates whether there is a
226 * complete lack of connectivity, i.e., no network is available.
227 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
228 */
229 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
230 /**
231 * The lookup key for a string that indicates why an attempt to connect
232 * to a network failed. The string has no particular structure. It is
233 * intended to be used in notifications presented to users. Retrieve
234 * it with {@link android.content.Intent#getStringExtra(String)}.
235 */
236 public static final String EXTRA_REASON = "reason";
237 /**
238 * The lookup key for a string that provides optionally supplied
239 * extra information about the network state. The information
240 * may be passed up from the lower networking layers, and its
241 * meaning may be specific to a particular network type. Retrieve
242 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800243 *
244 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 */
junyulai3822c8a2018-12-13 12:47:51 +0800246 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700248 /**
249 * The lookup key for an int that provides information about
250 * our connection to the internet at large. 0 indicates no connection,
251 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700252 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700253 * {@hide}
254 */
255 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400257 * The lookup key for a {@link CaptivePortal} object included with the
258 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
259 * object can be used to either indicate to the system that the captive
260 * portal has been dismissed or that the user does not want to pursue
261 * signing in to captive portal. Retrieve it with
262 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500263 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400264 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700265
266 /**
267 * Key for passing a URL to the captive portal login activity.
268 */
269 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
270
Paul Jensen25a217c2015-02-27 22:55:47 -0500271 /**
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900272 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
273 * portal login activity.
274 * {@hide}
275 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900276 @SystemApi
277 @TestApi
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900278 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
279 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
280
281 /**
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900282 * Key for passing a user agent string to the captive portal login activity.
283 * {@hide}
284 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900285 @SystemApi
286 @TestApi
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900287 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
288 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
289
290 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700291 * Broadcast action to indicate the change of data activity status
292 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800293 * The network becomes active when data transmission is started, or
294 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700295 * {@hide}
296 */
297 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean4d660112018-06-04 16:52:49 +0900298 public static final String ACTION_DATA_ACTIVITY_CHANGE =
299 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700300 /**
301 * The lookup key for an enum that indicates the network device type on which this data activity
302 * change happens.
303 * {@hide}
304 */
305 public static final String EXTRA_DEVICE_TYPE = "deviceType";
306 /**
307 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
308 * it is actively sending or receiving data and {@code false} means it is idle.
309 * {@hide}
310 */
311 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700312 /**
313 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
314 * {@hide}
315 */
316 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700317
318 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 * Broadcast Action: The setting for background data usage has changed
320 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
321 * <p>
322 * If an application uses the network in the background, it should listen
323 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700324 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800325 * <p>
326 *
327 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
328 * of background data depends on several combined factors, and
329 * this broadcast is no longer sent. Instead, when background
330 * data is unavailable, {@link #getActiveNetworkInfo()} will now
331 * appear disconnected. During first boot after a platform
332 * upgrade, this broadcast will be sent once if
333 * {@link #getBackgroundDataSetting()} was {@code false} before
334 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 */
336 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800337 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
339 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
340
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700341 /**
342 * Broadcast Action: The network connection may not be good
343 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
344 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
345 * the network and it's condition.
346 * @hide
347 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800348 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100349 @UnsupportedAppUsage
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700350 public static final String INET_CONDITION_ACTION =
351 "android.net.conn.INET_CONDITION_ACTION";
352
Robert Greenwalt42acef32009-08-12 16:08:25 -0700353 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800354 * Broadcast Action: A tetherable connection has come or gone.
355 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline8351faa2017-04-17 16:47:23 +0900356 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
357 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800358 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
359 * the current state of tethering. Each include a list of
360 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800361 * @hide
362 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800363 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100364 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800365 public static final String ACTION_TETHER_STATE_CHANGED =
366 "android.net.conn.TETHER_STATE_CHANGED";
367
368 /**
369 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800370 * gives a String[] listing all the interfaces configured for
371 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800372 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100373 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800374 public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800375
376 /**
377 * @hide
Erik Kline8351faa2017-04-17 16:47:23 +0900378 * gives a String[] listing all the interfaces currently in local-only
379 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800380 */
Erik Kline8351faa2017-04-17 16:47:23 +0900381 public static final String EXTRA_ACTIVE_LOCAL_ONLY = "localOnlyArray";
382
383 /**
384 * @hide
385 * gives a String[] listing all the interfaces currently tethered
386 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
387 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100388 @UnsupportedAppUsage
Erik Kline8351faa2017-04-17 16:47:23 +0900389 public static final String EXTRA_ACTIVE_TETHER = "tetherArray";
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800390
391 /**
392 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800393 * gives a String[] listing all the interfaces we tried to tether and
394 * failed. Use {@link #getLastTetherError} to find the error code
395 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800396 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100397 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800398 public static final String EXTRA_ERRORED_TETHER = "erroredArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800399
400 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800401 * Broadcast Action: The captive portal tracker has finished its test.
402 * Sent only while running Setup Wizard, in lieu of showing a user
403 * notification.
404 * @hide
405 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800406 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800407 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
408 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
409 /**
410 * The lookup key for a boolean that indicates whether a captive portal was detected.
411 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
412 * @hide
413 */
414 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
415
416 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900417 * Action used to display a dialog that asks the user whether to connect to a network that is
418 * not validated. This intent is used to start the dialog in settings via startActivity.
419 *
420 * @hide
421 */
422 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
423
424 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900425 * Action used to display a dialog that asks the user whether to avoid a network that is no
426 * longer validated. This intent is used to start the dialog in settings via startActivity.
427 *
428 * @hide
429 */
430 public static final String ACTION_PROMPT_LOST_VALIDATION =
431 "android.net.conn.PROMPT_LOST_VALIDATION";
432
433 /**
lucasline252a742019-03-12 13:08:03 +0800434 * Action used to display a dialog that asks the user whether to stay connected to a network
435 * that has not validated. This intent is used to start the dialog in settings via
436 * startActivity.
437 *
438 * @hide
439 */
440 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
441 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
442
443 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800444 * Invalid tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900445 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800446 * @hide
447 */
448 public static final int TETHERING_INVALID = -1;
449
450 /**
451 * Wifi tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900452 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800453 * @hide
454 */
455 @SystemApi
456 public static final int TETHERING_WIFI = 0;
457
458 /**
459 * USB tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900460 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800461 * @hide
462 */
463 @SystemApi
464 public static final int TETHERING_USB = 1;
465
466 /**
467 * Bluetooth tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900468 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800469 * @hide
470 */
471 @SystemApi
472 public static final int TETHERING_BLUETOOTH = 2;
473
474 /**
Jimmy Chenbcd86d02019-07-15 18:03:23 +0800475 * Wifi P2p tethering type.
476 * Wifi P2p tethering is set through events automatically, and don't
477 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
478 * @hide
479 */
480 public static final int TETHERING_WIFI_P2P = 3;
481
482 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800483 * Extra used for communicating with the TetherService. Includes the type of tethering to
484 * enable if any.
485 * @hide
486 */
487 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
488
489 /**
490 * Extra used for communicating with the TetherService. Includes the type of tethering for
491 * which to cancel provisioning.
492 * @hide
493 */
494 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
495
496 /**
497 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
498 * provisioning.
499 * @hide
500 */
501 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
502
503 /**
504 * Tells the TetherService to run a provision check now.
505 * @hide
506 */
507 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
508
509 /**
510 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
511 * which will receive provisioning results. Can be left empty.
512 * @hide
513 */
514 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
515
516 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800517 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700518 * @hide
519 */
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900520 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700521 public static final int TYPE_NONE = -1;
522
523 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900524 * A Mobile data connection. Devices may support more than one.
525 *
526 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
527 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
528 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700529 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900530 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700531 public static final int TYPE_MOBILE = 0;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900532
Robert Greenwalt42acef32009-08-12 16:08:25 -0700533 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900534 * A WIFI data connection. Devices may support more than one.
535 *
536 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
537 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
538 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700539 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900540 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700541 public static final int TYPE_WIFI = 1;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900542
Robert Greenwalt42acef32009-08-12 16:08:25 -0700543 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800544 * An MMS-specific Mobile data connection. This network type may use the
545 * same network interface as {@link #TYPE_MOBILE} or it may use a different
546 * one. This is used by applications needing to talk to the carrier's
547 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900548 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900549 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900550 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900551 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700552 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700553 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700554 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900555
Robert Greenwalt42acef32009-08-12 16:08:25 -0700556 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800557 * A SUPL-specific Mobile data connection. This network type may use the
558 * same network interface as {@link #TYPE_MOBILE} or it may use a different
559 * one. This is used by applications needing to talk to the carrier's
560 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900561 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900562 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900563 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900564 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700565 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700566 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700567 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900568
Robert Greenwalt42acef32009-08-12 16:08:25 -0700569 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800570 * A DUN-specific Mobile data connection. This network type may use the
571 * same network interface as {@link #TYPE_MOBILE} or it may use a different
572 * one. This is sometimes by the system when setting up an upstream connection
573 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900574 *
575 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
576 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
577 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700578 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900579 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700580 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900581
Robert Greenwalt42acef32009-08-12 16:08:25 -0700582 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800583 * A High Priority Mobile data connection. This network type uses the
584 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900585 * is different.
586 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900587 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
588 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
589 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700590 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700591 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700592 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900593
jsh8214deb2010-03-11 15:04:43 -0800594 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900595 * A WiMAX data connection.
596 *
597 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
598 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
599 * appropriate network. {@see NetworkCapabilities} for supported transports.
jsh8214deb2010-03-11 15:04:43 -0800600 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900601 @Deprecated
jsh8214deb2010-03-11 15:04:43 -0800602 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800603
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800604 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900605 * A Bluetooth data connection.
606 *
607 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
608 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
609 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800610 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900611 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800612 public static final int TYPE_BLUETOOTH = 7;
613
Robert Greenwalt60810842011-04-22 15:28:18 -0700614 /**
615 * Dummy data connection. This should not be used on shipping devices.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900616 * @deprecated This is not used any more.
Robert Greenwalt60810842011-04-22 15:28:18 -0700617 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900618 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800619 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800620
Robert Greenwalt60810842011-04-22 15:28:18 -0700621 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900622 * An Ethernet data connection.
623 *
624 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
625 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
626 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt60810842011-04-22 15:28:18 -0700627 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900628 @Deprecated
Robert Greenwalte12aec92011-01-28 14:48:37 -0800629 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700630
Wink Saville9d7d6282011-03-12 14:52:01 -0800631 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800632 * Over the air Administration.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900633 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800634 * {@hide}
635 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900636 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900637 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Saville9d7d6282011-03-12 14:52:01 -0800638 public static final int TYPE_MOBILE_FOTA = 10;
639
640 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800641 * IP Multimedia Subsystem.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900642 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800643 * {@hide}
644 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900645 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100646 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800647 public static final int TYPE_MOBILE_IMS = 11;
648
649 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800650 * Carrier Branded Services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900651 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800652 * {@hide}
653 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900654 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900655 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Saville9d7d6282011-03-12 14:52:01 -0800656 public static final int TYPE_MOBILE_CBS = 12;
657
repo syncaea743a2011-07-29 23:55:49 -0700658 /**
659 * A Wi-Fi p2p connection. Only requesting processes will have access to
660 * the peers connected.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900661 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncaea743a2011-07-29 23:55:49 -0700662 * {@hide}
663 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900664 @Deprecated
Chalard Jean2253ff92019-06-17 19:46:34 +0900665 @UnsupportedAppUsage
repo syncaea743a2011-07-29 23:55:49 -0700666 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800667
Wink Saville5e56bc52013-07-29 15:00:57 -0700668 /**
669 * The network to use for initially attaching to the network
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900670 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville5e56bc52013-07-29 15:00:57 -0700671 * {@hide}
672 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900673 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100674 @UnsupportedAppUsage
Wink Saville5e56bc52013-07-29 15:00:57 -0700675 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700676
Lorenzo Colittie285b432015-04-23 15:32:42 +0900677 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700678 * Emergency PDN connection for emergency services. This
679 * may include IMS and MMS in emergency situations.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900680 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram3e0e3bc2014-06-26 11:03:44 -0700681 * {@hide}
682 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900683 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900684 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram3e0e3bc2014-06-26 11:03:44 -0700685 public static final int TYPE_MOBILE_EMERGENCY = 15;
686
Hui Lu1c5624a2014-01-15 11:05:36 -0500687 /**
688 * The network that uses proxy to achieve connectivity.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900689 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu1c5624a2014-01-15 11:05:36 -0500690 * {@hide}
691 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900692 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100693 @UnsupportedAppUsage
Hui Lu1c5624a2014-01-15 11:05:36 -0500694 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700695
Robert Greenwalt8283f882014-07-07 17:09:01 -0700696 /**
697 * A virtual network using one or more native bearers.
698 * It may or may not be providing security services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900699 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700700 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900701 @Deprecated
Robert Greenwalt8283f882014-07-07 17:09:01 -0700702 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500703
Benedict Wong89ce5e32018-11-14 17:40:55 -0800704 /**
705 * A network that is exclusively meant to be used for testing
706 *
707 * @deprecated Use {@link NetworkCapabilities} instead.
708 * @hide
709 */
710 @Deprecated
711 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700712
Chalard Jeanc06d7882019-11-21 14:48:00 +0900713 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
714 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
715 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
716 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
717 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
718
Robert Greenwalt8283f882014-07-07 17:09:01 -0700719 /** {@hide} */
Benedict Wong89ce5e32018-11-14 17:40:55 -0800720 public static final int MAX_RADIO_TYPE = TYPE_TEST;
721
722 /** {@hide} */
723 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724
Hugo Benichi16f0a942017-06-20 14:07:59 +0900725 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
726
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800727 /**
728 * If you want to set the default network preference,you can directly
729 * change the networkAttributes array in framework's config.xml.
730 *
731 * @deprecated Since we support so many more networks now, the single
732 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800733 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800734 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800735 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800736 * from an App.
737 */
738 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
740
Jeff Sharkey625239a2012-09-26 22:03:49 -0700741 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700742 * @hide
743 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900744 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700745
Paul Jensen5d59e782014-07-11 12:28:19 -0400746 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900747 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
748 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean4d660112018-06-04 16:52:49 +0900749 * registered from those that were already unregistered.
Hugo Benichi31c176d2017-06-17 13:14:12 +0900750 * @hide
751 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900752 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900753 new NetworkRequest.Builder().clearCapabilities().build();
754
755 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400756 * A NetID indicating no Network is selected.
757 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
758 * @hide
759 */
760 public static final int NETID_UNSET = 0;
761
Erik Kline4d092232017-10-30 15:29:44 +0900762 /**
763 * Private DNS Mode values.
764 *
765 * The "private_dns_mode" global setting stores a String value which is
766 * expected to be one of the following.
767 */
768
769 /**
770 * @hide
771 */
772 public static final String PRIVATE_DNS_MODE_OFF = "off";
773 /**
774 * @hide
775 */
776 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
777 /**
778 * @hide
779 */
780 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
781 /**
782 * The default Private DNS mode.
783 *
784 * This may change from release to release or may become dependent upon
785 * the capabilities of the underlying platform.
786 *
787 * @hide
788 */
Erik Kline19841792018-05-16 16:41:57 +0900789 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline4d092232017-10-30 15:29:44 +0900790
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900791 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700792 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500793 /**
794 * A kludge to facilitate static access where a Context pointer isn't available, like in the
795 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
796 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
797 * methods that take a Context argument.
798 */
799 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900801 private final Context mContext;
802
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800803 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800804 private INetworkPolicyManager mNPManager;
markchienae8aa642019-12-16 20:15:20 +0800805 private TetheringManager mTetheringManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800806
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800807 /**
808 * Tests if a given integer represents a valid network type.
809 * @param networkType the type to be tested
810 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400811 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
812 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800813 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700814 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700815 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900816 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 }
818
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800819 /**
820 * Returns a non-localized string representing a given network type.
821 * ONLY used for debugging output.
822 * @param type the type needing naming
823 * @return a String for the given type, or a string version of the type ("87")
824 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900825 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800826 * {@hide}
827 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900828 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100829 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700830 public static String getNetworkTypeName(int type) {
831 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900832 case TYPE_NONE:
833 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700834 case TYPE_MOBILE:
835 return "MOBILE";
836 case TYPE_WIFI:
837 return "WIFI";
838 case TYPE_MOBILE_MMS:
839 return "MOBILE_MMS";
840 case TYPE_MOBILE_SUPL:
841 return "MOBILE_SUPL";
842 case TYPE_MOBILE_DUN:
843 return "MOBILE_DUN";
844 case TYPE_MOBILE_HIPRI:
845 return "MOBILE_HIPRI";
846 case TYPE_WIMAX:
847 return "WIMAX";
848 case TYPE_BLUETOOTH:
849 return "BLUETOOTH";
850 case TYPE_DUMMY:
851 return "DUMMY";
852 case TYPE_ETHERNET:
853 return "ETHERNET";
854 case TYPE_MOBILE_FOTA:
855 return "MOBILE_FOTA";
856 case TYPE_MOBILE_IMS:
857 return "MOBILE_IMS";
858 case TYPE_MOBILE_CBS:
859 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700860 case TYPE_WIFI_P2P:
861 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700862 case TYPE_MOBILE_IA:
863 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700864 case TYPE_MOBILE_EMERGENCY:
865 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500866 case TYPE_PROXY:
867 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900868 case TYPE_VPN:
869 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700870 default:
871 return Integer.toString(type);
872 }
873 }
874
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800875 /**
876 * Checks if a given type uses the cellular data connection.
877 * This should be replaced in the future by a network property.
878 * @param networkType the type to check
879 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900880 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800881 * {@hide}
882 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900883 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900884 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700885 public static boolean isNetworkTypeMobile(int networkType) {
886 switch (networkType) {
887 case TYPE_MOBILE:
888 case TYPE_MOBILE_MMS:
889 case TYPE_MOBILE_SUPL:
890 case TYPE_MOBILE_DUN:
891 case TYPE_MOBILE_HIPRI:
892 case TYPE_MOBILE_FOTA:
893 case TYPE_MOBILE_IMS:
894 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700895 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700896 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700897 return true;
898 default:
899 return false;
900 }
901 }
902
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800903 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700904 * Checks if the given network type is backed by a Wi-Fi radio.
905 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900906 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700907 * @hide
908 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900909 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700910 public static boolean isNetworkTypeWifi(int networkType) {
911 switch (networkType) {
912 case TYPE_WIFI:
913 case TYPE_WIFI_P2P:
914 return true;
915 default:
916 return false;
917 }
918 }
919
920 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800921 * Specifies the preferred network type. When the device has more
922 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800923 *
924 * @param preference the network type to prefer over all others. It is
925 * unspecified what happens to the old preferred network in the
926 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700927 * @deprecated Functionality has been removed as it no longer makes sense,
928 * with many more than two networks - we'd need an array to express
929 * preference. Instead we use dynamic network properties of
930 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800931 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700932 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 }
935
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800936 /**
937 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800938 *
939 * @return an integer representing the preferred network type
940 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700941 * @deprecated Functionality has been removed as it no longer makes sense,
942 * with many more than two networks - we'd need an array to express
943 * preference. Instead we use dynamic network properties of
944 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800945 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700946 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600947 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700949 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 }
951
Scott Main671644c2011-10-06 19:02:28 -0700952 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800953 * Returns details about the currently active default data network. When
954 * connected, this network is the default route for outgoing connections.
955 * You should always check {@link NetworkInfo#isConnected()} before initiating
956 * network traffic. This may return {@code null} when there is no default
957 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900958 * Note that if the default network is a VPN, this method will return the
959 * NetworkInfo for one of its underlying networks instead, or null if the
960 * VPN agent did not specify any. Apps interested in learning about VPNs
961 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800962 *
963 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500964 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800965 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700966 */
junyulai3822c8a2018-12-13 12:47:51 +0800967 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600968 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900969 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 public NetworkInfo getActiveNetworkInfo() {
971 try {
972 return mService.getActiveNetworkInfo();
973 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700974 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976 }
977
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800978 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500979 * Returns a {@link Network} object corresponding to the currently active
980 * default data network. In the event that the current active default data
981 * network disconnects, the returned {@code Network} object will no longer
982 * be usable. This will return {@code null} when there is no default
983 * network.
984 *
985 * @return a {@link Network} object for the current default network or
986 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500987 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600988 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900989 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -0500990 public Network getActiveNetwork() {
991 try {
992 return mService.getActiveNetwork();
993 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700994 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500995 }
996 }
997
998 /**
Robin Leed2baf792016-03-24 12:07:00 +0000999 * Returns a {@link Network} object corresponding to the currently active
1000 * default data network for a specific UID. In the event that the default data
1001 * network disconnects, the returned {@code Network} object will no longer
1002 * be usable. This will return {@code null} when there is no default
1003 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +00001004 *
1005 * @return a {@link Network} object for the current default network for the
1006 * given UID or {@code null} if no default network is currently active
1007 *
1008 * @hide
1009 */
paulhua6af6b62019-08-12 16:25:11 +08001010 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001011 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +00001012 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001013 return getActiveNetworkForUid(uid, false);
1014 }
1015
1016 /** {@hide} */
1017 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001018 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001019 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001020 } catch (RemoteException e) {
1021 throw e.rethrowFromSystemServer();
1022 }
1023 }
1024
1025 /**
Charles He36738632017-05-15 17:07:18 +01001026 * Checks if a VPN app supports always-on mode.
1027 *
1028 * In order to support the always-on feature, an app has to
1029 * <ul>
1030 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +01001031 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
1032 * meta-data field.
Charles He36738632017-05-15 17:07:18 +01001033 * </ul>
1034 *
1035 * @param userId The identifier of the user for whom the VPN app is installed.
1036 * @param vpnPackage The canonical package name of the VPN app.
1037 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
1038 * @hide
1039 */
1040 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1041 try {
1042 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1043 } catch (RemoteException e) {
1044 throw e.rethrowFromSystemServer();
1045 }
1046 }
1047
1048 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001049 * Configures an always-on VPN connection through a specific application.
1050 * This connection is automatically granted and persisted after a reboot.
1051 *
1052 * <p>The designated package should declare a {@link VpnService} in its
1053 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1054 * otherwise the call will fail.
1055 *
1056 * @param userId The identifier of the user to set an always-on VPN for.
1057 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1058 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001059 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1060 * {@code false} otherwise.
Pavel Grafova462bcb2019-01-25 08:50:06 +00001061 * @param lockdownWhitelist The list of packages that are allowed to access network directly
1062 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
1063 * this method must be called when a package that should be whitelisted is installed or
1064 * uninstalled.
Robin Lee244ce8e2016-01-05 18:03:46 +00001065 * @return {@code true} if the package is set as always-on VPN controller;
1066 * {@code false} otherwise.
1067 * @hide
1068 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001069 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leedc679712016-05-03 13:23:03 +01001070 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001071 boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001072 try {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001073 return mService.setAlwaysOnVpnPackage(
1074 userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
Robin Lee244ce8e2016-01-05 18:03:46 +00001075 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001076 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001077 }
1078 }
1079
Pavel Grafova462bcb2019-01-25 08:50:06 +00001080 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001081 * Returns the package name of the currently set always-on VPN application.
1082 * If there is no always-on VPN set, or the VPN is provided by the system instead
1083 * of by an app, {@code null} will be returned.
1084 *
1085 * @return Package name of VPN controller responsible for always-on VPN,
1086 * or {@code null} if none is set.
1087 * @hide
1088 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001089 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee244ce8e2016-01-05 18:03:46 +00001090 public String getAlwaysOnVpnPackageForUser(int userId) {
1091 try {
1092 return mService.getAlwaysOnVpnPackage(userId);
1093 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001094 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001095 }
1096 }
1097
1098 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001099 * @return whether always-on VPN is in lockdown mode.
1100 *
1101 * @hide
1102 **/
1103 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1104 public boolean isVpnLockdownEnabled(int userId) {
1105 try {
1106 return mService.isVpnLockdownEnabled(userId);
1107 } catch (RemoteException e) {
1108 throw e.rethrowFromSystemServer();
1109 }
1110
1111 }
1112
1113 /**
1114 * @return the list of packages that are allowed to access network when always-on VPN is in
1115 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1116 *
1117 * @hide
1118 **/
1119 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1120 public List<String> getVpnLockdownWhitelist(int userId) {
1121 try {
1122 return mService.getVpnLockdownWhitelist(userId);
1123 } catch (RemoteException e) {
1124 throw e.rethrowFromSystemServer();
1125 }
1126 }
1127
1128 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001129 * Returns details about the currently active default data network
1130 * for a given uid. This is for internal use only to avoid spying
1131 * other apps.
1132 *
1133 * @return a {@link NetworkInfo} object for the current default network
1134 * for the given uid or {@code null} if no default network is
1135 * available for the specified uid.
1136 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001137 * {@hide}
1138 */
paulhua6af6b62019-08-12 16:25:11 +08001139 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001140 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001141 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001142 return getActiveNetworkInfoForUid(uid, false);
1143 }
1144
1145 /** {@hide} */
1146 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001147 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001148 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001149 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001150 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001151 }
1152 }
1153
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001154 /**
1155 * Returns connection status information about a particular
1156 * network type.
1157 *
1158 * @param networkType integer specifying which networkType in
1159 * which you're interested.
1160 * @return a {@link NetworkInfo} object for the requested
1161 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001162 * supported by the device. If {@code networkType} is
1163 * TYPE_VPN and a VPN is active for the calling app,
1164 * then this method will try to return one of the
1165 * underlying networks for the VPN or null if the
1166 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001167 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001168 * @deprecated This method does not support multiple connected networks
1169 * of the same type. Use {@link #getAllNetworks} and
1170 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001171 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001172 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001173 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001174 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 public NetworkInfo getNetworkInfo(int networkType) {
1176 try {
1177 return mService.getNetworkInfo(networkType);
1178 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001179 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 }
1181 }
1182
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001183 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001184 * Returns connection status information about a particular
1185 * Network.
1186 *
1187 * @param network {@link Network} specifying which network
1188 * in which you're interested.
1189 * @return a {@link NetworkInfo} object for the requested
1190 * network or {@code null} if the {@code Network}
1191 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001192 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001193 */
junyulai3822c8a2018-12-13 12:47:51 +08001194 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001195 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001196 @Nullable
1197 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001198 return getNetworkInfoForUid(network, Process.myUid(), false);
1199 }
1200
1201 /** {@hide} */
1202 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001203 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001204 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001205 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001206 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001207 }
1208 }
1209
1210 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001211 * Returns connection status information about all network
1212 * types supported by the device.
1213 *
1214 * @return an array of {@link NetworkInfo} objects. Check each
1215 * {@link NetworkInfo#getType} for which type each applies.
1216 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001217 * @deprecated This method does not support multiple connected networks
1218 * of the same type. Use {@link #getAllNetworks} and
1219 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001220 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001221 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001222 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001223 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 public NetworkInfo[] getAllNetworkInfo() {
1225 try {
1226 return mService.getAllNetworkInfo();
1227 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001228 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 }
1230 }
1231
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001232 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001233 * Returns the {@link Network} object currently serving a given type, or
1234 * null if the given type is not connected.
1235 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001236 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001237 * @deprecated This method does not support multiple connected networks
1238 * of the same type. Use {@link #getAllNetworks} and
1239 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001240 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001241 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001242 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001243 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001244 public Network getNetworkForType(int networkType) {
1245 try {
1246 return mService.getNetworkForType(networkType);
1247 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001248 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001249 }
1250 }
1251
1252 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001253 * Returns an array of all {@link Network} currently tracked by the
1254 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001255 *
1256 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001257 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001258 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001259 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001260 public Network[] getAllNetworks() {
1261 try {
1262 return mService.getAllNetworks();
1263 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001264 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001265 }
1266 }
1267
1268 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001269 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001270 * the Networks that applications run by the given user will use by default.
1271 * @hide
1272 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001273 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001274 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1275 try {
1276 return mService.getDefaultNetworkCapabilitiesForUser(userId);
1277 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001278 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001279 }
1280 }
1281
1282 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001283 * Returns the IP information for the current default network.
1284 *
1285 * @return a {@link LinkProperties} object describing the IP info
1286 * for the current default network, or {@code null} if there
1287 * is no current default network.
1288 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001289 * {@hide}
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001290 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1291 * value of {@link #getActiveNetwork()} instead. In particular,
1292 * this method will return non-null LinkProperties even if the
1293 * app is blocked by policy from using this network.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001294 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001295 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001296 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001297 public LinkProperties getActiveLinkProperties() {
1298 try {
1299 return mService.getActiveLinkProperties();
1300 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001301 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001302 }
1303 }
1304
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001305 /**
1306 * Returns the IP information for a given network type.
1307 *
1308 * @param networkType the network type of interest.
1309 * @return a {@link LinkProperties} object describing the IP info
1310 * for the given networkType, or {@code null} if there is
1311 * no current default network.
1312 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001313 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001314 * @deprecated This method does not support multiple connected networks
1315 * of the same type. Use {@link #getAllNetworks},
1316 * {@link #getNetworkInfo(android.net.Network)}, and
1317 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001318 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001319 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001320 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09001321 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001322 public LinkProperties getLinkProperties(int networkType) {
1323 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001324 return mService.getLinkPropertiesForType(networkType);
1325 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001326 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001327 }
1328 }
1329
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001330 /**
1331 * Get the {@link LinkProperties} for the given {@link Network}. This
1332 * will return {@code null} if the network is unknown.
1333 *
1334 * @param network The {@link Network} object identifying the network in question.
1335 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001336 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001337 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001338 @Nullable
1339 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001340 try {
1341 return mService.getLinkProperties(network);
1342 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001343 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001344 }
1345 }
1346
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001347 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001348 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001349 * will return {@code null} if the network is unknown.
1350 *
1351 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001352 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001353 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001354 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001355 @Nullable
1356 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001357 try {
1358 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001359 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001360 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001361 }
1362 }
1363
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001364 /**
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001365 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainib7c24872016-01-04 12:16:14 -08001366 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1367 * portal is present.
1368 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1369 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1370 *
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001371 * The system network validation may be using different strategies to detect captive portals,
1372 * so this method does not necessarily return a URL used by the system. It only returns a URL
1373 * that may be relevant for other components trying to detect captive portals.
paulhua6af6b62019-08-12 16:25:11 +08001374 *
Udam Sainib7c24872016-01-04 12:16:14 -08001375 * @hide
paulhua6af6b62019-08-12 16:25:11 +08001376 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1377 * system.
Udam Sainib7c24872016-01-04 12:16:14 -08001378 */
paulhua6af6b62019-08-12 16:25:11 +08001379 @Deprecated
Udam Sainib7c24872016-01-04 12:16:14 -08001380 @SystemApi
paulhua6af6b62019-08-12 16:25:11 +08001381 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainib7c24872016-01-04 12:16:14 -08001382 public String getCaptivePortalServerUrl() {
1383 try {
1384 return mService.getCaptivePortalServerUrl();
1385 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001386 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001387 }
1388 }
1389
1390 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 * Tells the underlying networking system that the caller wants to
1392 * begin using the named feature. The interpretation of {@code feature}
1393 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001394 *
1395 * <p>This method requires the caller to hold either the
1396 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1397 * or the ability to modify system settings as determined by
1398 * {@link android.provider.Settings.System#canWrite}.</p>
1399 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 * @param networkType specifies which network the request pertains to
1401 * @param feature the name of the feature to be used
1402 * @return an integer value representing the outcome of the request.
1403 * The interpretation of this value is specific to each networking
1404 * implementation+feature combination, except that the value {@code -1}
1405 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001406 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001407 * @deprecated Deprecated in favor of the cleaner
1408 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001409 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001410 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001411 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001413 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001415 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001416 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1417 if (netCap == null) {
1418 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1419 feature);
Chalard Jeanc06d7882019-11-21 14:48:00 +09001420 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001421 }
1422
1423 NetworkRequest request = null;
1424 synchronized (sLegacyRequests) {
1425 LegacyRequest l = sLegacyRequests.get(netCap);
1426 if (l != null) {
1427 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1428 renewRequestLocked(l);
1429 if (l.currentNetwork != null) {
Chalard Jeanc06d7882019-11-21 14:48:00 +09001430 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001431 } else {
Chalard Jeanc06d7882019-11-21 14:48:00 +09001432 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001433 }
1434 }
1435
1436 request = requestNetworkForFeatureLocked(netCap);
1437 }
1438 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001439 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanc06d7882019-11-21 14:48:00 +09001440 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001441 } else {
1442 Log.d(TAG, " request Failed");
Chalard Jeanc06d7882019-11-21 14:48:00 +09001443 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 }
1445 }
1446
1447 /**
1448 * Tells the underlying networking system that the caller is finished
1449 * using the named feature. The interpretation of {@code feature}
1450 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001451 *
1452 * <p>This method requires the caller to hold either the
1453 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1454 * or the ability to modify system settings as determined by
1455 * {@link android.provider.Settings.System#canWrite}.</p>
1456 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 * @param networkType specifies which network the request pertains to
1458 * @param feature the name of the feature that is no longer needed
1459 * @return an integer value representing the outcome of the request.
1460 * The interpretation of this value is specific to each networking
1461 * implementation+feature combination, except that the value {@code -1}
1462 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001463 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001464 * @deprecated Deprecated in favor of the cleaner
1465 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001466 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001467 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001468 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001470 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001472 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001473 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1474 if (netCap == null) {
1475 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1476 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 return -1;
1478 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001479
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001480 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001481 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001482 }
1483 return 1;
1484 }
1485
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001486 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001487 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1488 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001489 switch (feature) {
1490 case "enableCBS":
1491 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1492 case "enableDUN":
1493 case "enableDUNAlways":
1494 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1495 case "enableFOTA":
1496 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1497 case "enableHIPRI":
1498 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1499 case "enableIMS":
1500 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1501 case "enableMMS":
1502 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1503 case "enableSUPL":
1504 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1505 default:
1506 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001507 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001508 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1509 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001510 }
1511 return null;
1512 }
1513
Robert Greenwalt06314e42014-10-29 14:04:06 -07001514 /**
1515 * Guess what the network request was trying to say so that the resulting
1516 * network is accessible via the legacy (deprecated) API such as
1517 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001518 *
1519 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001520 * capability but ignore things such as networkSpecifier.
1521 * If the request has more than one transport or capability it doesn't
1522 * match the old legacy requests (they selected only single transport/capability)
1523 * so this function cannot map the request to a single legacy type and
1524 * the resulting network will not be available to the legacy APIs.
1525 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001526 * This code is only called from the requestNetwork API (L and above).
1527 *
1528 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1529 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1530 * do this for SUPL requests, which are the only ones that we know need it. If
1531 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1532 * compatibility we can send them:
1533 *
1534 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1535 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1536 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001537 * TODO - This should be removed when the legacy APIs are removed.
1538 */
Ye Wenb87875e2014-07-21 14:19:01 -07001539 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1540 if (netCap == null) {
1541 return TYPE_NONE;
1542 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001543
Ye Wenb87875e2014-07-21 14:19:01 -07001544 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1545 return TYPE_NONE;
1546 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001547
Lifu Tang30f95a72016-01-07 23:20:38 -08001548 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001549 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1550 // NOTE: if this causes app breakage, we should not just comment out this early return;
1551 // instead, we should make this early return conditional on the requesting app's target
1552 // SDK version, as described in the comment above.
1553 return TYPE_NONE;
1554 }
1555
Robert Greenwalt06314e42014-10-29 14:04:06 -07001556 String type = null;
1557 int result = TYPE_NONE;
1558
Ye Wenb87875e2014-07-21 14:19:01 -07001559 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001560 type = "enableCBS";
1561 result = TYPE_MOBILE_CBS;
1562 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1563 type = "enableIMS";
1564 result = TYPE_MOBILE_IMS;
1565 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1566 type = "enableFOTA";
1567 result = TYPE_MOBILE_FOTA;
1568 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1569 type = "enableDUN";
1570 result = TYPE_MOBILE_DUN;
1571 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001572 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001573 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001574 // back out this hack for mms as they no longer need this and it's causing
1575 // device slowdowns - b/23350688 (note, supl still needs this)
1576 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1577 // type = "enableMMS";
1578 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001579 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1580 type = "enableHIPRI";
1581 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001582 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001583 if (type != null) {
1584 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1585 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1586 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001587 }
1588 }
1589 return TYPE_NONE;
1590 }
1591
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001592 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001593 if (netCap == null) return TYPE_NONE;
1594 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1595 return TYPE_MOBILE_CBS;
1596 }
1597 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1598 return TYPE_MOBILE_IMS;
1599 }
1600 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1601 return TYPE_MOBILE_FOTA;
1602 }
1603 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1604 return TYPE_MOBILE_DUN;
1605 }
1606 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1607 return TYPE_MOBILE_SUPL;
1608 }
1609 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1610 return TYPE_MOBILE_MMS;
1611 }
1612 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1613 return TYPE_MOBILE_HIPRI;
1614 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001615 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1616 return TYPE_WIFI_P2P;
1617 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001618 return TYPE_NONE;
1619 }
1620
1621 private static class LegacyRequest {
1622 NetworkCapabilities networkCapabilities;
1623 NetworkRequest networkRequest;
1624 int expireSequenceNumber;
1625 Network currentNetwork;
1626 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001627
1628 private void clearDnsBinding() {
1629 if (currentNetwork != null) {
1630 currentNetwork = null;
1631 setProcessDefaultNetworkForHostResolution(null);
1632 }
1633 }
1634
Robert Greenwalt6078b502014-06-11 16:05:07 -07001635 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001636 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001637 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001638 currentNetwork = network;
1639 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001640 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001641 }
1642 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001643 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001644 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001645 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1646 }
1647 };
1648 }
1649
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001650 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001651 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1652 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001653
1654 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1655 synchronized (sLegacyRequests) {
1656 LegacyRequest l = sLegacyRequests.get(netCap);
1657 if (l != null) return l.networkRequest;
1658 }
1659 return null;
1660 }
1661
1662 private void renewRequestLocked(LegacyRequest l) {
1663 l.expireSequenceNumber++;
1664 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1665 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1666 }
1667
1668 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1669 int ourSeqNum = -1;
1670 synchronized (sLegacyRequests) {
1671 LegacyRequest l = sLegacyRequests.get(netCap);
1672 if (l == null) return;
1673 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001674 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001675 }
1676 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1677 }
1678
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001679 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001680 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1681 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001682 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001683 try {
1684 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001685 } catch (RemoteException e) {
1686 throw e.rethrowFromSystemServer();
1687 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001688 LegacyRequest l = new LegacyRequest();
1689 l.networkCapabilities = netCap;
1690 l.delay = delay;
1691 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001692 l.networkRequest = sendRequestForNetwork(
1693 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001694 if (l.networkRequest == null) return null;
1695 sLegacyRequests.put(netCap, l);
1696 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1697 return l.networkRequest;
1698 }
1699
1700 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1701 if (delay >= 0) {
1702 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001703 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001704 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1705 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001706 }
1707 }
1708
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001709 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001710 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1711 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001712 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001713 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001714 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001715 if (l == null) return false;
1716 unregisterNetworkCallback(l.networkCallback);
1717 l.clearDnsBinding();
1718 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 }
1720
Erik Kline35bf06c2017-01-26 18:08:28 +09001721 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1722 static {
1723 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1724 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1725 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1726 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1727 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1728 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1729 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1730 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1731 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1732 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1733 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1734 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1735 }
1736
1737 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1738 static {
1739 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1740 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1741 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1742 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1743 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1744 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1745 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1746 }
1747
1748 /**
1749 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1750 * instance suitable for registering a request or callback. Throws an
1751 * IllegalArgumentException if no mapping from the legacy type to
1752 * NetworkCapabilities is known.
1753 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001754 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1755 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001756 * @hide
1757 */
1758 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1759 final NetworkCapabilities nc = new NetworkCapabilities();
1760
1761 // Map from type to transports.
1762 final int NOT_FOUND = -1;
1763 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001764 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001765 nc.addTransportType(transport);
1766
1767 // Map from type to capabilities.
1768 nc.addCapability(sLegacyTypeToCapability.get(
1769 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1770 nc.maybeMarkCapabilitiesRestricted();
1771 return nc;
1772 }
1773
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001774 /** @hide */
1775 public static class PacketKeepaliveCallback {
Artur Satayev751e5512019-11-15 19:12:49 +00001776 @UnsupportedAppUsage
1777 public PacketKeepaliveCallback() {
1778 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001779 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001780 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001781 public void onStarted() {}
1782 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001783 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001784 public void onStopped() {}
1785 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001786 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001787 public void onError(int error) {}
1788 }
1789
1790 /**
1791 * Allows applications to request that the system periodically send specific packets on their
1792 * behalf, using hardware offload to save battery power.
1793 *
1794 * To request that the system send keepalives, call one of the methods that return a
1795 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1796 * passing in a non-null callback. If the callback is successfully started, the callback's
1797 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1798 * specifying one of the {@code ERROR_*} constants in this class.
1799 *
Chalard Jean4d660112018-06-04 16:52:49 +09001800 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1801 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1802 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001803 *
junyulai48eac1d42018-12-27 17:25:29 +08001804 * @deprecated Use {@link SocketKeepalive} instead.
1805 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001806 * @hide
1807 */
1808 public class PacketKeepalive {
1809
1810 private static final String TAG = "PacketKeepalive";
1811
1812 /** @hide */
1813 public static final int SUCCESS = 0;
1814
1815 /** @hide */
1816 public static final int NO_KEEPALIVE = -1;
1817
1818 /** @hide */
1819 public static final int BINDER_DIED = -10;
1820
1821 /** The specified {@code Network} is not connected. */
1822 public static final int ERROR_INVALID_NETWORK = -20;
1823 /** The specified IP addresses are invalid. For example, the specified source IP address is
1824 * not configured on the specified {@code Network}. */
1825 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1826 /** The requested port is invalid. */
1827 public static final int ERROR_INVALID_PORT = -22;
1828 /** The packet length is invalid (e.g., too long). */
1829 public static final int ERROR_INVALID_LENGTH = -23;
1830 /** The packet transmission interval is invalid (e.g., too short). */
1831 public static final int ERROR_INVALID_INTERVAL = -24;
1832
1833 /** The hardware does not support this request. */
1834 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001835 /** The hardware returned an error. */
1836 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001837
Nathan Harold63dd8132018-02-14 13:09:45 -08001838 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001839 public static final int NATT_PORT = 4500;
1840
Nathan Harold63dd8132018-02-14 13:09:45 -08001841 /** The minimum interval in seconds between keepalive packet transmissions */
1842 public static final int MIN_INTERVAL = 10;
1843
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001844 private final Network mNetwork;
junyulai7c469172019-01-16 20:23:34 +08001845 private final ISocketKeepaliveCallback mCallback;
1846 private final ExecutorService mExecutor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001847
1848 private volatile Integer mSlot;
1849
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001850 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001851 public void stop() {
1852 try {
junyulai7c469172019-01-16 20:23:34 +08001853 mExecutor.execute(() -> {
1854 try {
1855 if (mSlot != null) {
1856 mService.stopKeepalive(mNetwork, mSlot);
1857 }
1858 } catch (RemoteException e) {
1859 Log.e(TAG, "Error stopping packet keepalive: ", e);
1860 throw e.rethrowFromSystemServer();
1861 }
1862 });
1863 } catch (RejectedExecutionException e) {
1864 // The internal executor has already stopped due to previous event.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001865 }
1866 }
1867
1868 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001869 Preconditions.checkNotNull(network, "network cannot be null");
1870 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001871 mNetwork = network;
junyulai7c469172019-01-16 20:23:34 +08001872 mExecutor = Executors.newSingleThreadExecutor();
1873 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001874 @Override
junyulai7c469172019-01-16 20:23:34 +08001875 public void onStarted(int slot) {
1876 Binder.withCleanCallingIdentity(() ->
1877 mExecutor.execute(() -> {
1878 mSlot = slot;
1879 callback.onStarted();
1880 }));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001881 }
junyulai7c469172019-01-16 20:23:34 +08001882
1883 @Override
1884 public void onStopped() {
1885 Binder.withCleanCallingIdentity(() ->
1886 mExecutor.execute(() -> {
1887 mSlot = null;
1888 callback.onStopped();
1889 }));
1890 mExecutor.shutdown();
1891 }
1892
1893 @Override
1894 public void onError(int error) {
1895 Binder.withCleanCallingIdentity(() ->
1896 mExecutor.execute(() -> {
1897 mSlot = null;
1898 callback.onError(error);
1899 }));
1900 mExecutor.shutdown();
1901 }
1902
1903 @Override
1904 public void onDataReceived() {
1905 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1906 // this callback when data is received.
1907 }
1908 };
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001909 }
1910 }
1911
1912 /**
1913 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1914 *
junyulai48eac1d42018-12-27 17:25:29 +08001915 * @deprecated Use {@link #createSocketKeepalive} instead.
1916 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001917 * @hide
1918 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001919 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001920 public PacketKeepalive startNattKeepalive(
1921 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1922 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1923 final PacketKeepalive k = new PacketKeepalive(network, callback);
1924 try {
junyulai7c469172019-01-16 20:23:34 +08001925 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001926 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1927 } catch (RemoteException e) {
1928 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai7c469172019-01-16 20:23:34 +08001929 throw e.rethrowFromSystemServer();
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001930 }
1931 return k;
1932 }
1933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 /**
junyulai48eac1d42018-12-27 17:25:29 +08001935 * Request that keepalives be started on a IPsec NAT-T socket.
1936 *
1937 * @param network The {@link Network} the socket is on.
1938 * @param socket The socket that needs to be kept alive.
1939 * @param source The source address of the {@link UdpEncapsulationSocket}.
1940 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1941 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1942 * must run callback sequentially, otherwise the order of callbacks cannot be
1943 * guaranteed.
1944 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1945 * changes. Must be extended by applications that use this API.
1946 *
junyulai352dc2f2019-01-08 20:04:33 +08001947 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1948 * given socket.
junyulai48eac1d42018-12-27 17:25:29 +08001949 **/
junyulai0c666972019-03-04 22:45:36 +08001950 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai48eac1d42018-12-27 17:25:29 +08001951 @NonNull UdpEncapsulationSocket socket,
1952 @NonNull InetAddress source,
1953 @NonNull InetAddress destination,
1954 @NonNull @CallbackExecutor Executor executor,
1955 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001956 ParcelFileDescriptor dup;
1957 try {
junyulai15178152019-03-27 11:00:37 +08001958 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1959 // which cannot be obtained by the app process.
junyulai0c666972019-03-04 22:45:36 +08001960 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1961 } catch (IOException ignored) {
1962 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1963 // ERROR_INVALID_SOCKET.
1964 dup = new ParcelFileDescriptor(new FileDescriptor());
1965 }
1966 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1967 destination, executor, callback);
junyulai215b8772019-01-15 11:32:44 +08001968 }
1969
1970 /**
1971 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1972 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1973 *
1974 * @param network The {@link Network} the socket is on.
junyulai0c666972019-03-04 22:45:36 +08001975 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1976 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1977 * from that port.
junyulai215b8772019-01-15 11:32:44 +08001978 * @param source The source address of the {@link UdpEncapsulationSocket}.
1979 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1980 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1981 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1982 * must run callback sequentially, otherwise the order of callbacks cannot be
1983 * guaranteed.
1984 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1985 * changes. Must be extended by applications that use this API.
1986 *
junyulai352dc2f2019-01-08 20:04:33 +08001987 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1988 * given socket.
junyulai215b8772019-01-15 11:32:44 +08001989 * @hide
1990 */
1991 @SystemApi
1992 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08001993 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1994 @NonNull ParcelFileDescriptor pfd,
junyulai215b8772019-01-15 11:32:44 +08001995 @NonNull InetAddress source,
1996 @NonNull InetAddress destination,
1997 @NonNull @CallbackExecutor Executor executor,
1998 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001999 ParcelFileDescriptor dup;
2000 try {
junyulai15178152019-03-27 11:00:37 +08002001 // TODO: Consider remove unnecessary dup.
junyulai0c666972019-03-04 22:45:36 +08002002 dup = pfd.dup();
2003 } catch (IOException ignored) {
2004 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2005 // ERROR_INVALID_SOCKET.
2006 dup = new ParcelFileDescriptor(new FileDescriptor());
2007 }
2008 return new NattSocketKeepalive(mService, network, dup,
2009 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08002010 }
2011
2012 /**
junyulai352dc2f2019-01-08 20:04:33 +08002013 * Request that keepalives be started on a TCP socket.
2014 * The socket must be established.
2015 *
2016 * @param network The {@link Network} the socket is on.
2017 * @param socket The socket that needs to be kept alive.
2018 * @param executor The executor on which callback will be invoked. This implementation assumes
2019 * the provided {@link Executor} runs the callbacks in sequence with no
2020 * concurrency. Failing this, no guarantee of correctness can be made. It is
2021 * the responsibility of the caller to ensure the executor provides this
2022 * guarantee. A simple way of creating such an executor is with the standard
2023 * tool {@code Executors.newSingleThreadExecutor}.
2024 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2025 * changes. Must be extended by applications that use this API.
2026 *
2027 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2028 * given socket.
2029 * @hide
2030 */
2031 @SystemApi
2032 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08002033 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai352dc2f2019-01-08 20:04:33 +08002034 @NonNull Socket socket,
2035 @NonNull Executor executor,
2036 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08002037 ParcelFileDescriptor dup;
2038 try {
2039 dup = ParcelFileDescriptor.fromSocket(socket);
2040 } catch (UncheckedIOException ignored) {
2041 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2042 // ERROR_INVALID_SOCKET.
2043 dup = new ParcelFileDescriptor(new FileDescriptor());
2044 }
2045 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai352dc2f2019-01-08 20:04:33 +08002046 }
2047
2048 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 * Ensure that a network route exists to deliver traffic to the specified
2050 * host via the specified network interface. An attempt to add a route that
2051 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002052 *
2053 * <p>This method requires the caller to hold either the
2054 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2055 * or the ability to modify system settings as determined by
2056 * {@link android.provider.Settings.System#canWrite}.</p>
2057 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 * @param networkType the type of the network over which traffic to the specified
2059 * host is to be routed
2060 * @param hostAddress the IP address of the host to which the route is desired
2061 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002062 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002063 * @deprecated Deprecated in favor of the
2064 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2065 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07002066 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002067 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09002068 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002070 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002072 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002073 }
2074
2075 /**
2076 * Ensure that a network route exists to deliver traffic to the specified
2077 * host via the specified network interface. An attempt to add a route that
2078 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002079 *
2080 * <p>This method requires the caller to hold either the
2081 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2082 * or the ability to modify system settings as determined by
2083 * {@link android.provider.Settings.System#canWrite}.</p>
2084 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002085 * @param networkType the type of the network over which traffic to the specified
2086 * host is to be routed
2087 * @param hostAddress the IP address of the host to which the route is desired
2088 * @return {@code true} on success, {@code false} on failure
2089 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002090 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002091 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002092 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002093 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002094 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002095 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002096 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002098 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002100 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 }
2102 }
2103
2104 /**
2105 * Returns the value of the setting for background data usage. If false,
2106 * applications should not use the network if the application is not in the
2107 * foreground. Developers should respect this setting, and check the value
2108 * of this before performing any background data operations.
2109 * <p>
2110 * All applications that have background services that use the network
2111 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002112 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002113 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002114 * background data depends on several combined factors, and this method will
2115 * always return {@code true}. Instead, when background data is unavailable,
2116 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002117 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 * @return Whether background data usage is allowed.
2119 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002120 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002122 // assume that background data is allowed; final authority is
2123 // NetworkInfo which may be blocked.
2124 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 }
2126
2127 /**
2128 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002129 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 * @param allowBackgroundData Whether an application should use data while
2131 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002132 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2134 * @see #getBackgroundDataSetting()
2135 * @hide
2136 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002137 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002138 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002140 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002142
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002143 /** {@hide} */
2144 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002145 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002146 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2147 try {
2148 return mService.getActiveNetworkQuotaInfo();
2149 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002150 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002151 }
2152 }
2153
2154 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002155 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002156 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002157 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002158 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002159 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002160 public boolean getMobileDataEnabled() {
Meng Wanga73bed82019-11-18 17:10:00 -08002161 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2162 if (tm != null) {
2163 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2164 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2165 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2166 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2167 + " retVal=" + retVal);
2168 return retVal;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002169 }
Wink Saville36ffb042014-12-05 11:10:30 -08002170 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002171 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002172 }
2173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002175 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002176 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002177 */
2178 public interface OnNetworkActiveListener {
2179 /**
2180 * Called on the main thread of the process to report that the current data network
2181 * has become active, and it is now a good time to perform any pending network
2182 * operations. Note that this listener only tells you when the network becomes
2183 * active; if at any other time you want to know whether it is active (and thus okay
2184 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002185 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002186 */
Chalard Jean4d660112018-06-04 16:52:49 +09002187 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002188 }
2189
2190 private INetworkManagementService getNetworkManagementService() {
2191 synchronized (this) {
2192 if (mNMService != null) {
2193 return mNMService;
2194 }
2195 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2196 mNMService = INetworkManagementService.Stub.asInterface(b);
2197 return mNMService;
2198 }
2199 }
2200
2201 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002202 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002203
2204 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002205 * Start listening to reports when the system's default data network is active, meaning it is
2206 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2207 * to determine the current state of the system's default network after registering the
2208 * listener.
2209 * <p>
2210 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002211 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002212 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002213 *
2214 * @param l The listener to be told when the network is active.
2215 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002216 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002217 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2218 @Override
2219 public void onNetworkActive() throws RemoteException {
2220 l.onNetworkActive();
2221 }
2222 };
2223
2224 try {
2225 getNetworkManagementService().registerNetworkActivityListener(rl);
2226 mNetworkActivityListeners.put(l, rl);
2227 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002228 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002229 }
2230 }
2231
2232 /**
2233 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002234 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002235 *
2236 * @param l Previously registered listener.
2237 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002238 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002239 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002240 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002241 try {
2242 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2243 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002244 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002245 }
2246 }
2247
2248 /**
2249 * Return whether the data network is currently active. An active network means that
2250 * it is currently in a high power state for performing data transmission. On some
2251 * types of networks, it may be expensive to move and stay in such a state, so it is
2252 * more power efficient to batch network traffic together when the radio is already in
2253 * this state. This method tells you whether right now is currently a good time to
2254 * initiate network traffic, as the network is already active.
2255 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002256 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002257 try {
2258 return getNetworkManagementService().isNetworkActive();
2259 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002260 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002261 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002262 }
2263
2264 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 * {@hide}
2266 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002267 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002268 mContext = Preconditions.checkNotNull(context, "missing context");
2269 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05002270 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002272
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002273 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002274 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002275 public static ConnectivityManager from(Context context) {
2276 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2277 }
2278
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002279 /** @hide */
2280 public NetworkRequest getDefaultRequest() {
2281 try {
2282 // This is not racy as the default request is final in ConnectivityService.
2283 return mService.getDefaultRequest();
2284 } catch (RemoteException e) {
2285 throw e.rethrowFromSystemServer();
2286 }
2287 }
2288
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002289 /* TODO: These permissions checks don't belong in client-side code. Move them to
2290 * services.jar, possibly in com.android.server.net. */
2291
2292 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002293 public static final void enforceChangePermission(Context context) {
2294 int uid = Binder.getCallingUid();
2295 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2296 .getPackageNameForUid(context, uid), true /* throwException */);
2297 }
2298
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002299 /** {@hide} */
2300 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002301 Preconditions.checkNotNull(context, "Context cannot be null");
2302 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002303
Robert Greenwaltedb47662014-09-16 17:54:19 -07002304 if (context.getResources().getStringArray(
2305 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2306 // Have a provisioning app - must only let system apps (which check this app)
2307 // turn on tethering
2308 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002309 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002310 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002311 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002312 // If callingPkg's uid is not same as Binder.getCallingUid(),
2313 // AppOpsService throws SecurityException.
2314 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2315 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002316 }
2317 }
2318
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002319 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002320 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2321 * situations where a Context pointer is unavailable.
2322 * @hide
2323 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002324 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002325 static ConnectivityManager getInstanceOrNull() {
2326 return sInstance;
2327 }
2328
2329 /**
2330 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2331 * situations where a Context pointer is unavailable.
2332 * @hide
2333 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002334 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002335 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002336 private static ConnectivityManager getInstance() {
2337 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002338 throw new IllegalStateException("No ConnectivityManager yet constructed");
2339 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002340 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002341 }
2342
markchienae8aa642019-12-16 20:15:20 +08002343 private static final int TETHERING_TIMEOUT_MS = 60_000;
2344 private final Object mTetheringLock = new Object();
2345
2346 private TetheringManager getTetheringManager() {
2347 synchronized (mTetheringLock) {
2348 if (mTetheringManager != null) {
2349 return mTetheringManager;
2350 }
2351 final long before = System.currentTimeMillis();
2352 while ((mTetheringManager = (TetheringManager) mContext.getSystemService(
2353 Context.TETHERING_SERVICE)) == null) {
2354 if (System.currentTimeMillis() - before > TETHERING_TIMEOUT_MS) {
2355 Log.e(TAG, "Timeout waiting tethering service not ready yet");
2356 throw new IllegalStateException("No tethering service yet");
2357 }
2358 SystemClock.sleep(100);
2359 }
2360
2361 return mTetheringManager;
2362 }
2363 }
2364
Paul Jensene0bef712014-12-10 15:12:18 -05002365 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002366 * Get the set of tetherable, available interfaces. This list is limited by
2367 * device configuration and current interface existence.
2368 *
2369 * @return an array of 0 or more Strings of tetherable interface names.
2370 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002371 * {@hide}
2372 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002373 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002374 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002375 public String[] getTetherableIfaces() {
markchienae8aa642019-12-16 20:15:20 +08002376 return getTetheringManager().getTetherableIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002377 }
2378
2379 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002380 * Get the set of tethered interfaces.
2381 *
2382 * @return an array of 0 or more String of currently tethered interface names.
2383 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002384 * {@hide}
2385 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002386 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002387 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002388 public String[] getTetheredIfaces() {
markchienae8aa642019-12-16 20:15:20 +08002389 return getTetheringManager().getTetheredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002390 }
2391
2392 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002393 * Get the set of interface names which attempted to tether but
2394 * failed. Re-attempting to tether may cause them to reset to the Tethered
2395 * state. Alternatively, causing the interface to be destroyed and recreated
2396 * may cause them to reset to the available state.
2397 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2398 * information on the cause of the errors.
2399 *
2400 * @return an array of 0 or more String indicating the interface names
2401 * which failed to tether.
2402 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002403 * {@hide}
2404 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002405 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002406 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002407 public String[] getTetheringErroredIfaces() {
markchienae8aa642019-12-16 20:15:20 +08002408 return getTetheringManager().getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002409 }
2410
2411 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002412 * Get the set of tethered dhcp ranges.
2413 *
2414 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
2415 * {@hide}
2416 */
paulhua6af6b62019-08-12 16:25:11 +08002417 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002418 public String[] getTetheredDhcpRanges() {
markchienae8aa642019-12-16 20:15:20 +08002419 return getTetheringManager().getTetheredDhcpRanges();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002420 }
2421
2422 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002423 * Attempt to tether the named interface. This will setup a dhcp server
2424 * on the interface, forward and NAT IP packets and forward DNS requests
2425 * to the best active upstream network interface. Note that if no upstream
2426 * IP network interface is available, dhcp will still run and traffic will be
2427 * allowed between the tethered devices and this device, though upstream net
2428 * access will of course fail until an upstream network interface becomes
2429 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002430 *
2431 * <p>This method requires the caller to hold either the
2432 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2433 * or the ability to modify system settings as determined by
2434 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002435 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002436 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2437 * and WifiStateMachine which need direct access. All other clients should use
2438 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2439 * logic.</p>
2440 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002441 * @param iface the interface name to tether.
2442 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2443 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002444 * {@hide}
2445 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002446 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002447 public int tether(String iface) {
markchienae8aa642019-12-16 20:15:20 +08002448 return getTetheringManager().tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002449 }
2450
2451 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002452 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002453 *
2454 * <p>This method requires the caller to hold either the
2455 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2456 * or the ability to modify system settings as determined by
2457 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002458 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002459 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2460 * and WifiStateMachine which need direct access. All other clients should use
2461 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2462 * logic.</p>
2463 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002464 * @param iface the interface name to untether.
2465 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2466 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002467 * {@hide}
2468 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002469 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002470 public int untether(String iface) {
markchienae8aa642019-12-16 20:15:20 +08002471 return getTetheringManager().untether(iface);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002472 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002473
2474 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002475 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002476 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002477 * due to device configuration.
2478 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002479 * <p>If this app does not have permission to use this API, it will always
2480 * return false rather than throw an exception.</p>
2481 *
2482 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2483 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2484 *
2485 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2486 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2487 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002488 * @return a boolean - {@code true} indicating Tethering is supported.
2489 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002490 * {@hide}
2491 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002492 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002493 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2494 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002495 public boolean isTetheringSupported() {
markchienae8aa642019-12-16 20:15:20 +08002496 return getTetheringManager().isTetheringSupported();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002497 }
2498
2499 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002500 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2501 * @hide
2502 */
2503 @SystemApi
2504 public static abstract class OnStartTetheringCallback {
2505 /**
2506 * Called when tethering has been successfully started.
2507 */
Chalard Jean4d660112018-06-04 16:52:49 +09002508 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002509
2510 /**
2511 * Called when starting tethering failed.
2512 */
Chalard Jean4d660112018-06-04 16:52:49 +09002513 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002514 }
2515
2516 /**
2517 * Convenient overload for
2518 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2519 * handler to run on the current thread's {@link Looper}.
2520 * @hide
2521 */
2522 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07002523 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002524 public void startTethering(int type, boolean showProvisioningUi,
2525 final OnStartTetheringCallback callback) {
2526 startTethering(type, showProvisioningUi, callback, null);
2527 }
2528
2529 /**
2530 * Runs tether provisioning for the given type if needed and then starts tethering if
2531 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2532 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2533 * schedules tether provisioning re-checks if appropriate.
2534 *
2535 * @param type The type of tethering to start. Must be one of
2536 * {@link ConnectivityManager.TETHERING_WIFI},
2537 * {@link ConnectivityManager.TETHERING_USB}, or
2538 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2539 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2540 * is one. This should be true the first time this function is called and also any time
2541 * the user can see this UI. It gives users information from their carrier about the
2542 * check failing and how they can sign up for tethering if possible.
2543 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2544 * of the result of trying to tether.
2545 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2546 * @hide
2547 */
2548 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002549 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002550 public void startTethering(int type, boolean showProvisioningUi,
2551 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002552 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002553
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002554 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2555 @Override
2556 protected void onReceiveResult(int resultCode, Bundle resultData) {
2557 if (resultCode == TETHER_ERROR_NO_ERROR) {
2558 callback.onTetheringStarted();
2559 } else {
2560 callback.onTetheringFailed();
2561 }
2562 }
2563 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002564
markchienae8aa642019-12-16 20:15:20 +08002565 getTetheringManager().startTethering(type, wrappedCallback, showProvisioningUi);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002566 }
2567
2568 /**
2569 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2570 * applicable.
2571 *
2572 * @param type The type of tethering to stop. Must be one of
2573 * {@link ConnectivityManager.TETHERING_WIFI},
2574 * {@link ConnectivityManager.TETHERING_USB}, or
2575 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2576 * @hide
2577 */
2578 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002579 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002580 public void stopTethering(int type) {
markchienae8aa642019-12-16 20:15:20 +08002581 getTetheringManager().stopTethering(type);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002582 }
2583
2584 /**
markchien26299ed2019-02-27 14:56:11 +08002585 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2586 * upstream status.
2587 *
2588 *@hide
2589 */
2590 @SystemApi
2591 public abstract static class OnTetheringEventCallback {
2592
2593 /**
2594 * Called when tethering upstream changed. This can be called multiple times and can be
2595 * called any time.
2596 *
2597 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2598 * have any upstream.
2599 */
2600 public void onUpstreamChanged(@Nullable Network network) {}
2601 }
2602
markchien26299ed2019-02-27 14:56:11 +08002603 /**
2604 * Start listening to tethering change events. Any new added callback will receive the last
markchien9f246bd2019-04-03 10:43:09 +08002605 * tethering status right away. If callback is registered when tethering has no upstream or
markchien26299ed2019-02-27 14:56:11 +08002606 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2607 * with a null argument. The same callback object cannot be registered twice.
2608 *
2609 * @param executor the executor on which callback will be invoked.
2610 * @param callback the callback to be called when tethering has change events.
2611 * @hide
2612 */
2613 @SystemApi
2614 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2615 public void registerTetheringEventCallback(
2616 @NonNull @CallbackExecutor Executor executor,
2617 @NonNull final OnTetheringEventCallback callback) {
2618 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2619
markchienae8aa642019-12-16 20:15:20 +08002620 getTetheringManager().registerTetheringEventCallback(executor, callback);
markchien26299ed2019-02-27 14:56:11 +08002621 }
2622
2623 /**
2624 * Remove tethering event callback previously registered with
2625 * {@link #registerTetheringEventCallback}.
2626 *
2627 * @param callback previously registered callback.
2628 * @hide
2629 */
2630 @SystemApi
2631 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2632 public void unregisterTetheringEventCallback(
2633 @NonNull final OnTetheringEventCallback callback) {
markchienae8aa642019-12-16 20:15:20 +08002634 getTetheringManager().unregisterTetheringEventCallback(callback);
markchien26299ed2019-02-27 14:56:11 +08002635 }
2636
2637
2638 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002639 * Get the list of regular expressions that define any tetherable
2640 * USB network interfaces. If USB tethering is not supported by the
2641 * device, this list should be empty.
2642 *
2643 * @return an array of 0 or more regular expression Strings defining
2644 * what interfaces are considered tetherable usb interfaces.
2645 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002646 * {@hide}
2647 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002648 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002649 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002650 public String[] getTetherableUsbRegexs() {
markchienae8aa642019-12-16 20:15:20 +08002651 return getTetheringManager().getTetherableUsbRegexs();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002652 }
2653
2654 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002655 * Get the list of regular expressions that define any tetherable
2656 * Wifi network interfaces. If Wifi tethering is not supported by the
2657 * device, this list should be empty.
2658 *
2659 * @return an array of 0 or more regular expression Strings defining
2660 * what interfaces are considered tetherable wifi interfaces.
2661 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002662 * {@hide}
2663 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002664 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002665 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002666 public String[] getTetherableWifiRegexs() {
markchienae8aa642019-12-16 20:15:20 +08002667 return getTetheringManager().getTetherableWifiRegexs();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002668 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002669
Danica Chang6fdd0c62010-08-11 14:54:43 -07002670 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002671 * Get the list of regular expressions that define any tetherable
2672 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2673 * device, this list should be empty.
2674 *
2675 * @return an array of 0 or more regular expression Strings defining
2676 * what interfaces are considered tetherable bluetooth interfaces.
2677 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002678 * {@hide}
2679 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002680 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002681 @UnsupportedAppUsage
Danica Chang6fdd0c62010-08-11 14:54:43 -07002682 public String[] getTetherableBluetoothRegexs() {
markchienae8aa642019-12-16 20:15:20 +08002683 return getTetheringManager().getTetherableBluetoothRegexs();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002684 }
2685
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002686 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002687 * Attempt to both alter the mode of USB and Tethering of USB. A
2688 * utility method to deal with some of the complexity of USB - will
2689 * attempt to switch to Rndis and subsequently tether the resulting
2690 * interface on {@code true} or turn off tethering and switch off
2691 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002692 *
2693 * <p>This method requires the caller to hold either the
2694 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2695 * or the ability to modify system settings as determined by
2696 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002697 *
2698 * @param enable a boolean - {@code true} to enable tethering
2699 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2700 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002701 * {@hide}
2702 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002703 @UnsupportedAppUsage
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002704 public int setUsbTethering(boolean enable) {
markchienae8aa642019-12-16 20:15:20 +08002705 return getTetheringManager().setUsbTethering(enable);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002706 }
2707
Robert Greenwalt5a735062010-03-02 17:25:02 -08002708 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002709 @SystemApi
Robert Greenwalt5a735062010-03-02 17:25:02 -08002710 public static final int TETHER_ERROR_NO_ERROR = 0;
2711 /** {@hide} */
2712 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2713 /** {@hide} */
2714 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2715 /** {@hide} */
2716 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2717 /** {@hide} */
2718 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2719 /** {@hide} */
2720 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2721 /** {@hide} */
2722 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2723 /** {@hide} */
2724 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2725 /** {@hide} */
2726 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2727 /** {@hide} */
2728 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2729 /** {@hide} */
2730 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002731 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002732 @SystemApi
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002733 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +09002734 /** {@hide} */
2735 public static final int TETHER_ERROR_DHCPSERVER_ERROR = 12;
markchienf2731272019-01-16 17:44:13 +08002736 /** {@hide} */
2737 @SystemApi
2738 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002739
2740 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002741 * Get a more detailed error code after a Tethering or Untethering
2742 * request asynchronously failed.
2743 *
2744 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002745 * @return error The error code of the last error tethering or untethering the named
2746 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002747 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002748 * {@hide}
2749 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002750 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002751 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002752 public int getLastTetherError(String iface) {
markchienae8aa642019-12-16 20:15:20 +08002753 return getTetheringManager().getLastTetherError(iface);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002754 }
2755
markchien9554abf2019-03-06 16:25:00 +08002756 /** @hide */
2757 @Retention(RetentionPolicy.SOURCE)
2758 @IntDef(value = {
2759 TETHER_ERROR_NO_ERROR,
2760 TETHER_ERROR_PROVISION_FAILED,
2761 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2762 })
2763 public @interface EntitlementResultCode {
2764 }
2765
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002766 /**
markchien9554abf2019-03-06 16:25:00 +08002767 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchienf2731272019-01-16 17:44:13 +08002768 * entitlement succeeded.
2769 * @hide
2770 */
2771 @SystemApi
markchien9554abf2019-03-06 16:25:00 +08002772 public interface OnTetheringEntitlementResultListener {
2773 /**
2774 * Called to notify entitlement result.
2775 *
2776 * @param resultCode an int value of entitlement result. It may be one of
2777 * {@link #TETHER_ERROR_NO_ERROR},
2778 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2779 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2780 */
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002781 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchien9554abf2019-03-06 16:25:00 +08002782 }
2783
2784 /**
markchienf2731272019-01-16 17:44:13 +08002785 * Get the last value of the entitlement check on this downstream. If the cached value is
2786 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2787 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2788 * guaranteed that the UI-based entitlement check will complete in any specific time period
2789 * and may in fact never complete. Any successful entitlement check the platform performs for
2790 * any reason will update the cached value.
2791 *
2792 * @param type the downstream type of tethering. Must be one of
2793 * {@link #TETHERING_WIFI},
2794 * {@link #TETHERING_USB}, or
2795 * {@link #TETHERING_BLUETOOTH}.
2796 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchien9554abf2019-03-06 16:25:00 +08002797 * @param executor the executor on which callback will be invoked.
2798 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2799 * notify the caller of the result of entitlement check. The listener may be called zero
2800 * or one time.
markchienf2731272019-01-16 17:44:13 +08002801 * {@hide}
2802 */
2803 @SystemApi
2804 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchien9554abf2019-03-06 16:25:00 +08002805 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2806 @NonNull @CallbackExecutor Executor executor,
2807 @NonNull final OnTetheringEntitlementResultListener listener) {
2808 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2809 ResultReceiver wrappedListener = new ResultReceiver(null) {
2810 @Override
2811 protected void onReceiveResult(int resultCode, Bundle resultData) {
2812 Binder.withCleanCallingIdentity(() ->
2813 executor.execute(() -> {
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002814 listener.onTetheringEntitlementResult(resultCode);
markchien9554abf2019-03-06 16:25:00 +08002815 }));
2816 }
2817 };
2818
markchienae8aa642019-12-16 20:15:20 +08002819 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
2820 showEntitlementUi);
markchien9554abf2019-03-06 16:25:00 +08002821 }
2822
2823 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002824 * Report network connectivity status. This is currently used only
2825 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002826 * <p>This method requires the caller to hold the permission
2827 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002828 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002829 * @param networkType The type of network you want to report on
2830 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002831 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002832 * {@hide}
2833 */
2834 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002835 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002836 try {
2837 mService.reportInetCondition(networkType, percentage);
2838 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002839 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002840 }
2841 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002842
2843 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002844 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002845 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002846 * the framework to re-evaluate network connectivity and/or switch to another
2847 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002848 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002849 * @param network The {@link Network} the application was attempting to use
2850 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002851 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2852 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002853 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002854 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002855 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002856 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002857 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002858 // One of these will be ignored because it matches system's current state.
2859 // The other will trigger the necessary reevaluation.
2860 mService.reportNetworkConnectivity(network, true);
2861 mService.reportNetworkConnectivity(network, false);
2862 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002863 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002864 }
2865 }
2866
2867 /**
2868 * Report to the framework whether a network has working connectivity.
2869 * This provides a hint to the system that a particular network is providing
2870 * working connectivity or not. In response the framework may re-evaluate
2871 * the network's connectivity and might take further action thereafter.
2872 *
2873 * @param network The {@link Network} the application was attempting to use
2874 * or {@code null} to indicate the current default network.
2875 * @param hasConnectivity {@code true} if the application was able to successfully access the
2876 * Internet using {@code network} or {@code false} if not.
2877 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002878 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002879 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002880 try {
2881 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002882 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002883 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002884 }
2885 }
2886
2887 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002888 * Set a network-independent global http proxy. This is not normally what you want
2889 * for typical HTTP proxies - they are general network dependent. However if you're
2890 * doing something unusual like general internal filtering this may be useful. On
2891 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002892 *
2893 * @param p A {@link ProxyInfo} object defining the new global
2894 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002895 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002896 */
paulhua6af6b62019-08-12 16:25:11 +08002897 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk207900c2014-04-25 15:00:09 -04002898 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002899 try {
2900 mService.setGlobalProxy(p);
2901 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002902 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002903 }
2904 }
2905
2906 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002907 * Retrieve any network-independent global HTTP proxy.
2908 *
Jason Monk207900c2014-04-25 15:00:09 -04002909 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002910 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002911 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002912 */
Jason Monk207900c2014-04-25 15:00:09 -04002913 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002914 try {
2915 return mService.getGlobalProxy();
2916 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002917 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002918 }
2919 }
2920
2921 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002922 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2923 * network-specific HTTP proxy. If {@code network} is null, the
2924 * network-specific proxy returned is the proxy of the default active
2925 * network.
2926 *
2927 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2928 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2929 * or when {@code network} is {@code null},
2930 * the {@code ProxyInfo} for the default active network. Returns
2931 * {@code null} when no proxy applies or the caller doesn't have
2932 * permission to use {@code network}.
2933 * @hide
2934 */
2935 public ProxyInfo getProxyForNetwork(Network network) {
2936 try {
2937 return mService.getProxyForNetwork(network);
2938 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002939 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04002940 }
2941 }
2942
2943 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002944 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
2945 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04002946 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05002947 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002948 *
Jason Monk207900c2014-04-25 15:00:09 -04002949 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002950 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07002951 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002952 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05002953 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04002954 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07002955 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002956
2957 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002958 * Returns true if the hardware supports the given network type
2959 * else it returns false. This doesn't indicate we have coverage
2960 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002961 * hardware supports it. For example a GSM phone without a SIM
2962 * should still return {@code true} for mobile data, but a wifi only
2963 * tablet would return {@code false}.
2964 *
2965 * @param networkType The network type we'd like to check
2966 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002967 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002968 * @hide
2969 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002970 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002971 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09002972 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002973 public boolean isNetworkSupported(int networkType) {
2974 try {
2975 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002976 } catch (RemoteException e) {
2977 throw e.rethrowFromSystemServer();
2978 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002979 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002980
2981 /**
2982 * Returns if the currently active data network is metered. A network is
2983 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002984 * that connection due to monetary costs, data limitations or
2985 * battery/performance issues. You should check this before doing large
2986 * data transfers, and warn the user or delay the operation until another
2987 * network is available.
2988 *
2989 * @return {@code true} if large transfers should be avoided, otherwise
2990 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002991 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002992 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002993 public boolean isActiveNetworkMetered() {
2994 try {
2995 return mService.isActiveNetworkMetered();
2996 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002997 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002998 }
2999 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003000
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003001 /**
3002 * If the LockdownVpn mechanism is enabled, updates the vpn
3003 * with a reload of its profile.
3004 *
3005 * @return a boolean with {@code} indicating success
3006 *
3007 * <p>This method can only be called by the system UID
3008 * {@hide}
3009 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003010 public boolean updateLockdownVpn() {
3011 try {
3012 return mService.updateLockdownVpn();
3013 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003014 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003015 }
3016 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07003017
3018 /**
Wink Saville948282b2013-08-29 08:55:16 -07003019 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07003020 *
Wink Savilleab9321d2013-06-29 21:10:57 -07003021 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07003022 *
3023 * @return time out that will be used, maybe less that suggestedTimeOutMs
3024 * -1 if an error.
3025 *
3026 * {@hide}
3027 */
Wink Saville948282b2013-08-29 08:55:16 -07003028 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003029 int timeOutMs = -1;
3030 try {
Wink Saville948282b2013-08-29 08:55:16 -07003031 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07003032 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003033 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07003034 }
3035 return timeOutMs;
3036 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003037
3038 /**
Wink Saville42d4f082013-07-20 20:31:59 -07003039 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003040 * {@hide}
3041 */
paulhua6af6b62019-08-12 16:25:11 +08003042 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003043 public String getMobileProvisioningUrl() {
3044 try {
3045 return mService.getMobileProvisioningUrl();
3046 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003047 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003048 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003049 }
Wink Saville42d4f082013-07-20 20:31:59 -07003050
3051 /**
Wink Saville948282b2013-08-29 08:55:16 -07003052 * Set sign in error notification to visible or in visible
3053 *
Wink Saville948282b2013-08-29 08:55:16 -07003054 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04003055 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07003056 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003057 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07003058 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003059 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003060 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04003061 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07003062 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003063 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07003064 }
3065 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003066
3067 /**
3068 * Set the value for enabling/disabling airplane mode
3069 *
3070 * @param enable whether to enable airplane mode or not
3071 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003072 * @hide
3073 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003074 @RequiresPermission(anyOf = {
3075 android.Manifest.permission.NETWORK_SETTINGS,
3076 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3077 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09003078 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003079 public void setAirplaneMode(boolean enable) {
3080 try {
3081 mService.setAirplaneMode(enable);
3082 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003083 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003084 }
3085 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003086
Chalard Jean05ab6812018-05-02 21:14:54 +09003087 /** {@hide} - returns the factory serial number */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003088 @UnsupportedAppUsage
paulhua6af6b62019-08-12 16:25:11 +08003089 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
Chalard Jean05ab6812018-05-02 21:14:54 +09003090 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003091 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003092 return mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003093 } catch (RemoteException e) {
3094 throw e.rethrowFromSystemServer();
3095 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003096 }
3097
3098 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00003099 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
paulhua6af6b62019-08-12 16:25:11 +08003100 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
Robert Greenwalta67be032014-05-16 15:49:14 -07003101 public void unregisterNetworkFactory(Messenger messenger) {
3102 try {
3103 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003104 } catch (RemoteException e) {
3105 throw e.rethrowFromSystemServer();
3106 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003107 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003108
Chalard Jean05ab6812018-05-02 21:14:54 +09003109 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3110 // of dependent changes that would conflict throughout the automerger graph. Having this
3111 // temporarily helps with the process of going through with all these dependent changes across
3112 // the entire tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05003113 /**
3114 * @hide
3115 * Register a NetworkAgent with ConnectivityService.
3116 * @return NetID corresponding to NetworkAgent.
3117 */
paulhua6af6b62019-08-12 16:25:11 +08003118 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
Paul Jensen31a94f42015-02-13 14:18:39 -05003119 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003120 NetworkCapabilities nc, int score, NetworkMisc misc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003121 return registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3122 NetworkFactory.SerialNumber.NONE);
3123 }
3124
3125 /**
3126 * @hide
3127 * Register a NetworkAgent with ConnectivityService.
3128 * @return NetID corresponding to NetworkAgent.
3129 */
paulhua6af6b62019-08-12 16:25:11 +08003130 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
Chalard Jean05ab6812018-05-02 21:14:54 +09003131 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
3132 NetworkCapabilities nc, int score, NetworkMisc misc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003133 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003134 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3135 factorySerialNumber);
Paul Jensen31a94f42015-02-13 14:18:39 -05003136 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003137 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05003138 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003139 }
3140
Robert Greenwalt9258c642014-03-26 16:47:06 -07003141 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003142 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3143 * changes. Should be extended by applications wanting notifications.
3144 *
3145 * A {@code NetworkCallback} is registered by calling
3146 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3147 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09003148 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09003149 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3150 * A {@code NetworkCallback} should be registered at most once at any time.
3151 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003152 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003153 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003154 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003155 * Called when the framework connects to a new network to evaluate whether it satisfies this
3156 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3157 * callback. There is no guarantee that this new network will satisfy any requests, or that
3158 * the network will stay connected for longer than the time necessary to evaluate it.
3159 * <p>
3160 * Most applications <b>should not</b> act on this callback, and should instead use
3161 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3162 * the framework in properly evaluating the network &mdash; for example, an application that
3163 * can automatically log in to a captive portal without user intervention.
3164 *
3165 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09003166 *
3167 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07003168 */
paulhu3d67f532019-03-22 16:35:06 +08003169 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003170
3171 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003172 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003173 * This callback may be called more than once if the {@link Network} that is
3174 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003175 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003176 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003177 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3178 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08003179 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003180 * @hide
3181 */
paulhu3d67f532019-03-22 16:35:06 +08003182 public void onAvailable(@NonNull Network network,
3183 @NonNull NetworkCapabilities networkCapabilities,
3184 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003185 // Internally only this method is called when a new network is available, and
3186 // it calls the callback in the same way and order that older versions used
3187 // to call so as not to change the behavior.
3188 onAvailable(network);
3189 if (!networkCapabilities.hasCapability(
3190 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3191 onNetworkSuspended(network);
3192 }
3193 onCapabilitiesChanged(network, networkCapabilities);
3194 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003195 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003196 }
3197
3198 /**
3199 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean599ce752019-08-30 16:27:28 +09003200 *
3201 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3202 * be available at the same time, and onAvailable will be called for each of these as they
3203 * appear.
3204 *
3205 * <p>For callbacks registered with {@link #requestNetwork} and
3206 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3207 * is the new best network for this request and is now tracked by this callback ; this
3208 * callback will no longer receive method calls about other networks that may have been
3209 * passed to this method previously. The previously-best network may have disconnected, or
3210 * it may still be around and the newly-best network may simply be better.
3211 *
3212 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3213 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3214 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3215 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3216 *
3217 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3218 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3219 * this callback as this is prone to race conditions (there is no guarantee the objects
3220 * returned by these methods will be current). Instead, wait for a call to
3221 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3222 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3223 * to be well-ordered with respect to other callbacks.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003224 *
3225 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003226 */
paulhu3d67f532019-03-22 16:35:06 +08003227 public void onAvailable(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003228
3229 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003230 * Called when the network is about to be lost, typically because there are no outstanding
3231 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3232 * with the new replacement network for graceful handover. This method is not guaranteed
3233 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3234 * network is suddenly disconnected.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003235 *
Chalard Jean599ce752019-08-30 16:27:28 +09003236 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3237 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3238 * this callback as this is prone to race conditions ; calling these methods while in a
3239 * callback may return an outdated or even a null object.
3240 *
3241 * @param network The {@link Network} that is about to be lost.
3242 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3243 * connected for graceful handover; note that the network may still
3244 * suffer a hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003245 */
paulhu3d67f532019-03-22 16:35:06 +08003246 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003247
3248 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003249 * Called when a network disconnects or otherwise no longer satisfies this request or
3250 * callback.
3251 *
3252 * <p>If the callback was registered with requestNetwork() or
3253 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3254 * returned by onAvailable() when that network is lost and no other network satisfies
3255 * the criteria of the request.
3256 *
3257 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3258 * each network which no longer satisfies the criteria of the callback.
3259 *
3260 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3261 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3262 * this callback as this is prone to race conditions ; calling these methods while in a
3263 * callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003264 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003265 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003266 */
paulhu3d67f532019-03-22 16:35:06 +08003267 public void onLost(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003268
3269 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003270 * Called if no network is found within the timeout time specified in
Etan Cohenddb720a2019-01-08 12:09:18 -08003271 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3272 * requested network request cannot be fulfilled (whether or not a timeout was
3273 * specified). When this callback is invoked the associated
Etan Cohenaebf17e2017-03-01 12:47:28 -08003274 * {@link NetworkRequest} will have already been removed and released, as if
3275 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003276 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003277 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003278
3279 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003280 * Called when the network corresponding to this request changes capabilities but still
3281 * satisfies the requested criteria.
3282 *
3283 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3284 * to be called immediately after {@link #onAvailable}.
3285 *
3286 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3287 * ConnectivityManager methods in this callback as this is prone to race conditions :
3288 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003289 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003290 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003291 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3292 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003293 */
paulhu3d67f532019-03-22 16:35:06 +08003294 public void onCapabilitiesChanged(@NonNull Network network,
3295 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003296
3297 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003298 * Called when the network corresponding to this request changes {@link LinkProperties}.
3299 *
3300 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3301 * to be called immediately after {@link #onAvailable}.
3302 *
3303 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3304 * ConnectivityManager methods in this callback as this is prone to race conditions :
3305 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003306 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003307 * @param network The {@link Network} whose link properties have changed.
3308 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003309 */
paulhu3d67f532019-03-22 16:35:06 +08003310 public void onLinkPropertiesChanged(@NonNull Network network,
3311 @NonNull LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003312
Robert Greenwalt8d482522015-06-24 13:23:42 -07003313 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003314 * Called when the network the framework connected to for this request suspends data
3315 * transmission temporarily.
3316 *
3317 * <p>This generally means that while the TCP connections are still live temporarily
3318 * network data fails to transfer. To give a specific example, this is used on cellular
3319 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3320 * means read operations on sockets on this network will block once the buffers are
3321 * drained, and write operations will block once the buffers are full.
3322 *
3323 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3324 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3325 * this callback as this is prone to race conditions (there is no guarantee the objects
3326 * returned by these methods will be current).
3327 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003328 * @hide
3329 */
paulhu3d67f532019-03-22 16:35:06 +08003330 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003331
3332 /**
3333 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003334 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3335 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean599ce752019-08-30 16:27:28 +09003336
3337 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3338 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3339 * this callback as this is prone to race conditions : calling these methods while in a
3340 * callback may return an outdated or even a null object.
3341 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003342 * @hide
3343 */
paulhu3d67f532019-03-22 16:35:06 +08003344 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003345
junyulai05986c62018-08-07 19:50:45 +08003346 /**
3347 * Called when access to the specified network is blocked or unblocked.
3348 *
Chalard Jean599ce752019-08-30 16:27:28 +09003349 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3350 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3351 * this callback as this is prone to race conditions : calling these methods while in a
3352 * callback may return an outdated or even a null object.
3353 *
junyulai05986c62018-08-07 19:50:45 +08003354 * @param network The {@link Network} whose blocked status has changed.
3355 * @param blocked The blocked status of this {@link Network}.
3356 */
junyulai0c666972019-03-04 22:45:36 +08003357 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai05986c62018-08-07 19:50:45 +08003358
Robert Greenwalt6078b502014-06-11 16:05:07 -07003359 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003360 }
3361
Hugo Benichicb883232017-05-11 13:16:17 +09003362 /**
3363 * Constant error codes used by ConnectivityService to communicate about failures and errors
3364 * across a Binder boundary.
3365 * @hide
3366 */
3367 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003368 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003369 }
3370
3371 /** @hide */
3372 public static class TooManyRequestsException extends RuntimeException {}
3373
3374 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3375 switch (e.errorCode) {
3376 case Errors.TOO_MANY_REQUESTS:
3377 return new TooManyRequestsException();
3378 default:
3379 Log.w(TAG, "Unknown service error code " + e.errorCode);
3380 return new RuntimeException(e);
3381 }
3382 }
3383
Robert Greenwalt9258c642014-03-26 16:47:06 -07003384 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003385 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003386 public static final int CALLBACK_PRECHECK = BASE + 1;
3387 /** @hide */
3388 public static final int CALLBACK_AVAILABLE = BASE + 2;
3389 /** @hide arg1 = TTL */
3390 public static final int CALLBACK_LOSING = BASE + 3;
3391 /** @hide */
3392 public static final int CALLBACK_LOST = BASE + 4;
3393 /** @hide */
3394 public static final int CALLBACK_UNAVAIL = BASE + 5;
3395 /** @hide */
3396 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3397 /** @hide */
3398 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003399 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003400 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003401 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003402 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003403 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003404 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003405 /** @hide */
3406 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003407
Erik Kline57faba92015-11-25 12:49:38 +09003408 /** @hide */
3409 public static String getCallbackName(int whichCallback) {
3410 switch (whichCallback) {
3411 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3412 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3413 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3414 case CALLBACK_LOST: return "CALLBACK_LOST";
3415 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3416 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3417 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003418 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3419 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3420 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003421 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003422 default:
3423 return Integer.toString(whichCallback);
3424 }
3425 }
3426
Robert Greenwalt562cc542014-05-15 18:07:26 -07003427 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003428 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003429 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003430
Hugo Benichid42650f2016-07-06 22:53:17 +09003431 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003432 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003433 }
3434
Hugo Benichi2583ef02017-02-02 17:02:36 +09003435 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003436 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003437 }
3438
Robert Greenwalt9258c642014-03-26 16:47:06 -07003439 @Override
3440 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003441 if (message.what == EXPIRE_LEGACY_REQUEST) {
3442 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3443 return;
3444 }
3445
3446 final NetworkRequest request = getObject(message, NetworkRequest.class);
3447 final Network network = getObject(message, Network.class);
3448 final NetworkCallback callback;
3449 synchronized (sCallbacks) {
3450 callback = sCallbacks.get(request);
Etan Cohen4a62d1d2019-05-21 12:06:04 -07003451 if (callback == null) {
3452 Log.w(TAG,
3453 "callback not found for " + getCallbackName(message.what) + " message");
3454 return;
3455 }
Etan Cohen9b09a162019-04-16 15:07:55 -07003456 if (message.what == CALLBACK_UNAVAIL) {
3457 sCallbacks.remove(request);
3458 callback.networkRequest = ALREADY_UNREGISTERED;
3459 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003460 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003461 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003462 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003463 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003464
Robert Greenwalt9258c642014-03-26 16:47:06 -07003465 switch (message.what) {
3466 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003467 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003468 break;
3469 }
3470 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003471 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3472 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003473 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003474 break;
3475 }
3476 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003477 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003478 break;
3479 }
3480 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003481 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003482 break;
3483 }
3484 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003485 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003486 break;
3487 }
3488 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003489 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3490 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003491 break;
3492 }
3493 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003494 LinkProperties lp = getObject(message, LinkProperties.class);
3495 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003496 break;
3497 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003498 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003499 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003500 break;
3501 }
3502 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003503 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003504 break;
3505 }
junyulai05986c62018-08-07 19:50:45 +08003506 case CALLBACK_BLK_CHANGED: {
3507 boolean blocked = message.arg1 != 0;
3508 callback.onBlockedStatusChanged(network, blocked);
3509 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003510 }
3511 }
3512
Hugo Benichid42650f2016-07-06 22:53:17 +09003513 private <T> T getObject(Message msg, Class<T> c) {
3514 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003515 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003516 }
3517
Hugo Benichi2583ef02017-02-02 17:02:36 +09003518 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003519 synchronized (sCallbacks) {
3520 if (sCallbackHandler == null) {
3521 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003522 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003523 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003524 }
3525 }
3526
Hugo Benichi6f260f32017-02-03 14:18:44 +09003527 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3528 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003529
Hugo Benichi6f260f32017-02-03 14:18:44 +09003530 private static final int LISTEN = 1;
3531 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003532
Hugo Benichi6f260f32017-02-03 14:18:44 +09003533 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3534 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003535 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003536 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003537 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003538 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003539 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003540 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003541 if (callback.networkRequest != null
3542 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003543 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3544 // and requests (http://b/20701525).
3545 Log.e(TAG, "NetworkCallback was already registered");
3546 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003547 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003548 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003549 if (action == LISTEN) {
Hugo Benichid42650f2016-07-06 22:53:17 +09003550 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04003551 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003552 request = mService.requestNetwork(
3553 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04003554 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003555 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003556 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003557 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003558 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003559 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003560 } catch (RemoteException e) {
3561 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003562 } catch (ServiceSpecificException e) {
3563 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003564 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003565 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003566 }
3567
3568 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003569 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003570 *
3571 * This is temporarily public @hide so it can be called by system code that uses the
3572 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
3573 * instead network notifications.
3574 *
3575 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
3576 *
3577 * @hide
3578 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003579 public void requestNetwork(@NonNull NetworkRequest request,
3580 @NonNull NetworkCallback networkCallback, int timeoutMs, int legacyType,
3581 @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003582 CallbackHandler cbHandler = new CallbackHandler(handler);
3583 NetworkCapabilities nc = request.networkCapabilities;
3584 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003585 }
3586
3587 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003588 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003589 *
Chalard Jean599ce752019-08-30 16:27:28 +09003590 * <p>This method will attempt to find the best network that matches the passed
3591 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3592 * criteria. The platform will evaluate which network is the best at its own discretion.
3593 * Throughput, latency, cost per byte, policy, user preference and other considerations
3594 * may be factored in the decision of what is considered the best network.
3595 *
3596 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3597 * matching this request, while always attempting to match the request to a better network if
3598 * possible. If a better match is found, the platform will switch this request to the now-best
3599 * network and inform the app of the newly best network by invoking
3600 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3601 * will not try to maintain any other network than the best one currently matching the request:
3602 * a network not matching any network request may be disconnected at any time.
3603 *
3604 * <p>For example, an application could use this method to obtain a connected cellular network
3605 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3606 * radio to consume additional power. Or, an application could inform the system that it wants
3607 * a network supporting sending MMSes and have the system let it know about the currently best
3608 * MMS-supporting network through the provided {@link NetworkCallback}.
3609 *
3610 * <p>The status of the request can be followed by listening to the various callbacks described
3611 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3612 * used to direct traffic to the network (although accessing some networks may be subject to
3613 * holding specific permissions). Callers will learn about the specific characteristics of the
3614 * network through
3615 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3616 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3617 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3618 * matching the request at any given time; therefore when a better network matching the request
3619 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3620 * with the new network after which no further updates are given about the previously-best
3621 * network, unless it becomes the best again at some later time. All callbacks are invoked
3622 * in order on the same thread, which by default is a thread created by the framework running
3623 * in the app.
3624 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3625 * callbacks are invoked.
3626 *
3627 * <p>This{@link NetworkRequest} will live until released via
3628 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3629 * which point the system may let go of the network at any time.
3630 *
3631 * <p>A version of this method which takes a timeout is
3632 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3633 * wait for a limited amount of time for the network to become unavailable.
3634 *
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003635 * <p>It is presently unsupported to request a network with mutable
3636 * {@link NetworkCapabilities} such as
3637 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3638 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3639 * as these {@code NetworkCapabilities} represent states that a particular
3640 * network may never attain, and whether a network will attain these states
3641 * is unknown prior to bringing up the network so the framework does not
Chalard Jean599ce752019-08-30 16:27:28 +09003642 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003643 *
3644 * <p>This method requires the caller to hold either the
3645 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3646 * or the ability to modify system settings as determined by
3647 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003648 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003649 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003650 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3651 * the callback must not be shared - it uniquely specifies this request.
3652 * The callback is invoked on the default internal Handler.
Chalard Jean92c8b672019-05-13 15:13:58 +09003653 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3654 * @throws SecurityException if missing the appropriate permissions.
3655 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003656 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003657 public void requestNetwork(@NonNull NetworkRequest request,
3658 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003659 requestNetwork(request, networkCallback, getDefaultHandler());
3660 }
3661
3662 /**
3663 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3664 *
Chalard Jean599ce752019-08-30 16:27:28 +09003665 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3666 * but runs all the callbacks on the passed Handler.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003667 *
Chalard Jean599ce752019-08-30 16:27:28 +09003668 * <p>This method has the same permission requirements as
3669 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3670 * the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003671 *
3672 * @param request {@link NetworkRequest} describing this request.
3673 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3674 * the callback must not be shared - it uniquely specifies this request.
3675 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003676 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003677 public void requestNetwork(@NonNull NetworkRequest request,
3678 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003679 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3680 CallbackHandler cbHandler = new CallbackHandler(handler);
3681 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003682 }
3683
3684 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003685 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3686 * by a timeout.
3687 *
3688 * This function behaves identically to the non-timed-out version
3689 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3690 * is not found within the given time (in milliseconds) the
3691 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3692 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3693 * not have to be released if timed-out (it is automatically released). Unregistering a
3694 * request that timed out is not an error.
3695 *
3696 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3697 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3698 * for that purpose. Calling this method will attempt to bring up the requested network.
3699 *
Chalard Jean599ce752019-08-30 16:27:28 +09003700 * <p>This method has the same permission requirements as
3701 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3702 * the same conditions.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003703 *
3704 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003705 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3706 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003707 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3708 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3709 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003710 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003711 public void requestNetwork(@NonNull NetworkRequest request,
3712 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003713 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003714 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003715 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003716 }
3717
Hugo Benichi2583ef02017-02-02 17:02:36 +09003718 /**
3719 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3720 * by a timeout.
3721 *
Chalard Jean599ce752019-08-30 16:27:28 +09003722 * This method behaves identically to
3723 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3724 * on the passed Handler.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003725 *
Chalard Jean599ce752019-08-30 16:27:28 +09003726 * <p>This method has the same permission requirements as
3727 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} and throws the same exceptions
3728 * in the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003729 *
3730 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003731 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3732 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003733 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003734 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3735 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003736 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003737 public void requestNetwork(@NonNull NetworkRequest request,
3738 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003739 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003740 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3741 CallbackHandler cbHandler = new CallbackHandler(handler);
3742 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003743 }
3744
3745 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003746 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003747 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003748 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003749 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003750 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3751 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003752 */
Erik Kline90e93072014-11-19 12:12:24 +09003753 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003754
3755 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003756 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003757 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003758 * {@link android.content.Intent#getParcelableExtra(String)}.
3759 */
Erik Kline90e93072014-11-19 12:12:24 +09003760 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003761
3762
3763 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003764 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003765 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003766 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003767 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003768 * the request may outlive the calling application and get called back when a suitable
3769 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003770 * <p>
3771 * The operation is an Intent broadcast that goes to a broadcast receiver that
3772 * you registered with {@link Context#registerReceiver} or through the
3773 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3774 * <p>
3775 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003776 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3777 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003778 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003779 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003780 * Intent to reserve the network or it will be released shortly after the Intent
3781 * is processed.
3782 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003783 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003784 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003785 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003786 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003787 * The request may be released normally by calling
3788 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003789 * <p>It is presently unsupported to request a network with either
3790 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3791 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3792 * as these {@code NetworkCapabilities} represent states that a particular
3793 * network may never attain, and whether a network will attain these states
3794 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003795 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003796 *
3797 * <p>This method requires the caller to hold either the
3798 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3799 * or the ability to modify system settings as determined by
3800 * {@link android.provider.Settings.System#canWrite}.</p>
3801 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003802 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003803 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003804 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003805 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean92c8b672019-05-13 15:13:58 +09003806 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3807 * @throws SecurityException if missing the appropriate permissions.
3808 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003809 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003810 public void requestNetwork(@NonNull NetworkRequest request,
3811 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003812 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003813 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003814 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003815 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003816 } catch (RemoteException e) {
3817 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003818 } catch (ServiceSpecificException e) {
3819 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003820 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003821 }
3822
3823 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003824 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3825 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003826 * This method has the same behavior as
3827 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003828 * releasing network resources and disconnecting.
3829 *
3830 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3831 * PendingIntent passed to
3832 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3833 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3834 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003835 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003836 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003837 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003838 try {
3839 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003840 } catch (RemoteException e) {
3841 throw e.rethrowFromSystemServer();
3842 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003843 }
3844
Hugo Benichie7678512017-05-09 15:19:01 +09003845 private static void checkPendingIntentNotNull(PendingIntent intent) {
3846 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3847 }
3848
3849 private static void checkCallbackNotNull(NetworkCallback callback) {
3850 Preconditions.checkNotNull(callback, "null NetworkCallback");
3851 }
3852
3853 private static void checkTimeout(int timeoutMs) {
3854 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003855 }
3856
3857 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003858 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003859 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003860 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3861 * called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003862 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003863 * @param request {@link NetworkRequest} describing this request.
3864 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3865 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003866 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003867 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003868 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003869 public void registerNetworkCallback(@NonNull NetworkRequest request,
3870 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003871 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3872 }
3873
3874 /**
3875 * Registers to receive notifications about all networks which satisfy the given
3876 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003877 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3878 * called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003879 *
3880 * @param request {@link NetworkRequest} describing this request.
3881 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3882 * networks change state.
3883 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003884 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003885 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003886 public void registerNetworkCallback(@NonNull NetworkRequest request,
3887 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003888 CallbackHandler cbHandler = new CallbackHandler(handler);
3889 NetworkCapabilities nc = request.networkCapabilities;
3890 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003891 }
3892
3893 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003894 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3895 * {@link NetworkRequest}.
3896 *
3897 * This function behaves identically to the version that takes a NetworkCallback, but instead
3898 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3899 * the request may outlive the calling application and get called back when a suitable
3900 * network is found.
3901 * <p>
3902 * The operation is an Intent broadcast that goes to a broadcast receiver that
3903 * you registered with {@link Context#registerReceiver} or through the
3904 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3905 * <p>
3906 * The operation Intent is delivered with two extras, a {@link Network} typed
3907 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3908 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3909 * the original requests parameters.
3910 * <p>
3911 * If there is already a request for this Intent registered (with the equality of
3912 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3913 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3914 * <p>
3915 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003916 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003917 * @param request {@link NetworkRequest} describing this request.
3918 * @param operation Action to perform when the network is available (corresponds
3919 * to the {@link NetworkCallback#onAvailable} call. Typically
3920 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3921 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003922 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003923 public void registerNetworkCallback(@NonNull NetworkRequest request,
3924 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003925 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003926 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04003927 try {
3928 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003929 } catch (RemoteException e) {
3930 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003931 } catch (ServiceSpecificException e) {
3932 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003933 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003934 }
3935
3936 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003937 * Registers to receive notifications about changes in the system default network. The callbacks
3938 * will continue to be called until either the application exits or
3939 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09003940 *
3941 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3942 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003943 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09003944 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003945 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003946 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003947 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
3948 }
3949
3950 /**
3951 * Registers to receive notifications about changes in the system default network. The callbacks
3952 * will continue to be called until either the application exits or
3953 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003954 *
3955 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3956 * system default network changes.
3957 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003958 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003959 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003960 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
3961 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09003962 // This works because if the NetworkCapabilities are null,
3963 // ConnectivityService takes them from the default request.
3964 //
3965 // Since the capabilities are exactly the same as the default request's
3966 // capabilities, this request is guaranteed, at all times, to be
3967 // satisfied by the same network, if any, that satisfies the default
3968 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003969 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09003970 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
3971 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09003972 }
3973
3974 /**
fengludb571472015-04-21 17:12:05 -07003975 * Requests bandwidth update for a given {@link Network} and returns whether the update request
3976 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
3977 * network connection for updated bandwidth information. The caller will be notified via
3978 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003979 * method assumes that the caller has previously called
3980 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
3981 * changes.
fenglub15e72b2015-03-20 11:29:56 -07003982 *
fengluae519192015-04-27 14:28:04 -07003983 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07003984 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07003985 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003986 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003987 try {
fengludb571472015-04-21 17:12:05 -07003988 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07003989 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003990 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07003991 }
3992 }
3993
3994 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003995 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003996 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
3997 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
3998 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09003999 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4000 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004001 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09004002 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4003 * triggering it as soon as this call returns.
4004 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07004005 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004006 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004007 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004008 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004009 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09004010 final List<NetworkRequest> reqs = new ArrayList<>();
4011 // Find all requests associated to this callback and stop callback triggers immediately.
4012 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4013 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09004014 Preconditions.checkArgument(networkCallback.networkRequest != null,
4015 "NetworkCallback was not registered");
Etan Cohen9b09a162019-04-16 15:07:55 -07004016 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4017 Log.d(TAG, "NetworkCallback was already unregistered");
4018 return;
4019 }
Hugo Benichidafed3d2017-03-06 09:17:06 +09004020 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4021 if (e.getValue() == networkCallback) {
4022 reqs.add(e.getKey());
4023 }
4024 }
4025 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4026 for (NetworkRequest r : reqs) {
4027 try {
4028 mService.releaseNetworkRequest(r);
4029 } catch (RemoteException e) {
4030 throw e.rethrowFromSystemServer();
4031 }
4032 // Only remove mapping if rpc was successful.
4033 sCallbacks.remove(r);
4034 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09004035 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004036 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004037 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004038
4039 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004040 * Unregisters a callback previously registered via
4041 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4042 *
4043 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4044 * PendingIntent passed to
4045 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4046 * Cannot be null.
4047 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004048 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09004049 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004050 releaseNetworkRequest(operation);
4051 }
4052
4053 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004054 * Informs the system whether it should switch to {@code network} regardless of whether it is
4055 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4056 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4057 * the system default network regardless of any other network that's currently connected. If
4058 * {@code always} is true, then the choice is remembered, so that the next time the user
4059 * connects to this network, the system will switch to it.
4060 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004061 * @param network The network to accept.
4062 * @param accept Whether to accept the network even if unvalidated.
4063 * @param always Whether to remember this choice in the future.
4064 *
4065 * @hide
4066 */
lucasline252a742019-03-12 13:08:03 +08004067 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004068 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4069 try {
4070 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004071 } catch (RemoteException e) {
4072 throw e.rethrowFromSystemServer();
4073 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004074 }
4075
4076 /**
lucasline252a742019-03-12 13:08:03 +08004077 * Informs the system whether it should consider the network as validated even if it only has
4078 * partial connectivity. If {@code accept} is true, then the network will be considered as
4079 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4080 * is remembered, so that the next time the user connects to this network, the system will
4081 * switch to it.
4082 *
4083 * @param network The network to accept.
4084 * @param accept Whether to consider the network as validated even if it has partial
4085 * connectivity.
4086 * @param always Whether to remember this choice in the future.
4087 *
4088 * @hide
4089 */
4090 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4091 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4092 try {
4093 mService.setAcceptPartialConnectivity(network, accept, always);
4094 } catch (RemoteException e) {
4095 throw e.rethrowFromSystemServer();
4096 }
4097 }
4098
4099 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004100 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4101 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4102 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4103 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4104 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004105 * @param network The network to accept.
4106 *
4107 * @hide
4108 */
lucasline252a742019-03-12 13:08:03 +08004109 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004110 public void setAvoidUnvalidated(Network network) {
4111 try {
4112 mService.setAvoidUnvalidated(network);
4113 } catch (RemoteException e) {
4114 throw e.rethrowFromSystemServer();
4115 }
4116 }
4117
4118 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004119 * Requests that the system open the captive portal app on the specified network.
4120 *
4121 * @param network The network to log into.
4122 *
4123 * @hide
4124 */
paulhua6af6b62019-08-12 16:25:11 +08004125 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004126 public void startCaptivePortalApp(Network network) {
4127 try {
4128 mService.startCaptivePortalApp(network);
4129 } catch (RemoteException e) {
4130 throw e.rethrowFromSystemServer();
4131 }
4132 }
4133
4134 /**
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004135 * Requests that the system open the captive portal app with the specified extras.
4136 *
4137 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4138 * corresponding permission.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004139 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004140 * @param appExtras Extras to include in the app start intent.
4141 * @hide
4142 */
4143 @SystemApi
4144 @TestApi
4145 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhud9736de2019-03-08 16:35:20 +08004146 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004147 try {
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004148 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004149 } catch (RemoteException e) {
4150 throw e.rethrowFromSystemServer();
4151 }
4152 }
4153
4154 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004155 * Determine whether the device is configured to avoid bad wifi.
4156 * @hide
4157 */
4158 @SystemApi
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004159 @RequiresPermission(anyOf = {
4160 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4161 android.Manifest.permission.NETWORK_STACK})
4162 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004163 try {
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004164 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004165 } catch (RemoteException e) {
4166 throw e.rethrowFromSystemServer();
4167 }
4168 }
4169
4170 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004171 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4172 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09004173 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4174 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004175 *
4176 * An example of such an operation might be a time-sensitive foreground activity, such as a
4177 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4178 */
4179 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4180
4181 /**
4182 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4183 * a backup channel for traffic that is primarily going over another network.
4184 *
4185 * An example might be maintaining backup connections to peers or servers for the purpose of
4186 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4187 * on backup paths should be negligible compared to the traffic on the main path.
4188 */
4189 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4190
4191 /**
4192 * It is acceptable to use metered data to improve network latency and performance.
4193 */
4194 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4195
4196 /**
4197 * Return value to use for unmetered networks. On such networks we currently set all the flags
4198 * to true.
4199 * @hide
4200 */
4201 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4202 MULTIPATH_PREFERENCE_HANDOVER |
4203 MULTIPATH_PREFERENCE_RELIABILITY |
4204 MULTIPATH_PREFERENCE_PERFORMANCE;
4205
4206 /** @hide */
4207 @Retention(RetentionPolicy.SOURCE)
4208 @IntDef(flag = true, value = {
4209 MULTIPATH_PREFERENCE_HANDOVER,
4210 MULTIPATH_PREFERENCE_RELIABILITY,
4211 MULTIPATH_PREFERENCE_PERFORMANCE,
4212 })
4213 public @interface MultipathPreference {
4214 }
4215
4216 /**
4217 * Provides a hint to the calling application on whether it is desirable to use the
4218 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4219 * for multipath data transfer on this network when it is not the system default network.
4220 * Applications desiring to use multipath network protocols should call this method before
4221 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004222 *
4223 * @param network The network on which the application desires to use multipath data.
4224 * If {@code null}, this method will return the a preference that will generally
4225 * apply to metered networks.
4226 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4227 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004228 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004229 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004230 try {
4231 return mService.getMultipathPreference(network);
4232 } catch (RemoteException e) {
4233 throw e.rethrowFromSystemServer();
4234 }
4235 }
4236
4237 /**
Stuart Scott984dc852015-03-30 13:17:11 -07004238 * Resets all connectivity manager settings back to factory defaults.
4239 * @hide
4240 */
paulhua6af6b62019-08-12 16:25:11 +08004241 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott984dc852015-03-30 13:17:11 -07004242 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07004243 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07004244 mService.factoryReset();
markchienae8aa642019-12-16 20:15:20 +08004245 getTetheringManager().stopAllTethering();
Stuart Scott984dc852015-03-30 13:17:11 -07004246 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004247 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07004248 }
4249 }
4250
4251 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004252 * Binds the current process to {@code network}. All Sockets created in the future
4253 * (and not explicitly bound via a bound SocketFactory from
4254 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4255 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4256 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4257 * work and all host name resolutions will fail. This is by design so an application doesn't
4258 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4259 * To clear binding pass {@code null} for {@code network}. Using individually bound
4260 * Sockets created by Network.getSocketFactory().createSocket() and
4261 * performing network-specific host name resolutions via
4262 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04004263 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004264 *
4265 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4266 * the current binding.
4267 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4268 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004269 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09004270 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04004271 // instantiated.
4272 return setProcessDefaultNetwork(network);
4273 }
4274
4275 /**
4276 * Binds the current process to {@code network}. All Sockets created in the future
4277 * (and not explicitly bound via a bound SocketFactory from
4278 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4279 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4280 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4281 * work and all host name resolutions will fail. This is by design so an application doesn't
4282 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4283 * To clear binding pass {@code null} for {@code network}. Using individually bound
4284 * Sockets created by Network.getSocketFactory().createSocket() and
4285 * performing network-specific host name resolutions via
4286 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4287 * {@code setProcessDefaultNetwork}.
4288 *
4289 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4290 * the current binding.
4291 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4292 * @deprecated This function can throw {@link IllegalStateException}. Use
4293 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4294 * is a direct replacement.
4295 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004296 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004297 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04004298 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004299 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4300
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09004301 if (netId != NETID_UNSET) {
4302 netId = network.getNetIdForResolv();
Paul Jensenc91b5342014-08-27 12:38:45 -04004303 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004304
4305 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4306 return false;
4307 }
4308
4309 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05004310 // Set HTTP proxy system properties to match network.
4311 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09004312 try {
4313 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4314 } catch (SecurityException e) {
4315 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4316 Log.e(TAG, "Can't set proxy properties", e);
4317 }
Paul Jensenc91b5342014-08-27 12:38:45 -04004318 // Must flush DNS cache as new network may have different DNS resolutions.
4319 InetAddress.clearDnsCache();
4320 // Must flush socket pool as idle sockets will be bound to previous network and may
4321 // cause subsequent fetches to be performed on old network.
4322 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04004323 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004324
4325 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004326 }
4327
4328 /**
4329 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004330 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004331 *
4332 * @return {@code Network} to which this process is bound, or {@code null}.
4333 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004334 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004335 public Network getBoundNetworkForProcess() {
4336 // Forcing callers to call thru non-static function ensures ConnectivityManager
4337 // instantiated.
4338 return getProcessDefaultNetwork();
4339 }
4340
4341 /**
4342 * Returns the {@link Network} currently bound to this process via
4343 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4344 *
4345 * @return {@code Network} to which this process is bound, or {@code null}.
4346 * @deprecated Using this function can lead to other functions throwing
4347 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4348 * {@code getBoundNetworkForProcess} is a direct replacement.
4349 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004350 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004351 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004352 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004353 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004354 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004355 return new Network(netId);
4356 }
4357
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004358 private void unsupportedStartingFrom(int version) {
4359 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004360 // The getApplicationInfo() call we make below is not supported in system context. Let
4361 // the call through here, and rely on the fact that ConnectivityService will refuse to
4362 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004363 return;
4364 }
4365
4366 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4367 throw new UnsupportedOperationException(
4368 "This method is not supported in target SDK version " + version + " and above");
4369 }
4370 }
4371
4372 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4373 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004374 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004375 // remove these exemptions. Note that this check is not secure, and apps can still access these
4376 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4377 // so is unsupported and may break in the future. http://b/22728205
4378 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004379 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004380 }
4381
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004382 /**
4383 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004384 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004385 *
4386 * @param network The {@link Network} to bind host resolutions from the current process to, or
4387 * {@code null} to clear the current binding.
4388 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4389 * @hide
4390 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4391 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004392 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004393 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004394 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004395 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004396 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004397 }
Felipe Leme1b103232016-01-22 09:44:57 -08004398
4399 /**
4400 * Device is not restricting metered network activity while application is running on
4401 * background.
4402 */
4403 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4404
4405 /**
4406 * Device is restricting metered network activity while application is running on background,
4407 * but application is allowed to bypass it.
4408 * <p>
4409 * In this state, application should take action to mitigate metered network access.
4410 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4411 */
4412 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4413
4414 /**
4415 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004416 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004417 * In this state, application should not try to use the network while running on background,
4418 * because it would be denied.
4419 */
4420 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4421
Felipe Leme9778f762016-01-27 14:46:39 -08004422 /**
4423 * A change in the background metered network activity restriction has occurred.
4424 * <p>
4425 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4426 * applies to them.
4427 * <p>
4428 * This is only sent to registered receivers, not manifest receivers.
4429 */
4430 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4431 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4432 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4433
Felipe Lemeecfccea2016-01-25 11:48:04 -08004434 /** @hide */
4435 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004436 @IntDef(flag = false, value = {
4437 RESTRICT_BACKGROUND_STATUS_DISABLED,
4438 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4439 RESTRICT_BACKGROUND_STATUS_ENABLED,
4440 })
Felipe Leme1b103232016-01-22 09:44:57 -08004441 public @interface RestrictBackgroundStatus {
4442 }
4443
4444 private INetworkPolicyManager getNetworkPolicyManager() {
4445 synchronized (this) {
4446 if (mNPManager != null) {
4447 return mNPManager;
4448 }
4449 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4450 .getService(Context.NETWORK_POLICY_SERVICE));
4451 return mNPManager;
4452 }
4453 }
4454
4455 /**
4456 * Determines if the calling application is subject to metered network restrictions while
4457 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004458 *
4459 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4460 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4461 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004462 */
4463 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4464 try {
4465 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4466 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004467 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004468 }
4469 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004470
4471 /**
4472 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004473 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4474 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004475 *
4476 * @return Hash of network watchlist config file. Null if config does not exist.
4477 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004478 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004479 public byte[] getNetworkWatchlistConfigHash() {
4480 try {
4481 return mService.getNetworkWatchlistConfigHash();
4482 } catch (RemoteException e) {
4483 Log.e(TAG, "Unable to get watchlist config hash");
4484 throw e.rethrowFromSystemServer();
4485 }
4486 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004487
4488 /**
4489 * Returns the {@code uid} of the owner of a network connection.
4490 *
4491 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and
4492 * {@code IPPROTO_UDP} currently supported.
4493 * @param local The local {@link InetSocketAddress} of a connection.
4494 * @param remote The remote {@link InetSocketAddress} of a connection.
4495 *
4496 * @return {@code uid} if the connection is found and the app has permission to observe it
4497 * (e.g., if it is associated with the calling VPN app's tunnel) or
4498 * {@link android.os.Process#INVALID_UID} if the connection is not found.
Jeff Vander Stoepb58d3fe2019-02-27 13:31:22 -08004499 * Throws {@link SecurityException} if the caller is not the active VPN for the current user.
4500 * Throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004501 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004502 public int getConnectionOwnerUid(int protocol, @NonNull InetSocketAddress local,
4503 @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004504 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4505 try {
4506 return mService.getConnectionOwnerUid(connectionInfo);
4507 } catch (RemoteException e) {
4508 throw e.rethrowFromSystemServer();
4509 }
4510 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004511
4512 private void printStackTrace() {
4513 if (DEBUG) {
4514 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4515 final StringBuffer sb = new StringBuffer();
4516 for (int i = 3; i < callStack.length; i++) {
4517 final String stackTrace = callStack[i].toString();
4518 if (stackTrace == null || stackTrace.contains("android.os")) {
4519 break;
4520 }
4521 sb.append(" [").append(stackTrace).append("]");
4522 }
4523 Log.d(TAG, "StackLog:" + sb.toString());
4524 }
4525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526}