blob: 56bacf29ac73478f90a3bfaabb7fd1a867f76c44 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080016package android.net;
17
junyulai215b8772019-01-15 11:32:44 +080018import static android.net.IpSecManager.INVALID_RESOURCE_ID;
19
junyulai48eac1d42018-12-27 17:25:29 +080020import android.annotation.CallbackExecutor;
Felipe Leme1b103232016-01-22 09:44:57 -080021import android.annotation.IntDef;
Chalard Jean50bea3d2019-01-07 19:26:34 +090022import android.annotation.NonNull;
Robin Lee244ce8e2016-01-05 18:03:46 +000023import android.annotation.Nullable;
Jeff Sharkey30e06bb2017-04-24 11:18:03 -060024import android.annotation.RequiresPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.annotation.SdkConstant;
26import android.annotation.SdkConstant.SdkConstantType;
Udam Sainib7c24872016-01-04 12:16:14 -080027import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060028import android.annotation.SystemService;
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +090029import android.annotation.TestApi;
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010030import android.annotation.UnsupportedAppUsage;
Robert Greenwalt9258c642014-03-26 16:47:06 -070031import android.app.PendingIntent;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070032import android.content.Context;
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070033import android.content.Intent;
junyulai48eac1d42018-12-27 17:25:29 +080034import android.net.IpSecManager.UdpEncapsulationSocket;
35import android.net.SocketKeepalive.Callback;
Robert Greenwalt42acef32009-08-12 16:08:25 -070036import android.os.Binder;
Mathew Inwood55418ea2018-12-20 15:30:45 +000037import android.os.Build;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070038import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080039import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070040import android.os.Handler;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080041import android.os.IBinder;
42import android.os.INetworkActivityListener;
43import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070044import android.os.Looper;
45import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070046import android.os.Messenger;
junyulai0c666972019-03-04 22:45:36 +080047import android.os.ParcelFileDescriptor;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090048import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080050import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080051import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090052import android.os.ServiceSpecificException;
Jeff Sharkey961e3042011-08-29 16:02:57 -070053import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080054import android.telephony.SubscriptionManager;
Meng Wanga73bed82019-11-18 17:10:00 -080055import android.telephony.TelephonyManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080056import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070057import android.util.Log;
Erik Kline35bf06c2017-01-26 18:08:28 +090058import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
markchien26299ed2019-02-27 14:56:11 +080060import com.android.internal.annotations.GuardedBy;
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;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800805
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800806 /**
807 * Tests if a given integer represents a valid network type.
808 * @param networkType the type to be tested
809 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400810 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
811 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800812 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700813 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700814 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900815 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 }
817
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800818 /**
819 * Returns a non-localized string representing a given network type.
820 * ONLY used for debugging output.
821 * @param type the type needing naming
822 * @return a String for the given type, or a string version of the type ("87")
823 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900824 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800825 * {@hide}
826 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900827 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100828 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700829 public static String getNetworkTypeName(int type) {
830 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900831 case TYPE_NONE:
832 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700833 case TYPE_MOBILE:
834 return "MOBILE";
835 case TYPE_WIFI:
836 return "WIFI";
837 case TYPE_MOBILE_MMS:
838 return "MOBILE_MMS";
839 case TYPE_MOBILE_SUPL:
840 return "MOBILE_SUPL";
841 case TYPE_MOBILE_DUN:
842 return "MOBILE_DUN";
843 case TYPE_MOBILE_HIPRI:
844 return "MOBILE_HIPRI";
845 case TYPE_WIMAX:
846 return "WIMAX";
847 case TYPE_BLUETOOTH:
848 return "BLUETOOTH";
849 case TYPE_DUMMY:
850 return "DUMMY";
851 case TYPE_ETHERNET:
852 return "ETHERNET";
853 case TYPE_MOBILE_FOTA:
854 return "MOBILE_FOTA";
855 case TYPE_MOBILE_IMS:
856 return "MOBILE_IMS";
857 case TYPE_MOBILE_CBS:
858 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700859 case TYPE_WIFI_P2P:
860 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700861 case TYPE_MOBILE_IA:
862 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700863 case TYPE_MOBILE_EMERGENCY:
864 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500865 case TYPE_PROXY:
866 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900867 case TYPE_VPN:
868 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700869 default:
870 return Integer.toString(type);
871 }
872 }
873
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800874 /**
875 * Checks if a given type uses the cellular data connection.
876 * This should be replaced in the future by a network property.
877 * @param networkType the type to check
878 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900879 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800880 * {@hide}
881 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900882 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900883 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700884 public static boolean isNetworkTypeMobile(int networkType) {
885 switch (networkType) {
886 case TYPE_MOBILE:
887 case TYPE_MOBILE_MMS:
888 case TYPE_MOBILE_SUPL:
889 case TYPE_MOBILE_DUN:
890 case TYPE_MOBILE_HIPRI:
891 case TYPE_MOBILE_FOTA:
892 case TYPE_MOBILE_IMS:
893 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700894 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700895 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700896 return true;
897 default:
898 return false;
899 }
900 }
901
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800902 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700903 * Checks if the given network type is backed by a Wi-Fi radio.
904 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900905 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700906 * @hide
907 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900908 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700909 public static boolean isNetworkTypeWifi(int networkType) {
910 switch (networkType) {
911 case TYPE_WIFI:
912 case TYPE_WIFI_P2P:
913 return true;
914 default:
915 return false;
916 }
917 }
918
919 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800920 * Specifies the preferred network type. When the device has more
921 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800922 *
923 * @param preference the network type to prefer over all others. It is
924 * unspecified what happens to the old preferred network in the
925 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700926 * @deprecated Functionality has been removed as it no longer makes sense,
927 * with many more than two networks - we'd need an array to express
928 * preference. Instead we use dynamic network properties of
929 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800930 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700931 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
934
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800935 /**
936 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800937 *
938 * @return an integer representing the preferred network type
939 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700940 * @deprecated Functionality has been removed as it no longer makes sense,
941 * with many more than two networks - we'd need an array to express
942 * preference. Instead we use dynamic network properties of
943 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800944 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700945 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600946 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700948 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 }
950
Scott Main671644c2011-10-06 19:02:28 -0700951 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800952 * Returns details about the currently active default data network. When
953 * connected, this network is the default route for outgoing connections.
954 * You should always check {@link NetworkInfo#isConnected()} before initiating
955 * network traffic. This may return {@code null} when there is no default
956 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900957 * Note that if the default network is a VPN, this method will return the
958 * NetworkInfo for one of its underlying networks instead, or null if the
959 * VPN agent did not specify any. Apps interested in learning about VPNs
960 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800961 *
962 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500963 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800964 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700965 */
junyulai3822c8a2018-12-13 12:47:51 +0800966 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600967 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900968 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 public NetworkInfo getActiveNetworkInfo() {
970 try {
971 return mService.getActiveNetworkInfo();
972 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700973 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 }
975 }
976
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800977 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500978 * Returns a {@link Network} object corresponding to the currently active
979 * default data network. In the event that the current active default data
980 * network disconnects, the returned {@code Network} object will no longer
981 * be usable. This will return {@code null} when there is no default
982 * network.
983 *
984 * @return a {@link Network} object for the current default network or
985 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500986 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600987 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900988 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -0500989 public Network getActiveNetwork() {
990 try {
991 return mService.getActiveNetwork();
992 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700993 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500994 }
995 }
996
997 /**
Robin Leed2baf792016-03-24 12:07:00 +0000998 * Returns a {@link Network} object corresponding to the currently active
999 * default data network for a specific UID. In the event that the default data
1000 * network disconnects, the returned {@code Network} object will no longer
1001 * be usable. This will return {@code null} when there is no default
1002 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +00001003 *
1004 * @return a {@link Network} object for the current default network for the
1005 * given UID or {@code null} if no default network is currently active
1006 *
1007 * @hide
1008 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001009 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001010 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +00001011 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001012 return getActiveNetworkForUid(uid, false);
1013 }
1014
1015 /** {@hide} */
1016 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001017 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001018 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001019 } catch (RemoteException e) {
1020 throw e.rethrowFromSystemServer();
1021 }
1022 }
1023
1024 /**
Charles He36738632017-05-15 17:07:18 +01001025 * Checks if a VPN app supports always-on mode.
1026 *
1027 * In order to support the always-on feature, an app has to
1028 * <ul>
1029 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +01001030 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
1031 * meta-data field.
Charles He36738632017-05-15 17:07:18 +01001032 * </ul>
1033 *
1034 * @param userId The identifier of the user for whom the VPN app is installed.
1035 * @param vpnPackage The canonical package name of the VPN app.
1036 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
1037 * @hide
1038 */
1039 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1040 try {
1041 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1042 } catch (RemoteException e) {
1043 throw e.rethrowFromSystemServer();
1044 }
1045 }
1046
1047 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001048 * Configures an always-on VPN connection through a specific application.
1049 * This connection is automatically granted and persisted after a reboot.
1050 *
1051 * <p>The designated package should declare a {@link VpnService} in its
1052 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1053 * otherwise the call will fail.
1054 *
1055 * @param userId The identifier of the user to set an always-on VPN for.
1056 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1057 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001058 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1059 * {@code false} otherwise.
Pavel Grafova462bcb2019-01-25 08:50:06 +00001060 * @param lockdownWhitelist The list of packages that are allowed to access network directly
1061 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
1062 * this method must be called when a package that should be whitelisted is installed or
1063 * uninstalled.
Robin Lee244ce8e2016-01-05 18:03:46 +00001064 * @return {@code true} if the package is set as always-on VPN controller;
1065 * {@code false} otherwise.
1066 * @hide
1067 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001068 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leedc679712016-05-03 13:23:03 +01001069 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001070 boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001071 try {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001072 return mService.setAlwaysOnVpnPackage(
1073 userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
Robin Lee244ce8e2016-01-05 18:03:46 +00001074 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001075 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001076 }
1077 }
1078
Pavel Grafova462bcb2019-01-25 08:50:06 +00001079 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001080 * Returns the package name of the currently set always-on VPN application.
1081 * If there is no always-on VPN set, or the VPN is provided by the system instead
1082 * of by an app, {@code null} will be returned.
1083 *
1084 * @return Package name of VPN controller responsible for always-on VPN,
1085 * or {@code null} if none is set.
1086 * @hide
1087 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001088 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee244ce8e2016-01-05 18:03:46 +00001089 public String getAlwaysOnVpnPackageForUser(int userId) {
1090 try {
1091 return mService.getAlwaysOnVpnPackage(userId);
1092 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001093 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001094 }
1095 }
1096
1097 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001098 * @return whether always-on VPN is in lockdown mode.
1099 *
1100 * @hide
1101 **/
1102 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1103 public boolean isVpnLockdownEnabled(int userId) {
1104 try {
1105 return mService.isVpnLockdownEnabled(userId);
1106 } catch (RemoteException e) {
1107 throw e.rethrowFromSystemServer();
1108 }
1109
1110 }
1111
1112 /**
1113 * @return the list of packages that are allowed to access network when always-on VPN is in
1114 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1115 *
1116 * @hide
1117 **/
1118 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1119 public List<String> getVpnLockdownWhitelist(int userId) {
1120 try {
1121 return mService.getVpnLockdownWhitelist(userId);
1122 } catch (RemoteException e) {
1123 throw e.rethrowFromSystemServer();
1124 }
1125 }
1126
1127 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001128 * Returns details about the currently active default data network
1129 * for a given uid. This is for internal use only to avoid spying
1130 * other apps.
1131 *
1132 * @return a {@link NetworkInfo} object for the current default network
1133 * for the given uid or {@code null} if no default network is
1134 * available for the specified uid.
1135 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001136 * {@hide}
1137 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001138 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001139 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001140 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001141 return getActiveNetworkInfoForUid(uid, false);
1142 }
1143
1144 /** {@hide} */
1145 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001146 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001147 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001149 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001150 }
1151 }
1152
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001153 /**
1154 * Returns connection status information about a particular
1155 * network type.
1156 *
1157 * @param networkType integer specifying which networkType in
1158 * which you're interested.
1159 * @return a {@link NetworkInfo} object for the requested
1160 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001161 * supported by the device. If {@code networkType} is
1162 * TYPE_VPN and a VPN is active for the calling app,
1163 * then this method will try to return one of the
1164 * underlying networks for the VPN or null if the
1165 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001166 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001167 * @deprecated This method does not support multiple connected networks
1168 * of the same type. Use {@link #getAllNetworks} and
1169 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001170 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001171 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001172 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001173 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 public NetworkInfo getNetworkInfo(int networkType) {
1175 try {
1176 return mService.getNetworkInfo(networkType);
1177 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001178 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 }
1180 }
1181
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001182 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001183 * Returns connection status information about a particular
1184 * Network.
1185 *
1186 * @param network {@link Network} specifying which network
1187 * in which you're interested.
1188 * @return a {@link NetworkInfo} object for the requested
1189 * network or {@code null} if the {@code Network}
1190 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001191 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001192 */
junyulai3822c8a2018-12-13 12:47:51 +08001193 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001194 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001195 @Nullable
1196 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001197 return getNetworkInfoForUid(network, Process.myUid(), false);
1198 }
1199
1200 /** {@hide} */
1201 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001202 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001203 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001204 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001205 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001206 }
1207 }
1208
1209 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001210 * Returns connection status information about all network
1211 * types supported by the device.
1212 *
1213 * @return an array of {@link NetworkInfo} objects. Check each
1214 * {@link NetworkInfo#getType} for which type each applies.
1215 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001216 * @deprecated This method does not support multiple connected networks
1217 * of the same type. Use {@link #getAllNetworks} and
1218 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001219 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001220 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001221 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001222 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 public NetworkInfo[] getAllNetworkInfo() {
1224 try {
1225 return mService.getAllNetworkInfo();
1226 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001227 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 }
1229 }
1230
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001231 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001232 * Returns the {@link Network} object currently serving a given type, or
1233 * null if the given type is not connected.
1234 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001235 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001236 * @deprecated This method does not support multiple connected networks
1237 * of the same type. Use {@link #getAllNetworks} and
1238 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001239 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001240 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001241 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001242 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001243 public Network getNetworkForType(int networkType) {
1244 try {
1245 return mService.getNetworkForType(networkType);
1246 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001247 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001248 }
1249 }
1250
1251 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001252 * Returns an array of all {@link Network} currently tracked by the
1253 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001254 *
1255 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001256 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001257 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001258 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001259 public Network[] getAllNetworks() {
1260 try {
1261 return mService.getAllNetworks();
1262 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001263 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001264 }
1265 }
1266
1267 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001268 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001269 * the Networks that applications run by the given user will use by default.
1270 * @hide
1271 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001272 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001273 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1274 try {
1275 return mService.getDefaultNetworkCapabilitiesForUser(userId);
1276 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001277 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001278 }
1279 }
1280
1281 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001282 * Returns the IP information for the current default network.
1283 *
1284 * @return a {@link LinkProperties} object describing the IP info
1285 * for the current default network, or {@code null} if there
1286 * is no current default network.
1287 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001288 * {@hide}
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001289 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1290 * value of {@link #getActiveNetwork()} instead. In particular,
1291 * this method will return non-null LinkProperties even if the
1292 * app is blocked by policy from using this network.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001293 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001294 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001295 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001296 public LinkProperties getActiveLinkProperties() {
1297 try {
1298 return mService.getActiveLinkProperties();
1299 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001300 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001301 }
1302 }
1303
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001304 /**
1305 * Returns the IP information for a given network type.
1306 *
1307 * @param networkType the network type of interest.
1308 * @return a {@link LinkProperties} object describing the IP info
1309 * for the given networkType, or {@code null} if there is
1310 * no current default network.
1311 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001312 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001313 * @deprecated This method does not support multiple connected networks
1314 * of the same type. Use {@link #getAllNetworks},
1315 * {@link #getNetworkInfo(android.net.Network)}, and
1316 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001317 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001318 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001319 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09001320 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001321 public LinkProperties getLinkProperties(int networkType) {
1322 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001323 return mService.getLinkPropertiesForType(networkType);
1324 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001325 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001326 }
1327 }
1328
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001329 /**
1330 * Get the {@link LinkProperties} for the given {@link Network}. This
1331 * will return {@code null} if the network is unknown.
1332 *
1333 * @param network The {@link Network} object identifying the network in question.
1334 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001335 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001336 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001337 @Nullable
1338 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001339 try {
1340 return mService.getLinkProperties(network);
1341 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001342 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001343 }
1344 }
1345
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001346 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001347 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001348 * will return {@code null} if the network is unknown.
1349 *
1350 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001351 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001352 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001353 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001354 @Nullable
1355 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001356 try {
1357 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001358 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001359 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001360 }
1361 }
1362
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001363 /**
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001364 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainib7c24872016-01-04 12:16:14 -08001365 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1366 * portal is present.
1367 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1368 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1369 *
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001370 * The system network validation may be using different strategies to detect captive portals,
1371 * so this method does not necessarily return a URL used by the system. It only returns a URL
1372 * that may be relevant for other components trying to detect captive portals.
Udam Sainib7c24872016-01-04 12:16:14 -08001373 * @hide
1374 */
1375 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07001376 @RequiresPermission(android.Manifest.permission.LOCAL_MAC_ADDRESS)
Udam Sainib7c24872016-01-04 12:16:14 -08001377 public String getCaptivePortalServerUrl() {
1378 try {
1379 return mService.getCaptivePortalServerUrl();
1380 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001381 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001382 }
1383 }
1384
1385 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 * Tells the underlying networking system that the caller wants to
1387 * begin using the named feature. The interpretation of {@code feature}
1388 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001389 *
1390 * <p>This method requires the caller to hold either the
1391 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1392 * or the ability to modify system settings as determined by
1393 * {@link android.provider.Settings.System#canWrite}.</p>
1394 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 * @param networkType specifies which network the request pertains to
1396 * @param feature the name of the feature to be used
1397 * @return an integer value representing the outcome of the request.
1398 * The interpretation of this value is specific to each networking
1399 * implementation+feature combination, except that the value {@code -1}
1400 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001401 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001402 * @deprecated Deprecated in favor of the cleaner
1403 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001404 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001405 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001406 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001408 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001410 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001411 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1412 if (netCap == null) {
1413 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1414 feature);
Chalard Jeanc06d7882019-11-21 14:48:00 +09001415 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001416 }
1417
1418 NetworkRequest request = null;
1419 synchronized (sLegacyRequests) {
1420 LegacyRequest l = sLegacyRequests.get(netCap);
1421 if (l != null) {
1422 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1423 renewRequestLocked(l);
1424 if (l.currentNetwork != null) {
Chalard Jeanc06d7882019-11-21 14:48:00 +09001425 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001426 } else {
Chalard Jeanc06d7882019-11-21 14:48:00 +09001427 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001428 }
1429 }
1430
1431 request = requestNetworkForFeatureLocked(netCap);
1432 }
1433 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001434 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanc06d7882019-11-21 14:48:00 +09001435 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001436 } else {
1437 Log.d(TAG, " request Failed");
Chalard Jeanc06d7882019-11-21 14:48:00 +09001438 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440 }
1441
1442 /**
1443 * Tells the underlying networking system that the caller is finished
1444 * using the named feature. The interpretation of {@code feature}
1445 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001446 *
1447 * <p>This method requires the caller to hold either the
1448 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1449 * or the ability to modify system settings as determined by
1450 * {@link android.provider.Settings.System#canWrite}.</p>
1451 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 * @param networkType specifies which network the request pertains to
1453 * @param feature the name of the feature that is no longer needed
1454 * @return an integer value representing the outcome of the request.
1455 * The interpretation of this value is specific to each networking
1456 * implementation+feature combination, except that the value {@code -1}
1457 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001458 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001459 * @deprecated Deprecated in favor of the cleaner
1460 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001461 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001462 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001463 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001465 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001467 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001468 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1469 if (netCap == null) {
1470 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1471 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 return -1;
1473 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001474
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001475 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001476 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001477 }
1478 return 1;
1479 }
1480
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001481 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001482 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1483 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001484 switch (feature) {
1485 case "enableCBS":
1486 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1487 case "enableDUN":
1488 case "enableDUNAlways":
1489 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1490 case "enableFOTA":
1491 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1492 case "enableHIPRI":
1493 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1494 case "enableIMS":
1495 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1496 case "enableMMS":
1497 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1498 case "enableSUPL":
1499 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1500 default:
1501 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001502 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001503 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1504 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001505 }
1506 return null;
1507 }
1508
Robert Greenwalt06314e42014-10-29 14:04:06 -07001509 /**
1510 * Guess what the network request was trying to say so that the resulting
1511 * network is accessible via the legacy (deprecated) API such as
1512 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001513 *
1514 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001515 * capability but ignore things such as networkSpecifier.
1516 * If the request has more than one transport or capability it doesn't
1517 * match the old legacy requests (they selected only single transport/capability)
1518 * so this function cannot map the request to a single legacy type and
1519 * the resulting network will not be available to the legacy APIs.
1520 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001521 * This code is only called from the requestNetwork API (L and above).
1522 *
1523 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1524 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1525 * do this for SUPL requests, which are the only ones that we know need it. If
1526 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1527 * compatibility we can send them:
1528 *
1529 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1530 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1531 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001532 * TODO - This should be removed when the legacy APIs are removed.
1533 */
Ye Wenb87875e2014-07-21 14:19:01 -07001534 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1535 if (netCap == null) {
1536 return TYPE_NONE;
1537 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001538
Ye Wenb87875e2014-07-21 14:19:01 -07001539 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1540 return TYPE_NONE;
1541 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001542
Lifu Tang30f95a72016-01-07 23:20:38 -08001543 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001544 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1545 // NOTE: if this causes app breakage, we should not just comment out this early return;
1546 // instead, we should make this early return conditional on the requesting app's target
1547 // SDK version, as described in the comment above.
1548 return TYPE_NONE;
1549 }
1550
Robert Greenwalt06314e42014-10-29 14:04:06 -07001551 String type = null;
1552 int result = TYPE_NONE;
1553
Ye Wenb87875e2014-07-21 14:19:01 -07001554 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001555 type = "enableCBS";
1556 result = TYPE_MOBILE_CBS;
1557 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1558 type = "enableIMS";
1559 result = TYPE_MOBILE_IMS;
1560 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1561 type = "enableFOTA";
1562 result = TYPE_MOBILE_FOTA;
1563 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1564 type = "enableDUN";
1565 result = TYPE_MOBILE_DUN;
1566 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001567 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001568 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001569 // back out this hack for mms as they no longer need this and it's causing
1570 // device slowdowns - b/23350688 (note, supl still needs this)
1571 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1572 // type = "enableMMS";
1573 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001574 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1575 type = "enableHIPRI";
1576 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001577 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001578 if (type != null) {
1579 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1580 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1581 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001582 }
1583 }
1584 return TYPE_NONE;
1585 }
1586
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001587 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001588 if (netCap == null) return TYPE_NONE;
1589 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1590 return TYPE_MOBILE_CBS;
1591 }
1592 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1593 return TYPE_MOBILE_IMS;
1594 }
1595 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1596 return TYPE_MOBILE_FOTA;
1597 }
1598 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1599 return TYPE_MOBILE_DUN;
1600 }
1601 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1602 return TYPE_MOBILE_SUPL;
1603 }
1604 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1605 return TYPE_MOBILE_MMS;
1606 }
1607 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1608 return TYPE_MOBILE_HIPRI;
1609 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001610 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1611 return TYPE_WIFI_P2P;
1612 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001613 return TYPE_NONE;
1614 }
1615
1616 private static class LegacyRequest {
1617 NetworkCapabilities networkCapabilities;
1618 NetworkRequest networkRequest;
1619 int expireSequenceNumber;
1620 Network currentNetwork;
1621 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001622
1623 private void clearDnsBinding() {
1624 if (currentNetwork != null) {
1625 currentNetwork = null;
1626 setProcessDefaultNetworkForHostResolution(null);
1627 }
1628 }
1629
Robert Greenwalt6078b502014-06-11 16:05:07 -07001630 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001631 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001632 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001633 currentNetwork = network;
1634 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001635 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001636 }
1637 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001638 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001639 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001640 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1641 }
1642 };
1643 }
1644
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001645 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001646 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1647 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001648
1649 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1650 synchronized (sLegacyRequests) {
1651 LegacyRequest l = sLegacyRequests.get(netCap);
1652 if (l != null) return l.networkRequest;
1653 }
1654 return null;
1655 }
1656
1657 private void renewRequestLocked(LegacyRequest l) {
1658 l.expireSequenceNumber++;
1659 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1660 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1661 }
1662
1663 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1664 int ourSeqNum = -1;
1665 synchronized (sLegacyRequests) {
1666 LegacyRequest l = sLegacyRequests.get(netCap);
1667 if (l == null) return;
1668 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001669 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001670 }
1671 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1672 }
1673
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001674 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001675 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1676 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001677 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001678 try {
1679 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001680 } catch (RemoteException e) {
1681 throw e.rethrowFromSystemServer();
1682 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001683 LegacyRequest l = new LegacyRequest();
1684 l.networkCapabilities = netCap;
1685 l.delay = delay;
1686 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001687 l.networkRequest = sendRequestForNetwork(
1688 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001689 if (l.networkRequest == null) return null;
1690 sLegacyRequests.put(netCap, l);
1691 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1692 return l.networkRequest;
1693 }
1694
1695 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1696 if (delay >= 0) {
1697 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001698 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001699 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1700 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001701 }
1702 }
1703
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001704 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001705 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1706 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001707 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001708 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001709 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001710 if (l == null) return false;
1711 unregisterNetworkCallback(l.networkCallback);
1712 l.clearDnsBinding();
1713 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
1715
Erik Kline35bf06c2017-01-26 18:08:28 +09001716 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1717 static {
1718 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1719 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1720 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1721 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1722 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1723 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1724 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1725 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1726 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1727 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1728 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1729 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1730 }
1731
1732 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1733 static {
1734 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1735 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1736 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1737 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1738 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1739 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1740 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1741 }
1742
1743 /**
1744 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1745 * instance suitable for registering a request or callback. Throws an
1746 * IllegalArgumentException if no mapping from the legacy type to
1747 * NetworkCapabilities is known.
1748 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001749 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1750 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001751 * @hide
1752 */
1753 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1754 final NetworkCapabilities nc = new NetworkCapabilities();
1755
1756 // Map from type to transports.
1757 final int NOT_FOUND = -1;
1758 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001759 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001760 nc.addTransportType(transport);
1761
1762 // Map from type to capabilities.
1763 nc.addCapability(sLegacyTypeToCapability.get(
1764 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1765 nc.maybeMarkCapabilitiesRestricted();
1766 return nc;
1767 }
1768
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001769 /** @hide */
1770 public static class PacketKeepaliveCallback {
Artur Satayevfc46be72019-11-04 17:50:59 +00001771 @UnsupportedAppUsage
1772 public PacketKeepaliveCallback() {
1773 }
1774
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001775 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001776 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001777 public void onStarted() {}
1778 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001779 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001780 public void onStopped() {}
1781 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001782 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001783 public void onError(int error) {}
1784 }
1785
1786 /**
1787 * Allows applications to request that the system periodically send specific packets on their
1788 * behalf, using hardware offload to save battery power.
1789 *
1790 * To request that the system send keepalives, call one of the methods that return a
1791 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1792 * passing in a non-null callback. If the callback is successfully started, the callback's
1793 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1794 * specifying one of the {@code ERROR_*} constants in this class.
1795 *
Chalard Jean4d660112018-06-04 16:52:49 +09001796 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1797 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1798 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001799 *
junyulai48eac1d42018-12-27 17:25:29 +08001800 * @deprecated Use {@link SocketKeepalive} instead.
1801 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001802 * @hide
1803 */
1804 public class PacketKeepalive {
1805
1806 private static final String TAG = "PacketKeepalive";
1807
1808 /** @hide */
1809 public static final int SUCCESS = 0;
1810
1811 /** @hide */
1812 public static final int NO_KEEPALIVE = -1;
1813
1814 /** @hide */
1815 public static final int BINDER_DIED = -10;
1816
1817 /** The specified {@code Network} is not connected. */
1818 public static final int ERROR_INVALID_NETWORK = -20;
1819 /** The specified IP addresses are invalid. For example, the specified source IP address is
1820 * not configured on the specified {@code Network}. */
1821 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1822 /** The requested port is invalid. */
1823 public static final int ERROR_INVALID_PORT = -22;
1824 /** The packet length is invalid (e.g., too long). */
1825 public static final int ERROR_INVALID_LENGTH = -23;
1826 /** The packet transmission interval is invalid (e.g., too short). */
1827 public static final int ERROR_INVALID_INTERVAL = -24;
1828
1829 /** The hardware does not support this request. */
1830 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001831 /** The hardware returned an error. */
1832 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001833
Nathan Harold63dd8132018-02-14 13:09:45 -08001834 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001835 public static final int NATT_PORT = 4500;
1836
Nathan Harold63dd8132018-02-14 13:09:45 -08001837 /** The minimum interval in seconds between keepalive packet transmissions */
1838 public static final int MIN_INTERVAL = 10;
1839
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001840 private final Network mNetwork;
junyulai7c469172019-01-16 20:23:34 +08001841 private final ISocketKeepaliveCallback mCallback;
1842 private final ExecutorService mExecutor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001843
1844 private volatile Integer mSlot;
1845
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001846 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001847 public void stop() {
1848 try {
junyulai7c469172019-01-16 20:23:34 +08001849 mExecutor.execute(() -> {
1850 try {
1851 if (mSlot != null) {
1852 mService.stopKeepalive(mNetwork, mSlot);
1853 }
1854 } catch (RemoteException e) {
1855 Log.e(TAG, "Error stopping packet keepalive: ", e);
1856 throw e.rethrowFromSystemServer();
1857 }
1858 });
1859 } catch (RejectedExecutionException e) {
1860 // The internal executor has already stopped due to previous event.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001861 }
1862 }
1863
1864 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001865 Preconditions.checkNotNull(network, "network cannot be null");
1866 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001867 mNetwork = network;
junyulai7c469172019-01-16 20:23:34 +08001868 mExecutor = Executors.newSingleThreadExecutor();
1869 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001870 @Override
junyulai7c469172019-01-16 20:23:34 +08001871 public void onStarted(int slot) {
1872 Binder.withCleanCallingIdentity(() ->
1873 mExecutor.execute(() -> {
1874 mSlot = slot;
1875 callback.onStarted();
1876 }));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001877 }
junyulai7c469172019-01-16 20:23:34 +08001878
1879 @Override
1880 public void onStopped() {
1881 Binder.withCleanCallingIdentity(() ->
1882 mExecutor.execute(() -> {
1883 mSlot = null;
1884 callback.onStopped();
1885 }));
1886 mExecutor.shutdown();
1887 }
1888
1889 @Override
1890 public void onError(int error) {
1891 Binder.withCleanCallingIdentity(() ->
1892 mExecutor.execute(() -> {
1893 mSlot = null;
1894 callback.onError(error);
1895 }));
1896 mExecutor.shutdown();
1897 }
1898
1899 @Override
1900 public void onDataReceived() {
1901 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1902 // this callback when data is received.
1903 }
1904 };
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001905 }
1906 }
1907
1908 /**
1909 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1910 *
junyulai48eac1d42018-12-27 17:25:29 +08001911 * @deprecated Use {@link #createSocketKeepalive} instead.
1912 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001913 * @hide
1914 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001915 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001916 public PacketKeepalive startNattKeepalive(
1917 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1918 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1919 final PacketKeepalive k = new PacketKeepalive(network, callback);
1920 try {
junyulai7c469172019-01-16 20:23:34 +08001921 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001922 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1923 } catch (RemoteException e) {
1924 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai7c469172019-01-16 20:23:34 +08001925 throw e.rethrowFromSystemServer();
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001926 }
1927 return k;
1928 }
1929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 /**
junyulai48eac1d42018-12-27 17:25:29 +08001931 * Request that keepalives be started on a IPsec NAT-T socket.
1932 *
1933 * @param network The {@link Network} the socket is on.
1934 * @param socket The socket that needs to be kept alive.
1935 * @param source The source address of the {@link UdpEncapsulationSocket}.
1936 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1937 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1938 * must run callback sequentially, otherwise the order of callbacks cannot be
1939 * guaranteed.
1940 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1941 * changes. Must be extended by applications that use this API.
1942 *
junyulai352dc2f2019-01-08 20:04:33 +08001943 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1944 * given socket.
junyulai48eac1d42018-12-27 17:25:29 +08001945 **/
junyulai0c666972019-03-04 22:45:36 +08001946 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai48eac1d42018-12-27 17:25:29 +08001947 @NonNull UdpEncapsulationSocket socket,
1948 @NonNull InetAddress source,
1949 @NonNull InetAddress destination,
1950 @NonNull @CallbackExecutor Executor executor,
1951 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001952 ParcelFileDescriptor dup;
1953 try {
junyulai15178152019-03-27 11:00:37 +08001954 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1955 // which cannot be obtained by the app process.
junyulai0c666972019-03-04 22:45:36 +08001956 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1957 } catch (IOException ignored) {
1958 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1959 // ERROR_INVALID_SOCKET.
1960 dup = new ParcelFileDescriptor(new FileDescriptor());
1961 }
1962 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1963 destination, executor, callback);
junyulai215b8772019-01-15 11:32:44 +08001964 }
1965
1966 /**
1967 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1968 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1969 *
1970 * @param network The {@link Network} the socket is on.
junyulai0c666972019-03-04 22:45:36 +08001971 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1972 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1973 * from that port.
junyulai215b8772019-01-15 11:32:44 +08001974 * @param source The source address of the {@link UdpEncapsulationSocket}.
1975 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1976 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1977 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1978 * must run callback sequentially, otherwise the order of callbacks cannot be
1979 * guaranteed.
1980 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1981 * changes. Must be extended by applications that use this API.
1982 *
junyulai352dc2f2019-01-08 20:04:33 +08001983 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1984 * given socket.
junyulai215b8772019-01-15 11:32:44 +08001985 * @hide
1986 */
1987 @SystemApi
1988 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08001989 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1990 @NonNull ParcelFileDescriptor pfd,
junyulai215b8772019-01-15 11:32:44 +08001991 @NonNull InetAddress source,
1992 @NonNull InetAddress destination,
1993 @NonNull @CallbackExecutor Executor executor,
1994 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001995 ParcelFileDescriptor dup;
1996 try {
junyulai15178152019-03-27 11:00:37 +08001997 // TODO: Consider remove unnecessary dup.
junyulai0c666972019-03-04 22:45:36 +08001998 dup = pfd.dup();
1999 } catch (IOException ignored) {
2000 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2001 // ERROR_INVALID_SOCKET.
2002 dup = new ParcelFileDescriptor(new FileDescriptor());
2003 }
2004 return new NattSocketKeepalive(mService, network, dup,
2005 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08002006 }
2007
2008 /**
junyulai352dc2f2019-01-08 20:04:33 +08002009 * Request that keepalives be started on a TCP socket.
2010 * The socket must be established.
2011 *
2012 * @param network The {@link Network} the socket is on.
2013 * @param socket The socket that needs to be kept alive.
2014 * @param executor The executor on which callback will be invoked. This implementation assumes
2015 * the provided {@link Executor} runs the callbacks in sequence with no
2016 * concurrency. Failing this, no guarantee of correctness can be made. It is
2017 * the responsibility of the caller to ensure the executor provides this
2018 * guarantee. A simple way of creating such an executor is with the standard
2019 * tool {@code Executors.newSingleThreadExecutor}.
2020 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2021 * changes. Must be extended by applications that use this API.
2022 *
2023 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2024 * given socket.
2025 * @hide
2026 */
2027 @SystemApi
2028 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08002029 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai352dc2f2019-01-08 20:04:33 +08002030 @NonNull Socket socket,
2031 @NonNull Executor executor,
2032 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08002033 ParcelFileDescriptor dup;
2034 try {
2035 dup = ParcelFileDescriptor.fromSocket(socket);
2036 } catch (UncheckedIOException ignored) {
2037 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2038 // ERROR_INVALID_SOCKET.
2039 dup = new ParcelFileDescriptor(new FileDescriptor());
2040 }
2041 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai352dc2f2019-01-08 20:04:33 +08002042 }
2043
2044 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 * Ensure that a network route exists to deliver traffic to the specified
2046 * host via the specified network interface. An attempt to add a route that
2047 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002048 *
2049 * <p>This method requires the caller to hold either the
2050 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2051 * or the ability to modify system settings as determined by
2052 * {@link android.provider.Settings.System#canWrite}.</p>
2053 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 * @param networkType the type of the network over which traffic to the specified
2055 * host is to be routed
2056 * @param hostAddress the IP address of the host to which the route is desired
2057 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002058 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002059 * @deprecated Deprecated in favor of the
2060 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2061 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07002062 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002063 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09002064 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002066 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002068 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002069 }
2070
2071 /**
2072 * Ensure that a network route exists to deliver traffic to the specified
2073 * host via the specified network interface. An attempt to add a route that
2074 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002075 *
2076 * <p>This method requires the caller to hold either the
2077 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2078 * or the ability to modify system settings as determined by
2079 * {@link android.provider.Settings.System#canWrite}.</p>
2080 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002081 * @param networkType the type of the network over which traffic to the specified
2082 * host is to be routed
2083 * @param hostAddress the IP address of the host to which the route is desired
2084 * @return {@code true} on success, {@code false} on failure
2085 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002086 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002087 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002088 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002089 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002090 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002091 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002092 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002094 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002096 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
2098 }
2099
2100 /**
2101 * Returns the value of the setting for background data usage. If false,
2102 * applications should not use the network if the application is not in the
2103 * foreground. Developers should respect this setting, and check the value
2104 * of this before performing any background data operations.
2105 * <p>
2106 * All applications that have background services that use the network
2107 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002108 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002109 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002110 * background data depends on several combined factors, and this method will
2111 * always return {@code true}. Instead, when background data is unavailable,
2112 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002113 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 * @return Whether background data usage is allowed.
2115 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002116 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002118 // assume that background data is allowed; final authority is
2119 // NetworkInfo which may be blocked.
2120 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 }
2122
2123 /**
2124 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002125 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 * @param allowBackgroundData Whether an application should use data while
2127 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002128 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2130 * @see #getBackgroundDataSetting()
2131 * @hide
2132 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002133 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002134 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002136 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002138
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002139 /** {@hide} */
2140 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002141 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002142 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2143 try {
2144 return mService.getActiveNetworkQuotaInfo();
2145 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002146 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002147 }
2148 }
2149
2150 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002151 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002152 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002153 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002154 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002155 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002156 public boolean getMobileDataEnabled() {
Meng Wanga73bed82019-11-18 17:10:00 -08002157 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2158 if (tm != null) {
2159 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2160 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2161 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2162 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2163 + " retVal=" + retVal);
2164 return retVal;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002165 }
Wink Saville36ffb042014-12-05 11:10:30 -08002166 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002167 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002168 }
2169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002171 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002172 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002173 */
2174 public interface OnNetworkActiveListener {
2175 /**
2176 * Called on the main thread of the process to report that the current data network
2177 * has become active, and it is now a good time to perform any pending network
2178 * operations. Note that this listener only tells you when the network becomes
2179 * active; if at any other time you want to know whether it is active (and thus okay
2180 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002181 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002182 */
Chalard Jean4d660112018-06-04 16:52:49 +09002183 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002184 }
2185
2186 private INetworkManagementService getNetworkManagementService() {
2187 synchronized (this) {
2188 if (mNMService != null) {
2189 return mNMService;
2190 }
2191 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2192 mNMService = INetworkManagementService.Stub.asInterface(b);
2193 return mNMService;
2194 }
2195 }
2196
2197 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002198 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002199
2200 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002201 * Start listening to reports when the system's default data network is active, meaning it is
2202 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2203 * to determine the current state of the system's default network after registering the
2204 * listener.
2205 * <p>
2206 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002207 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002208 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002209 *
2210 * @param l The listener to be told when the network is active.
2211 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002212 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002213 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2214 @Override
2215 public void onNetworkActive() throws RemoteException {
2216 l.onNetworkActive();
2217 }
2218 };
2219
2220 try {
2221 getNetworkManagementService().registerNetworkActivityListener(rl);
2222 mNetworkActivityListeners.put(l, rl);
2223 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002224 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002225 }
2226 }
2227
2228 /**
2229 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002230 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002231 *
2232 * @param l Previously registered listener.
2233 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002234 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002235 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002236 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002237 try {
2238 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2239 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002240 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002241 }
2242 }
2243
2244 /**
2245 * Return whether the data network is currently active. An active network means that
2246 * it is currently in a high power state for performing data transmission. On some
2247 * types of networks, it may be expensive to move and stay in such a state, so it is
2248 * more power efficient to batch network traffic together when the radio is already in
2249 * this state. This method tells you whether right now is currently a good time to
2250 * initiate network traffic, as the network is already active.
2251 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002252 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002253 try {
2254 return getNetworkManagementService().isNetworkActive();
2255 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002256 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002257 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002258 }
2259
2260 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 * {@hide}
2262 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002263 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002264 mContext = Preconditions.checkNotNull(context, "missing context");
2265 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05002266 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002268
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002269 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002270 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002271 public static ConnectivityManager from(Context context) {
2272 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2273 }
2274
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002275 /** @hide */
2276 public NetworkRequest getDefaultRequest() {
2277 try {
2278 // This is not racy as the default request is final in ConnectivityService.
2279 return mService.getDefaultRequest();
2280 } catch (RemoteException e) {
2281 throw e.rethrowFromSystemServer();
2282 }
2283 }
2284
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002285 /* TODO: These permissions checks don't belong in client-side code. Move them to
2286 * services.jar, possibly in com.android.server.net. */
2287
2288 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002289 public static final void enforceChangePermission(Context context) {
2290 int uid = Binder.getCallingUid();
2291 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2292 .getPackageNameForUid(context, uid), true /* throwException */);
2293 }
2294
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002295 /** {@hide} */
2296 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002297 Preconditions.checkNotNull(context, "Context cannot be null");
2298 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002299
Robert Greenwaltedb47662014-09-16 17:54:19 -07002300 if (context.getResources().getStringArray(
2301 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2302 // Have a provisioning app - must only let system apps (which check this app)
2303 // turn on tethering
2304 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002305 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002306 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002307 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002308 // If callingPkg's uid is not same as Binder.getCallingUid(),
2309 // AppOpsService throws SecurityException.
2310 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2311 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002312 }
2313 }
2314
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002315 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002316 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2317 * situations where a Context pointer is unavailable.
2318 * @hide
2319 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002320 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002321 static ConnectivityManager getInstanceOrNull() {
2322 return sInstance;
2323 }
2324
2325 /**
2326 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2327 * situations where a Context pointer is unavailable.
2328 * @hide
2329 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002330 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002331 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002332 private static ConnectivityManager getInstance() {
2333 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002334 throw new IllegalStateException("No ConnectivityManager yet constructed");
2335 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002336 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002337 }
2338
2339 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002340 * Get the set of tetherable, available interfaces. This list is limited by
2341 * device configuration and current interface existence.
2342 *
2343 * @return an array of 0 or more Strings of tetherable interface names.
2344 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002345 * {@hide}
2346 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002347 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002348 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002349 public String[] getTetherableIfaces() {
2350 try {
2351 return mService.getTetherableIfaces();
2352 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002353 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002354 }
2355 }
2356
2357 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002358 * Get the set of tethered interfaces.
2359 *
2360 * @return an array of 0 or more String of currently tethered interface names.
2361 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002362 * {@hide}
2363 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002364 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002365 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002366 public String[] getTetheredIfaces() {
2367 try {
2368 return mService.getTetheredIfaces();
2369 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002370 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002371 }
2372 }
2373
2374 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002375 * Get the set of interface names which attempted to tether but
2376 * failed. Re-attempting to tether may cause them to reset to the Tethered
2377 * state. Alternatively, causing the interface to be destroyed and recreated
2378 * may cause them to reset to the available state.
2379 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2380 * information on the cause of the errors.
2381 *
2382 * @return an array of 0 or more String indicating the interface names
2383 * which failed to tether.
2384 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002385 * {@hide}
2386 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002387 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002388 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002389 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002390 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08002391 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002392 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002393 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002394 }
2395 }
2396
2397 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002398 * Get the set of tethered dhcp ranges.
2399 *
2400 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
2401 * {@hide}
2402 */
2403 public String[] getTetheredDhcpRanges() {
2404 try {
2405 return mService.getTetheredDhcpRanges();
2406 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002407 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002408 }
2409 }
2410
2411 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002412 * Attempt to tether the named interface. This will setup a dhcp server
2413 * on the interface, forward and NAT IP packets and forward DNS requests
2414 * to the best active upstream network interface. Note that if no upstream
2415 * IP network interface is available, dhcp will still run and traffic will be
2416 * allowed between the tethered devices and this device, though upstream net
2417 * access will of course fail until an upstream network interface becomes
2418 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002419 *
2420 * <p>This method requires the caller to hold either the
2421 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2422 * or the ability to modify system settings as determined by
2423 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002424 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002425 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2426 * and WifiStateMachine which need direct access. All other clients should use
2427 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2428 * logic.</p>
2429 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002430 * @param iface the interface name to tether.
2431 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2432 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002433 * {@hide}
2434 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002435 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002436 public int tether(String iface) {
2437 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002438 String pkgName = mContext.getOpPackageName();
2439 Log.i(TAG, "tether caller:" + pkgName);
2440 return mService.tether(iface, pkgName);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002441 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002442 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002443 }
2444 }
2445
2446 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002447 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002448 *
2449 * <p>This method requires the caller to hold either the
2450 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2451 * or the ability to modify system settings as determined by
2452 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002453 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002454 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2455 * and WifiStateMachine which need direct access. All other clients should use
2456 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2457 * logic.</p>
2458 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002459 * @param iface the interface name to untether.
2460 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2461 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002462 * {@hide}
2463 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002464 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002465 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002466 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002467 String pkgName = mContext.getOpPackageName();
2468 Log.i(TAG, "untether caller:" + pkgName);
2469 return mService.untether(iface, pkgName);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002470 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002471 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002472 }
2473 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002474
2475 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002476 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002477 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002478 * due to device configuration.
2479 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002480 * <p>If this app does not have permission to use this API, it will always
2481 * return false rather than throw an exception.</p>
2482 *
2483 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2484 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2485 *
2486 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2487 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2488 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002489 * @return a boolean - {@code true} indicating Tethering is supported.
2490 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002491 * {@hide}
2492 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002493 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002494 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2495 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002496 public boolean isTetheringSupported() {
Chalard Jean8f76fc32017-09-26 15:45:18 +09002497 String pkgName = mContext.getOpPackageName();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002498 try {
Udam Saini0e94c362017-06-07 12:06:28 -07002499 return mService.isTetheringSupported(pkgName);
Chalard Jean8f76fc32017-09-26 15:45:18 +09002500 } catch (SecurityException e) {
2501 // This API is not available to this caller, but for backward-compatibility
2502 // this will just return false instead of throwing.
2503 return false;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002504 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002505 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002506 }
2507 }
2508
2509 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002510 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2511 * @hide
2512 */
2513 @SystemApi
2514 public static abstract class OnStartTetheringCallback {
2515 /**
2516 * Called when tethering has been successfully started.
2517 */
Chalard Jean4d660112018-06-04 16:52:49 +09002518 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002519
2520 /**
2521 * Called when starting tethering failed.
2522 */
Chalard Jean4d660112018-06-04 16:52:49 +09002523 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002524 }
2525
2526 /**
2527 * Convenient overload for
2528 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2529 * handler to run on the current thread's {@link Looper}.
2530 * @hide
2531 */
2532 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07002533 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002534 public void startTethering(int type, boolean showProvisioningUi,
2535 final OnStartTetheringCallback callback) {
2536 startTethering(type, showProvisioningUi, callback, null);
2537 }
2538
2539 /**
2540 * Runs tether provisioning for the given type if needed and then starts tethering if
2541 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2542 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2543 * schedules tether provisioning re-checks if appropriate.
2544 *
2545 * @param type The type of tethering to start. Must be one of
2546 * {@link ConnectivityManager.TETHERING_WIFI},
2547 * {@link ConnectivityManager.TETHERING_USB}, or
2548 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2549 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2550 * is one. This should be true the first time this function is called and also any time
2551 * the user can see this UI. It gives users information from their carrier about the
2552 * check failing and how they can sign up for tethering if possible.
2553 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2554 * of the result of trying to tether.
2555 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2556 * @hide
2557 */
2558 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002559 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002560 public void startTethering(int type, boolean showProvisioningUi,
2561 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002562 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002563
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002564 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2565 @Override
2566 protected void onReceiveResult(int resultCode, Bundle resultData) {
2567 if (resultCode == TETHER_ERROR_NO_ERROR) {
2568 callback.onTetheringStarted();
2569 } else {
2570 callback.onTetheringFailed();
2571 }
2572 }
2573 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002574
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002575 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002576 String pkgName = mContext.getOpPackageName();
2577 Log.i(TAG, "startTethering caller:" + pkgName);
2578 mService.startTethering(type, wrappedCallback, showProvisioningUi, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002579 } catch (RemoteException e) {
2580 Log.e(TAG, "Exception trying to start tethering.", e);
2581 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2582 }
2583 }
2584
2585 /**
2586 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2587 * applicable.
2588 *
2589 * @param type The type of tethering to stop. Must be one of
2590 * {@link ConnectivityManager.TETHERING_WIFI},
2591 * {@link ConnectivityManager.TETHERING_USB}, or
2592 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2593 * @hide
2594 */
2595 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002596 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002597 public void stopTethering(int type) {
2598 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002599 String pkgName = mContext.getOpPackageName();
2600 Log.i(TAG, "stopTethering caller:" + pkgName);
2601 mService.stopTethering(type, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002602 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002603 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002604 }
2605 }
2606
2607 /**
markchien26299ed2019-02-27 14:56:11 +08002608 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2609 * upstream status.
2610 *
2611 *@hide
2612 */
2613 @SystemApi
2614 public abstract static class OnTetheringEventCallback {
2615
2616 /**
2617 * Called when tethering upstream changed. This can be called multiple times and can be
2618 * called any time.
2619 *
2620 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2621 * have any upstream.
2622 */
2623 public void onUpstreamChanged(@Nullable Network network) {}
2624 }
2625
2626 @GuardedBy("mTetheringEventCallbacks")
2627 private final ArrayMap<OnTetheringEventCallback, ITetheringEventCallback>
2628 mTetheringEventCallbacks = new ArrayMap<>();
2629
2630 /**
2631 * Start listening to tethering change events. Any new added callback will receive the last
markchien9f246bd2019-04-03 10:43:09 +08002632 * tethering status right away. If callback is registered when tethering has no upstream or
markchien26299ed2019-02-27 14:56:11 +08002633 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2634 * with a null argument. The same callback object cannot be registered twice.
2635 *
2636 * @param executor the executor on which callback will be invoked.
2637 * @param callback the callback to be called when tethering has change events.
2638 * @hide
2639 */
2640 @SystemApi
2641 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2642 public void registerTetheringEventCallback(
2643 @NonNull @CallbackExecutor Executor executor,
2644 @NonNull final OnTetheringEventCallback callback) {
2645 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2646
2647 synchronized (mTetheringEventCallbacks) {
2648 Preconditions.checkArgument(!mTetheringEventCallbacks.containsKey(callback),
2649 "callback was already registered.");
2650 ITetheringEventCallback remoteCallback = new ITetheringEventCallback.Stub() {
2651 @Override
2652 public void onUpstreamChanged(Network network) throws RemoteException {
2653 Binder.withCleanCallingIdentity(() ->
2654 executor.execute(() -> {
2655 callback.onUpstreamChanged(network);
2656 }));
2657 }
2658 };
2659 try {
2660 String pkgName = mContext.getOpPackageName();
2661 Log.i(TAG, "registerTetheringUpstreamCallback:" + pkgName);
2662 mService.registerTetheringEventCallback(remoteCallback, pkgName);
2663 mTetheringEventCallbacks.put(callback, remoteCallback);
2664 } catch (RemoteException e) {
2665 throw e.rethrowFromSystemServer();
2666 }
2667 }
2668 }
2669
2670 /**
2671 * Remove tethering event callback previously registered with
2672 * {@link #registerTetheringEventCallback}.
2673 *
2674 * @param callback previously registered callback.
2675 * @hide
2676 */
2677 @SystemApi
2678 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2679 public void unregisterTetheringEventCallback(
2680 @NonNull final OnTetheringEventCallback callback) {
2681 synchronized (mTetheringEventCallbacks) {
2682 ITetheringEventCallback remoteCallback = mTetheringEventCallbacks.remove(callback);
2683 Preconditions.checkNotNull(remoteCallback, "callback was not registered.");
2684 try {
2685 String pkgName = mContext.getOpPackageName();
2686 Log.i(TAG, "unregisterTetheringEventCallback:" + pkgName);
2687 mService.unregisterTetheringEventCallback(remoteCallback, pkgName);
2688 } catch (RemoteException e) {
2689 throw e.rethrowFromSystemServer();
2690 }
2691 }
2692 }
2693
2694
2695 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002696 * Get the list of regular expressions that define any tetherable
2697 * USB network interfaces. If USB tethering is not supported by the
2698 * device, this list should be empty.
2699 *
2700 * @return an array of 0 or more regular expression Strings defining
2701 * what interfaces are considered tetherable usb interfaces.
2702 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002703 * {@hide}
2704 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002705 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002706 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002707 public String[] getTetherableUsbRegexs() {
2708 try {
2709 return mService.getTetherableUsbRegexs();
2710 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002711 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002712 }
2713 }
2714
2715 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002716 * Get the list of regular expressions that define any tetherable
2717 * Wifi network interfaces. If Wifi tethering is not supported by the
2718 * device, this list should be empty.
2719 *
2720 * @return an array of 0 or more regular expression Strings defining
2721 * what interfaces are considered tetherable wifi interfaces.
2722 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002723 * {@hide}
2724 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002725 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002726 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002727 public String[] getTetherableWifiRegexs() {
2728 try {
2729 return mService.getTetherableWifiRegexs();
2730 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002731 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002732 }
2733 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002734
Danica Chang6fdd0c62010-08-11 14:54:43 -07002735 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002736 * Get the list of regular expressions that define any tetherable
2737 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2738 * device, this list should be empty.
2739 *
2740 * @return an array of 0 or more regular expression Strings defining
2741 * what interfaces are considered tetherable bluetooth interfaces.
2742 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002743 * {@hide}
2744 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002745 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002746 @UnsupportedAppUsage
Danica Chang6fdd0c62010-08-11 14:54:43 -07002747 public String[] getTetherableBluetoothRegexs() {
2748 try {
2749 return mService.getTetherableBluetoothRegexs();
2750 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002751 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002752 }
2753 }
2754
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002755 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002756 * Attempt to both alter the mode of USB and Tethering of USB. A
2757 * utility method to deal with some of the complexity of USB - will
2758 * attempt to switch to Rndis and subsequently tether the resulting
2759 * interface on {@code true} or turn off tethering and switch off
2760 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002761 *
2762 * <p>This method requires the caller to hold either the
2763 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2764 * or the ability to modify system settings as determined by
2765 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002766 *
2767 * @param enable a boolean - {@code true} to enable tethering
2768 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2769 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002770 * {@hide}
2771 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002772 @UnsupportedAppUsage
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002773 public int setUsbTethering(boolean enable) {
2774 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002775 String pkgName = mContext.getOpPackageName();
2776 Log.i(TAG, "setUsbTethering caller:" + pkgName);
2777 return mService.setUsbTethering(enable, pkgName);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002778 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002779 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002780 }
2781 }
2782
Robert Greenwalt5a735062010-03-02 17:25:02 -08002783 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002784 @SystemApi
Robert Greenwalt5a735062010-03-02 17:25:02 -08002785 public static final int TETHER_ERROR_NO_ERROR = 0;
2786 /** {@hide} */
2787 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2788 /** {@hide} */
2789 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2790 /** {@hide} */
2791 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2792 /** {@hide} */
2793 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2794 /** {@hide} */
2795 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2796 /** {@hide} */
2797 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2798 /** {@hide} */
2799 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2800 /** {@hide} */
2801 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2802 /** {@hide} */
2803 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2804 /** {@hide} */
2805 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002806 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002807 @SystemApi
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002808 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +09002809 /** {@hide} */
2810 public static final int TETHER_ERROR_DHCPSERVER_ERROR = 12;
markchienf2731272019-01-16 17:44:13 +08002811 /** {@hide} */
2812 @SystemApi
2813 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002814
2815 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002816 * Get a more detailed error code after a Tethering or Untethering
2817 * request asynchronously failed.
2818 *
2819 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002820 * @return error The error code of the last error tethering or untethering the named
2821 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002822 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002823 * {@hide}
2824 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002825 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002826 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002827 public int getLastTetherError(String iface) {
2828 try {
2829 return mService.getLastTetherError(iface);
2830 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002831 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002832 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002833 }
2834
markchien9554abf2019-03-06 16:25:00 +08002835 /** @hide */
2836 @Retention(RetentionPolicy.SOURCE)
2837 @IntDef(value = {
2838 TETHER_ERROR_NO_ERROR,
2839 TETHER_ERROR_PROVISION_FAILED,
2840 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2841 })
2842 public @interface EntitlementResultCode {
2843 }
2844
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002845 /**
markchien9554abf2019-03-06 16:25:00 +08002846 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchienf2731272019-01-16 17:44:13 +08002847 * entitlement succeeded.
2848 * @hide
2849 */
2850 @SystemApi
markchien9554abf2019-03-06 16:25:00 +08002851 public interface OnTetheringEntitlementResultListener {
2852 /**
2853 * Called to notify entitlement result.
2854 *
2855 * @param resultCode an int value of entitlement result. It may be one of
2856 * {@link #TETHER_ERROR_NO_ERROR},
2857 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2858 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2859 */
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002860 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchien9554abf2019-03-06 16:25:00 +08002861 }
2862
2863 /**
markchienf2731272019-01-16 17:44:13 +08002864 * Get the last value of the entitlement check on this downstream. If the cached value is
2865 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2866 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2867 * guaranteed that the UI-based entitlement check will complete in any specific time period
2868 * and may in fact never complete. Any successful entitlement check the platform performs for
2869 * any reason will update the cached value.
2870 *
2871 * @param type the downstream type of tethering. Must be one of
2872 * {@link #TETHERING_WIFI},
2873 * {@link #TETHERING_USB}, or
2874 * {@link #TETHERING_BLUETOOTH}.
2875 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchien9554abf2019-03-06 16:25:00 +08002876 * @param executor the executor on which callback will be invoked.
2877 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2878 * notify the caller of the result of entitlement check. The listener may be called zero
2879 * or one time.
markchienf2731272019-01-16 17:44:13 +08002880 * {@hide}
2881 */
2882 @SystemApi
2883 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchien9554abf2019-03-06 16:25:00 +08002884 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2885 @NonNull @CallbackExecutor Executor executor,
2886 @NonNull final OnTetheringEntitlementResultListener listener) {
2887 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2888 ResultReceiver wrappedListener = new ResultReceiver(null) {
2889 @Override
2890 protected void onReceiveResult(int resultCode, Bundle resultData) {
2891 Binder.withCleanCallingIdentity(() ->
2892 executor.execute(() -> {
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002893 listener.onTetheringEntitlementResult(resultCode);
markchien9554abf2019-03-06 16:25:00 +08002894 }));
2895 }
2896 };
2897
2898 try {
2899 String pkgName = mContext.getOpPackageName();
2900 Log.i(TAG, "getLatestTetheringEntitlementResult:" + pkgName);
2901 mService.getLatestTetheringEntitlementResult(type, wrappedListener,
2902 showEntitlementUi, pkgName);
2903 } catch (RemoteException e) {
2904 throw e.rethrowFromSystemServer();
2905 }
2906 }
2907
2908 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002909 * Report network connectivity status. This is currently used only
2910 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002911 * <p>This method requires the caller to hold the permission
2912 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002913 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002914 * @param networkType The type of network you want to report on
2915 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002916 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002917 * {@hide}
2918 */
2919 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002920 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002921 try {
2922 mService.reportInetCondition(networkType, percentage);
2923 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002924 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002925 }
2926 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002927
2928 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002929 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002930 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002931 * the framework to re-evaluate network connectivity and/or switch to another
2932 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002933 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002934 * @param network The {@link Network} the application was attempting to use
2935 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002936 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2937 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002938 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002939 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002940 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002941 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002942 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002943 // One of these will be ignored because it matches system's current state.
2944 // The other will trigger the necessary reevaluation.
2945 mService.reportNetworkConnectivity(network, true);
2946 mService.reportNetworkConnectivity(network, false);
2947 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002948 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002949 }
2950 }
2951
2952 /**
2953 * Report to the framework whether a network has working connectivity.
2954 * This provides a hint to the system that a particular network is providing
2955 * working connectivity or not. In response the framework may re-evaluate
2956 * the network's connectivity and might take further action thereafter.
2957 *
2958 * @param network The {@link Network} the application was attempting to use
2959 * or {@code null} to indicate the current default network.
2960 * @param hasConnectivity {@code true} if the application was able to successfully access the
2961 * Internet using {@code network} or {@code false} if not.
2962 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002963 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002964 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002965 try {
2966 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002967 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002968 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002969 }
2970 }
2971
2972 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002973 * Set a network-independent global http proxy. This is not normally what you want
2974 * for typical HTTP proxies - they are general network dependent. However if you're
2975 * doing something unusual like general internal filtering this may be useful. On
2976 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002977 *
2978 * @param p A {@link ProxyInfo} object defining the new global
2979 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002980 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002981 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002982 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Jason Monk207900c2014-04-25 15:00:09 -04002983 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002984 try {
2985 mService.setGlobalProxy(p);
2986 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002987 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002988 }
2989 }
2990
2991 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002992 * Retrieve any network-independent global HTTP proxy.
2993 *
Jason Monk207900c2014-04-25 15:00:09 -04002994 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002995 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002996 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002997 */
Jason Monk207900c2014-04-25 15:00:09 -04002998 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002999 try {
3000 return mService.getGlobalProxy();
3001 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003002 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003003 }
3004 }
3005
3006 /**
Paul Jensencee9b512015-05-06 07:32:40 -04003007 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3008 * network-specific HTTP proxy. If {@code network} is null, the
3009 * network-specific proxy returned is the proxy of the default active
3010 * network.
3011 *
3012 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3013 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3014 * or when {@code network} is {@code null},
3015 * the {@code ProxyInfo} for the default active network. Returns
3016 * {@code null} when no proxy applies or the caller doesn't have
3017 * permission to use {@code network}.
3018 * @hide
3019 */
3020 public ProxyInfo getProxyForNetwork(Network network) {
3021 try {
3022 return mService.getProxyForNetwork(network);
3023 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003024 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04003025 }
3026 }
3027
3028 /**
Paul Jensene0bef712014-12-10 15:12:18 -05003029 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3030 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04003031 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05003032 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003033 *
Jason Monk207900c2014-04-25 15:00:09 -04003034 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003035 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07003036 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003037 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05003038 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04003039 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07003040 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003041
3042 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003043 * Returns true if the hardware supports the given network type
3044 * else it returns false. This doesn't indicate we have coverage
3045 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003046 * hardware supports it. For example a GSM phone without a SIM
3047 * should still return {@code true} for mobile data, but a wifi only
3048 * tablet would return {@code false}.
3049 *
3050 * @param networkType The network type we'd like to check
3051 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003052 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003053 * @hide
3054 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003055 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003056 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09003057 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003058 public boolean isNetworkSupported(int networkType) {
3059 try {
3060 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003061 } catch (RemoteException e) {
3062 throw e.rethrowFromSystemServer();
3063 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003064 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003065
3066 /**
3067 * Returns if the currently active data network is metered. A network is
3068 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003069 * that connection due to monetary costs, data limitations or
3070 * battery/performance issues. You should check this before doing large
3071 * data transfers, and warn the user or delay the operation until another
3072 * network is available.
3073 *
3074 * @return {@code true} if large transfers should be avoided, otherwise
3075 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003076 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003077 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003078 public boolean isActiveNetworkMetered() {
3079 try {
3080 return mService.isActiveNetworkMetered();
3081 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003082 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003083 }
3084 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003085
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003086 /**
3087 * If the LockdownVpn mechanism is enabled, updates the vpn
3088 * with a reload of its profile.
3089 *
3090 * @return a boolean with {@code} indicating success
3091 *
3092 * <p>This method can only be called by the system UID
3093 * {@hide}
3094 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003095 public boolean updateLockdownVpn() {
3096 try {
3097 return mService.updateLockdownVpn();
3098 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003099 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003100 }
3101 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07003102
3103 /**
Wink Saville948282b2013-08-29 08:55:16 -07003104 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07003105 *
Wink Savilleab9321d2013-06-29 21:10:57 -07003106 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07003107 *
3108 * @return time out that will be used, maybe less that suggestedTimeOutMs
3109 * -1 if an error.
3110 *
3111 * {@hide}
3112 */
Wink Saville948282b2013-08-29 08:55:16 -07003113 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003114 int timeOutMs = -1;
3115 try {
Wink Saville948282b2013-08-29 08:55:16 -07003116 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07003117 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003118 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07003119 }
3120 return timeOutMs;
3121 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003122
3123 /**
Wink Saville42d4f082013-07-20 20:31:59 -07003124 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003125 * {@hide}
3126 */
3127 public String getMobileProvisioningUrl() {
3128 try {
3129 return mService.getMobileProvisioningUrl();
3130 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003131 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003132 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003133 }
Wink Saville42d4f082013-07-20 20:31:59 -07003134
3135 /**
Wink Saville948282b2013-08-29 08:55:16 -07003136 * Set sign in error notification to visible or in visible
3137 *
Wink Saville948282b2013-08-29 08:55:16 -07003138 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04003139 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07003140 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003141 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07003142 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003143 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003144 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04003145 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07003146 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003147 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07003148 }
3149 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003150
3151 /**
3152 * Set the value for enabling/disabling airplane mode
3153 *
3154 * @param enable whether to enable airplane mode or not
3155 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003156 * @hide
3157 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003158 @RequiresPermission(anyOf = {
3159 android.Manifest.permission.NETWORK_SETTINGS,
3160 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3161 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09003162 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003163 public void setAirplaneMode(boolean enable) {
3164 try {
3165 mService.setAirplaneMode(enable);
3166 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003167 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003168 }
3169 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003170
Chalard Jean05ab6812018-05-02 21:14:54 +09003171 /** {@hide} - returns the factory serial number */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003172 @UnsupportedAppUsage
Chalard Jean05ab6812018-05-02 21:14:54 +09003173 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003174 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003175 return mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003176 } catch (RemoteException e) {
3177 throw e.rethrowFromSystemServer();
3178 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003179 }
3180
3181 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00003182 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Robert Greenwalta67be032014-05-16 15:49:14 -07003183 public void unregisterNetworkFactory(Messenger messenger) {
3184 try {
3185 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003186 } catch (RemoteException e) {
3187 throw e.rethrowFromSystemServer();
3188 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003189 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003190
Chalard Jean05ab6812018-05-02 21:14:54 +09003191 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3192 // of dependent changes that would conflict throughout the automerger graph. Having this
3193 // temporarily helps with the process of going through with all these dependent changes across
3194 // the entire tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05003195 /**
3196 * @hide
3197 * Register a NetworkAgent with ConnectivityService.
3198 * @return NetID corresponding to NetworkAgent.
3199 */
3200 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003201 NetworkCapabilities nc, int score, NetworkMisc misc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003202 return registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3203 NetworkFactory.SerialNumber.NONE);
3204 }
3205
3206 /**
3207 * @hide
3208 * Register a NetworkAgent with ConnectivityService.
3209 * @return NetID corresponding to NetworkAgent.
3210 */
3211 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
3212 NetworkCapabilities nc, int score, NetworkMisc misc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003213 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003214 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3215 factorySerialNumber);
Paul Jensen31a94f42015-02-13 14:18:39 -05003216 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003217 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05003218 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003219 }
3220
Robert Greenwalt9258c642014-03-26 16:47:06 -07003221 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003222 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3223 * changes. Should be extended by applications wanting notifications.
3224 *
3225 * A {@code NetworkCallback} is registered by calling
3226 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3227 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09003228 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09003229 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3230 * A {@code NetworkCallback} should be registered at most once at any time.
3231 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003232 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003233 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003234 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003235 * Called when the framework connects to a new network to evaluate whether it satisfies this
3236 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3237 * callback. There is no guarantee that this new network will satisfy any requests, or that
3238 * the network will stay connected for longer than the time necessary to evaluate it.
3239 * <p>
3240 * Most applications <b>should not</b> act on this callback, and should instead use
3241 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3242 * the framework in properly evaluating the network &mdash; for example, an application that
3243 * can automatically log in to a captive portal without user intervention.
3244 *
3245 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09003246 *
3247 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07003248 */
paulhu3d67f532019-03-22 16:35:06 +08003249 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003250
3251 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003252 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003253 * This callback may be called more than once if the {@link Network} that is
3254 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003255 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003256 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003257 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3258 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08003259 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003260 * @hide
3261 */
paulhu3d67f532019-03-22 16:35:06 +08003262 public void onAvailable(@NonNull Network network,
3263 @NonNull NetworkCapabilities networkCapabilities,
3264 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003265 // Internally only this method is called when a new network is available, and
3266 // it calls the callback in the same way and order that older versions used
3267 // to call so as not to change the behavior.
3268 onAvailable(network);
3269 if (!networkCapabilities.hasCapability(
3270 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3271 onNetworkSuspended(network);
3272 }
3273 onCapabilitiesChanged(network, networkCapabilities);
3274 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003275 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003276 }
3277
3278 /**
3279 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean599ce752019-08-30 16:27:28 +09003280 *
3281 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3282 * be available at the same time, and onAvailable will be called for each of these as they
3283 * appear.
3284 *
3285 * <p>For callbacks registered with {@link #requestNetwork} and
3286 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3287 * is the new best network for this request and is now tracked by this callback ; this
3288 * callback will no longer receive method calls about other networks that may have been
3289 * passed to this method previously. The previously-best network may have disconnected, or
3290 * it may still be around and the newly-best network may simply be better.
3291 *
3292 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3293 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3294 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3295 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3296 *
3297 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3298 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3299 * this callback as this is prone to race conditions (there is no guarantee the objects
3300 * returned by these methods will be current). Instead, wait for a call to
3301 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3302 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3303 * to be well-ordered with respect to other callbacks.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003304 *
3305 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003306 */
paulhu3d67f532019-03-22 16:35:06 +08003307 public void onAvailable(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003308
3309 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003310 * Called when the network is about to be lost, typically because there are no outstanding
3311 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3312 * with the new replacement network for graceful handover. This method is not guaranteed
3313 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3314 * network is suddenly disconnected.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003315 *
Chalard Jean599ce752019-08-30 16:27:28 +09003316 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3317 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3318 * this callback as this is prone to race conditions ; calling these methods while in a
3319 * callback may return an outdated or even a null object.
3320 *
3321 * @param network The {@link Network} that is about to be lost.
3322 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3323 * connected for graceful handover; note that the network may still
3324 * suffer a hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003325 */
paulhu3d67f532019-03-22 16:35:06 +08003326 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003327
3328 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003329 * Called when a network disconnects or otherwise no longer satisfies this request or
3330 * callback.
3331 *
3332 * <p>If the callback was registered with requestNetwork() or
3333 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3334 * returned by onAvailable() when that network is lost and no other network satisfies
3335 * the criteria of the request.
3336 *
3337 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3338 * each network which no longer satisfies the criteria of the callback.
3339 *
3340 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3341 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3342 * this callback as this is prone to race conditions ; calling these methods while in a
3343 * callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003344 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003345 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003346 */
paulhu3d67f532019-03-22 16:35:06 +08003347 public void onLost(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003348
3349 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003350 * Called if no network is found within the timeout time specified in
Etan Cohenddb720a2019-01-08 12:09:18 -08003351 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3352 * requested network request cannot be fulfilled (whether or not a timeout was
3353 * specified). When this callback is invoked the associated
Etan Cohenaebf17e2017-03-01 12:47:28 -08003354 * {@link NetworkRequest} will have already been removed and released, as if
3355 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003356 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003357 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003358
3359 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003360 * Called when the network corresponding to this request changes capabilities but still
3361 * satisfies the requested criteria.
3362 *
3363 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3364 * to be called immediately after {@link #onAvailable}.
3365 *
3366 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3367 * ConnectivityManager methods in this callback as this is prone to race conditions :
3368 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003369 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003370 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003371 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3372 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003373 */
paulhu3d67f532019-03-22 16:35:06 +08003374 public void onCapabilitiesChanged(@NonNull Network network,
3375 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003376
3377 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003378 * Called when the network corresponding to this request changes {@link LinkProperties}.
3379 *
3380 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3381 * to be called immediately after {@link #onAvailable}.
3382 *
3383 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3384 * ConnectivityManager methods in this callback as this is prone to race conditions :
3385 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003386 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003387 * @param network The {@link Network} whose link properties have changed.
3388 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003389 */
paulhu3d67f532019-03-22 16:35:06 +08003390 public void onLinkPropertiesChanged(@NonNull Network network,
3391 @NonNull LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003392
Robert Greenwalt8d482522015-06-24 13:23:42 -07003393 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003394 * Called when the network the framework connected to for this request suspends data
3395 * transmission temporarily.
3396 *
3397 * <p>This generally means that while the TCP connections are still live temporarily
3398 * network data fails to transfer. To give a specific example, this is used on cellular
3399 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3400 * means read operations on sockets on this network will block once the buffers are
3401 * drained, and write operations will block once the buffers are full.
3402 *
3403 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3404 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3405 * this callback as this is prone to race conditions (there is no guarantee the objects
3406 * returned by these methods will be current).
3407 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003408 * @hide
3409 */
paulhu3d67f532019-03-22 16:35:06 +08003410 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003411
3412 /**
3413 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003414 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3415 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean599ce752019-08-30 16:27:28 +09003416
3417 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3418 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3419 * this callback as this is prone to race conditions : calling these methods while in a
3420 * callback may return an outdated or even a null object.
3421 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003422 * @hide
3423 */
paulhu3d67f532019-03-22 16:35:06 +08003424 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003425
junyulai05986c62018-08-07 19:50:45 +08003426 /**
3427 * Called when access to the specified network is blocked or unblocked.
3428 *
Chalard Jean599ce752019-08-30 16:27:28 +09003429 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3430 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3431 * this callback as this is prone to race conditions : calling these methods while in a
3432 * callback may return an outdated or even a null object.
3433 *
junyulai05986c62018-08-07 19:50:45 +08003434 * @param network The {@link Network} whose blocked status has changed.
3435 * @param blocked The blocked status of this {@link Network}.
3436 */
junyulai0c666972019-03-04 22:45:36 +08003437 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai05986c62018-08-07 19:50:45 +08003438
Robert Greenwalt6078b502014-06-11 16:05:07 -07003439 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003440 }
3441
Hugo Benichicb883232017-05-11 13:16:17 +09003442 /**
3443 * Constant error codes used by ConnectivityService to communicate about failures and errors
3444 * across a Binder boundary.
3445 * @hide
3446 */
3447 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003448 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003449 }
3450
3451 /** @hide */
3452 public static class TooManyRequestsException extends RuntimeException {}
3453
3454 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3455 switch (e.errorCode) {
3456 case Errors.TOO_MANY_REQUESTS:
3457 return new TooManyRequestsException();
3458 default:
3459 Log.w(TAG, "Unknown service error code " + e.errorCode);
3460 return new RuntimeException(e);
3461 }
3462 }
3463
Robert Greenwalt9258c642014-03-26 16:47:06 -07003464 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003465 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003466 public static final int CALLBACK_PRECHECK = BASE + 1;
3467 /** @hide */
3468 public static final int CALLBACK_AVAILABLE = BASE + 2;
3469 /** @hide arg1 = TTL */
3470 public static final int CALLBACK_LOSING = BASE + 3;
3471 /** @hide */
3472 public static final int CALLBACK_LOST = BASE + 4;
3473 /** @hide */
3474 public static final int CALLBACK_UNAVAIL = BASE + 5;
3475 /** @hide */
3476 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3477 /** @hide */
3478 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003479 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003480 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003481 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003482 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003483 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003484 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003485 /** @hide */
3486 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003487
Erik Kline57faba92015-11-25 12:49:38 +09003488 /** @hide */
3489 public static String getCallbackName(int whichCallback) {
3490 switch (whichCallback) {
3491 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3492 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3493 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3494 case CALLBACK_LOST: return "CALLBACK_LOST";
3495 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3496 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3497 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003498 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3499 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3500 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003501 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003502 default:
3503 return Integer.toString(whichCallback);
3504 }
3505 }
3506
Robert Greenwalt562cc542014-05-15 18:07:26 -07003507 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003508 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003509 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003510
Hugo Benichid42650f2016-07-06 22:53:17 +09003511 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003512 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003513 }
3514
Hugo Benichi2583ef02017-02-02 17:02:36 +09003515 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003516 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003517 }
3518
Robert Greenwalt9258c642014-03-26 16:47:06 -07003519 @Override
3520 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003521 if (message.what == EXPIRE_LEGACY_REQUEST) {
3522 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3523 return;
3524 }
3525
3526 final NetworkRequest request = getObject(message, NetworkRequest.class);
3527 final Network network = getObject(message, Network.class);
3528 final NetworkCallback callback;
3529 synchronized (sCallbacks) {
3530 callback = sCallbacks.get(request);
Etan Cohen4a62d1d2019-05-21 12:06:04 -07003531 if (callback == null) {
3532 Log.w(TAG,
3533 "callback not found for " + getCallbackName(message.what) + " message");
3534 return;
3535 }
Etan Cohen9b09a162019-04-16 15:07:55 -07003536 if (message.what == CALLBACK_UNAVAIL) {
3537 sCallbacks.remove(request);
3538 callback.networkRequest = ALREADY_UNREGISTERED;
3539 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003540 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003541 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003542 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003543 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003544
Robert Greenwalt9258c642014-03-26 16:47:06 -07003545 switch (message.what) {
3546 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003547 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003548 break;
3549 }
3550 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003551 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3552 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003553 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003554 break;
3555 }
3556 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003557 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003558 break;
3559 }
3560 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003561 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003562 break;
3563 }
3564 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003565 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003566 break;
3567 }
3568 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003569 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3570 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003571 break;
3572 }
3573 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003574 LinkProperties lp = getObject(message, LinkProperties.class);
3575 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003576 break;
3577 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003578 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003579 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003580 break;
3581 }
3582 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003583 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003584 break;
3585 }
junyulai05986c62018-08-07 19:50:45 +08003586 case CALLBACK_BLK_CHANGED: {
3587 boolean blocked = message.arg1 != 0;
3588 callback.onBlockedStatusChanged(network, blocked);
3589 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003590 }
3591 }
3592
Hugo Benichid42650f2016-07-06 22:53:17 +09003593 private <T> T getObject(Message msg, Class<T> c) {
3594 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003595 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003596 }
3597
Hugo Benichi2583ef02017-02-02 17:02:36 +09003598 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003599 synchronized (sCallbacks) {
3600 if (sCallbackHandler == null) {
3601 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003602 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003603 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003604 }
3605 }
3606
Hugo Benichi6f260f32017-02-03 14:18:44 +09003607 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3608 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003609
Hugo Benichi6f260f32017-02-03 14:18:44 +09003610 private static final int LISTEN = 1;
3611 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003612
Hugo Benichi6f260f32017-02-03 14:18:44 +09003613 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3614 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003615 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003616 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003617 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003618 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003619 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003620 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003621 if (callback.networkRequest != null
3622 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003623 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3624 // and requests (http://b/20701525).
3625 Log.e(TAG, "NetworkCallback was already registered");
3626 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003627 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003628 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003629 if (action == LISTEN) {
Hugo Benichid42650f2016-07-06 22:53:17 +09003630 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04003631 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003632 request = mService.requestNetwork(
3633 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04003634 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003635 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003636 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003637 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003638 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003639 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003640 } catch (RemoteException e) {
3641 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003642 } catch (ServiceSpecificException e) {
3643 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003644 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003645 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003646 }
3647
3648 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003649 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003650 *
3651 * This is temporarily public @hide so it can be called by system code that uses the
3652 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
3653 * instead network notifications.
3654 *
3655 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
3656 *
3657 * @hide
3658 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003659 public void requestNetwork(@NonNull NetworkRequest request,
3660 @NonNull NetworkCallback networkCallback, int timeoutMs, int legacyType,
3661 @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003662 CallbackHandler cbHandler = new CallbackHandler(handler);
3663 NetworkCapabilities nc = request.networkCapabilities;
3664 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003665 }
3666
3667 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003668 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003669 *
Chalard Jean599ce752019-08-30 16:27:28 +09003670 * <p>This method will attempt to find the best network that matches the passed
3671 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3672 * criteria. The platform will evaluate which network is the best at its own discretion.
3673 * Throughput, latency, cost per byte, policy, user preference and other considerations
3674 * may be factored in the decision of what is considered the best network.
3675 *
3676 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3677 * matching this request, while always attempting to match the request to a better network if
3678 * possible. If a better match is found, the platform will switch this request to the now-best
3679 * network and inform the app of the newly best network by invoking
3680 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3681 * will not try to maintain any other network than the best one currently matching the request:
3682 * a network not matching any network request may be disconnected at any time.
3683 *
3684 * <p>For example, an application could use this method to obtain a connected cellular network
3685 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3686 * radio to consume additional power. Or, an application could inform the system that it wants
3687 * a network supporting sending MMSes and have the system let it know about the currently best
3688 * MMS-supporting network through the provided {@link NetworkCallback}.
3689 *
3690 * <p>The status of the request can be followed by listening to the various callbacks described
3691 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3692 * used to direct traffic to the network (although accessing some networks may be subject to
3693 * holding specific permissions). Callers will learn about the specific characteristics of the
3694 * network through
3695 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3696 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3697 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3698 * matching the request at any given time; therefore when a better network matching the request
3699 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3700 * with the new network after which no further updates are given about the previously-best
3701 * network, unless it becomes the best again at some later time. All callbacks are invoked
3702 * in order on the same thread, which by default is a thread created by the framework running
3703 * in the app.
3704 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3705 * callbacks are invoked.
3706 *
3707 * <p>This{@link NetworkRequest} will live until released via
3708 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3709 * which point the system may let go of the network at any time.
3710 *
3711 * <p>A version of this method which takes a timeout is
3712 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3713 * wait for a limited amount of time for the network to become unavailable.
3714 *
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003715 * <p>It is presently unsupported to request a network with mutable
3716 * {@link NetworkCapabilities} such as
3717 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3718 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3719 * as these {@code NetworkCapabilities} represent states that a particular
3720 * network may never attain, and whether a network will attain these states
3721 * is unknown prior to bringing up the network so the framework does not
Chalard Jean599ce752019-08-30 16:27:28 +09003722 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003723 *
3724 * <p>This method requires the caller to hold either the
3725 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3726 * or the ability to modify system settings as determined by
3727 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003728 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003729 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003730 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3731 * the callback must not be shared - it uniquely specifies this request.
3732 * The callback is invoked on the default internal Handler.
Chalard Jean92c8b672019-05-13 15:13:58 +09003733 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3734 * @throws SecurityException if missing the appropriate permissions.
3735 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003736 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003737 public void requestNetwork(@NonNull NetworkRequest request,
3738 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003739 requestNetwork(request, networkCallback, getDefaultHandler());
3740 }
3741
3742 /**
3743 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3744 *
Chalard Jean599ce752019-08-30 16:27:28 +09003745 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3746 * but runs all the callbacks on the passed Handler.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003747 *
Chalard Jean599ce752019-08-30 16:27:28 +09003748 * <p>This method has the same permission requirements as
3749 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3750 * the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003751 *
3752 * @param request {@link NetworkRequest} describing this request.
3753 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3754 * the callback must not be shared - it uniquely specifies this request.
3755 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003756 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003757 public void requestNetwork(@NonNull NetworkRequest request,
3758 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003759 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3760 CallbackHandler cbHandler = new CallbackHandler(handler);
3761 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003762 }
3763
3764 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003765 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3766 * by a timeout.
3767 *
3768 * This function behaves identically to the non-timed-out version
3769 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3770 * is not found within the given time (in milliseconds) the
3771 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3772 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3773 * not have to be released if timed-out (it is automatically released). Unregistering a
3774 * request that timed out is not an error.
3775 *
3776 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3777 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3778 * for that purpose. Calling this method will attempt to bring up the requested network.
3779 *
Chalard Jean599ce752019-08-30 16:27:28 +09003780 * <p>This method has the same permission requirements as
3781 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3782 * the same conditions.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003783 *
3784 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003785 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3786 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003787 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3788 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3789 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003790 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003791 public void requestNetwork(@NonNull NetworkRequest request,
3792 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003793 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003794 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003795 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003796 }
3797
Hugo Benichi2583ef02017-02-02 17:02:36 +09003798 /**
3799 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3800 * by a timeout.
3801 *
Chalard Jean599ce752019-08-30 16:27:28 +09003802 * This method behaves identically to
3803 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3804 * on the passed Handler.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003805 *
Chalard Jean599ce752019-08-30 16:27:28 +09003806 * <p>This method has the same permission requirements as
3807 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} and throws the same exceptions
3808 * in the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003809 *
3810 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003811 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3812 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003813 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003814 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3815 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003816 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003817 public void requestNetwork(@NonNull NetworkRequest request,
3818 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003819 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003820 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3821 CallbackHandler cbHandler = new CallbackHandler(handler);
3822 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003823 }
3824
3825 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003826 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003827 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003828 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003829 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003830 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3831 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003832 */
Erik Kline90e93072014-11-19 12:12:24 +09003833 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003834
3835 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003836 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003837 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003838 * {@link android.content.Intent#getParcelableExtra(String)}.
3839 */
Erik Kline90e93072014-11-19 12:12:24 +09003840 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003841
3842
3843 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003844 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003845 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003846 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003847 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003848 * the request may outlive the calling application and get called back when a suitable
3849 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003850 * <p>
3851 * The operation is an Intent broadcast that goes to a broadcast receiver that
3852 * you registered with {@link Context#registerReceiver} or through the
3853 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3854 * <p>
3855 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003856 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3857 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003858 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003859 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003860 * Intent to reserve the network or it will be released shortly after the Intent
3861 * is processed.
3862 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003863 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003864 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003865 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003866 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003867 * The request may be released normally by calling
3868 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003869 * <p>It is presently unsupported to request a network with either
3870 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3871 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3872 * as these {@code NetworkCapabilities} represent states that a particular
3873 * network may never attain, and whether a network will attain these states
3874 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003875 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003876 *
3877 * <p>This method requires the caller to hold either the
3878 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3879 * or the ability to modify system settings as determined by
3880 * {@link android.provider.Settings.System#canWrite}.</p>
3881 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003882 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003883 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003884 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003885 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean92c8b672019-05-13 15:13:58 +09003886 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3887 * @throws SecurityException if missing the appropriate permissions.
3888 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003889 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003890 public void requestNetwork(@NonNull NetworkRequest request,
3891 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003892 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003893 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003894 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003895 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003896 } catch (RemoteException e) {
3897 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003898 } catch (ServiceSpecificException e) {
3899 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003900 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003901 }
3902
3903 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003904 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3905 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003906 * This method has the same behavior as
3907 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003908 * releasing network resources and disconnecting.
3909 *
3910 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3911 * PendingIntent passed to
3912 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3913 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3914 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003915 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003916 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003917 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003918 try {
3919 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003920 } catch (RemoteException e) {
3921 throw e.rethrowFromSystemServer();
3922 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003923 }
3924
Hugo Benichie7678512017-05-09 15:19:01 +09003925 private static void checkPendingIntentNotNull(PendingIntent intent) {
3926 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3927 }
3928
3929 private static void checkCallbackNotNull(NetworkCallback callback) {
3930 Preconditions.checkNotNull(callback, "null NetworkCallback");
3931 }
3932
3933 private static void checkTimeout(int timeoutMs) {
3934 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003935 }
3936
3937 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003938 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003939 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003940 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3941 * called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003942 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003943 * @param request {@link NetworkRequest} describing this request.
3944 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3945 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003946 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003947 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003948 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003949 public void registerNetworkCallback(@NonNull NetworkRequest request,
3950 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003951 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3952 }
3953
3954 /**
3955 * Registers to receive notifications about all networks which satisfy the given
3956 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003957 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3958 * called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003959 *
3960 * @param request {@link NetworkRequest} describing this request.
3961 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3962 * networks change state.
3963 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003964 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003965 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003966 public void registerNetworkCallback(@NonNull NetworkRequest request,
3967 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003968 CallbackHandler cbHandler = new CallbackHandler(handler);
3969 NetworkCapabilities nc = request.networkCapabilities;
3970 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003971 }
3972
3973 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003974 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3975 * {@link NetworkRequest}.
3976 *
3977 * This function behaves identically to the version that takes a NetworkCallback, but instead
3978 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3979 * the request may outlive the calling application and get called back when a suitable
3980 * network is found.
3981 * <p>
3982 * The operation is an Intent broadcast that goes to a broadcast receiver that
3983 * you registered with {@link Context#registerReceiver} or through the
3984 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3985 * <p>
3986 * The operation Intent is delivered with two extras, a {@link Network} typed
3987 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3988 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3989 * the original requests parameters.
3990 * <p>
3991 * If there is already a request for this Intent registered (with the equality of
3992 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3993 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3994 * <p>
3995 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003996 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003997 * @param request {@link NetworkRequest} describing this request.
3998 * @param operation Action to perform when the network is available (corresponds
3999 * to the {@link NetworkCallback#onAvailable} call. Typically
4000 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4001 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004002 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004003 public void registerNetworkCallback(@NonNull NetworkRequest request,
4004 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004005 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004006 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04004007 try {
4008 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004009 } catch (RemoteException e) {
4010 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09004011 } catch (ServiceSpecificException e) {
4012 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004013 }
Paul Jensen694f2b82015-06-17 14:15:39 -04004014 }
4015
4016 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004017 * Registers to receive notifications about changes in the system default network. The callbacks
4018 * will continue to be called until either the application exits or
4019 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09004020 *
4021 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4022 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004023 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09004024 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004025 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004026 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004027 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4028 }
4029
4030 /**
4031 * Registers to receive notifications about changes in the system default network. The callbacks
4032 * will continue to be called until either the application exits or
4033 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004034 *
4035 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4036 * system default network changes.
4037 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004038 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004039 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004040 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4041 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09004042 // This works because if the NetworkCapabilities are null,
4043 // ConnectivityService takes them from the default request.
4044 //
4045 // Since the capabilities are exactly the same as the default request's
4046 // capabilities, this request is guaranteed, at all times, to be
4047 // satisfied by the same network, if any, that satisfies the default
4048 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004049 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09004050 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4051 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09004052 }
4053
4054 /**
fengludb571472015-04-21 17:12:05 -07004055 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4056 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4057 * network connection for updated bandwidth information. The caller will be notified via
4058 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004059 * method assumes that the caller has previously called
4060 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4061 * changes.
fenglub15e72b2015-03-20 11:29:56 -07004062 *
fengluae519192015-04-27 14:28:04 -07004063 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07004064 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07004065 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004066 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004067 try {
fengludb571472015-04-21 17:12:05 -07004068 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07004069 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004070 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07004071 }
4072 }
4073
4074 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09004075 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004076 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4077 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4078 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09004079 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4080 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004081 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09004082 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4083 * triggering it as soon as this call returns.
4084 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07004085 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004086 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004087 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004088 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004089 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09004090 final List<NetworkRequest> reqs = new ArrayList<>();
4091 // Find all requests associated to this callback and stop callback triggers immediately.
4092 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4093 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09004094 Preconditions.checkArgument(networkCallback.networkRequest != null,
4095 "NetworkCallback was not registered");
Etan Cohen9b09a162019-04-16 15:07:55 -07004096 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4097 Log.d(TAG, "NetworkCallback was already unregistered");
4098 return;
4099 }
Hugo Benichidafed3d2017-03-06 09:17:06 +09004100 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4101 if (e.getValue() == networkCallback) {
4102 reqs.add(e.getKey());
4103 }
4104 }
4105 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4106 for (NetworkRequest r : reqs) {
4107 try {
4108 mService.releaseNetworkRequest(r);
4109 } catch (RemoteException e) {
4110 throw e.rethrowFromSystemServer();
4111 }
4112 // Only remove mapping if rpc was successful.
4113 sCallbacks.remove(r);
4114 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09004115 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004116 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004118
4119 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004120 * Unregisters a callback previously registered via
4121 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4122 *
4123 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4124 * PendingIntent passed to
4125 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4126 * Cannot be null.
4127 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004128 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09004129 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004130 releaseNetworkRequest(operation);
4131 }
4132
4133 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004134 * Informs the system whether it should switch to {@code network} regardless of whether it is
4135 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4136 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4137 * the system default network regardless of any other network that's currently connected. If
4138 * {@code always} is true, then the choice is remembered, so that the next time the user
4139 * connects to this network, the system will switch to it.
4140 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004141 * @param network The network to accept.
4142 * @param accept Whether to accept the network even if unvalidated.
4143 * @param always Whether to remember this choice in the future.
4144 *
4145 * @hide
4146 */
lucasline252a742019-03-12 13:08:03 +08004147 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004148 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4149 try {
4150 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004151 } catch (RemoteException e) {
4152 throw e.rethrowFromSystemServer();
4153 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004154 }
4155
4156 /**
lucasline252a742019-03-12 13:08:03 +08004157 * Informs the system whether it should consider the network as validated even if it only has
4158 * partial connectivity. If {@code accept} is true, then the network will be considered as
4159 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4160 * is remembered, so that the next time the user connects to this network, the system will
4161 * switch to it.
4162 *
4163 * @param network The network to accept.
4164 * @param accept Whether to consider the network as validated even if it has partial
4165 * connectivity.
4166 * @param always Whether to remember this choice in the future.
4167 *
4168 * @hide
4169 */
4170 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4171 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4172 try {
4173 mService.setAcceptPartialConnectivity(network, accept, always);
4174 } catch (RemoteException e) {
4175 throw e.rethrowFromSystemServer();
4176 }
4177 }
4178
4179 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004180 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4181 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4182 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4183 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4184 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004185 * @param network The network to accept.
4186 *
4187 * @hide
4188 */
lucasline252a742019-03-12 13:08:03 +08004189 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004190 public void setAvoidUnvalidated(Network network) {
4191 try {
4192 mService.setAvoidUnvalidated(network);
4193 } catch (RemoteException e) {
4194 throw e.rethrowFromSystemServer();
4195 }
4196 }
4197
4198 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004199 * Requests that the system open the captive portal app on the specified network.
4200 *
4201 * @param network The network to log into.
4202 *
4203 * @hide
4204 */
4205 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
4206 public void startCaptivePortalApp(Network network) {
4207 try {
4208 mService.startCaptivePortalApp(network);
4209 } catch (RemoteException e) {
4210 throw e.rethrowFromSystemServer();
4211 }
4212 }
4213
4214 /**
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004215 * Requests that the system open the captive portal app with the specified extras.
4216 *
4217 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4218 * corresponding permission.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004219 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004220 * @param appExtras Extras to include in the app start intent.
4221 * @hide
4222 */
4223 @SystemApi
4224 @TestApi
4225 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhud9736de2019-03-08 16:35:20 +08004226 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004227 try {
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004228 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004229 } catch (RemoteException e) {
4230 throw e.rethrowFromSystemServer();
4231 }
4232 }
4233
4234 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004235 * Determine whether the device is configured to avoid bad wifi.
4236 * @hide
4237 */
4238 @SystemApi
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004239 @RequiresPermission(anyOf = {
4240 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4241 android.Manifest.permission.NETWORK_STACK})
4242 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004243 try {
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004244 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004245 } catch (RemoteException e) {
4246 throw e.rethrowFromSystemServer();
4247 }
4248 }
4249
4250 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004251 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4252 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09004253 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4254 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004255 *
4256 * An example of such an operation might be a time-sensitive foreground activity, such as a
4257 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4258 */
4259 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4260
4261 /**
4262 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4263 * a backup channel for traffic that is primarily going over another network.
4264 *
4265 * An example might be maintaining backup connections to peers or servers for the purpose of
4266 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4267 * on backup paths should be negligible compared to the traffic on the main path.
4268 */
4269 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4270
4271 /**
4272 * It is acceptable to use metered data to improve network latency and performance.
4273 */
4274 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4275
4276 /**
4277 * Return value to use for unmetered networks. On such networks we currently set all the flags
4278 * to true.
4279 * @hide
4280 */
4281 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4282 MULTIPATH_PREFERENCE_HANDOVER |
4283 MULTIPATH_PREFERENCE_RELIABILITY |
4284 MULTIPATH_PREFERENCE_PERFORMANCE;
4285
4286 /** @hide */
4287 @Retention(RetentionPolicy.SOURCE)
4288 @IntDef(flag = true, value = {
4289 MULTIPATH_PREFERENCE_HANDOVER,
4290 MULTIPATH_PREFERENCE_RELIABILITY,
4291 MULTIPATH_PREFERENCE_PERFORMANCE,
4292 })
4293 public @interface MultipathPreference {
4294 }
4295
4296 /**
4297 * Provides a hint to the calling application on whether it is desirable to use the
4298 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4299 * for multipath data transfer on this network when it is not the system default network.
4300 * Applications desiring to use multipath network protocols should call this method before
4301 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004302 *
4303 * @param network The network on which the application desires to use multipath data.
4304 * If {@code null}, this method will return the a preference that will generally
4305 * apply to metered networks.
4306 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4307 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004308 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004309 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004310 try {
4311 return mService.getMultipathPreference(network);
4312 } catch (RemoteException e) {
4313 throw e.rethrowFromSystemServer();
4314 }
4315 }
4316
4317 /**
Stuart Scott984dc852015-03-30 13:17:11 -07004318 * Resets all connectivity manager settings back to factory defaults.
4319 * @hide
4320 */
4321 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07004322 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07004323 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07004324 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004325 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07004326 }
4327 }
4328
4329 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004330 * Binds the current process to {@code network}. All Sockets created in the future
4331 * (and not explicitly bound via a bound SocketFactory from
4332 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4333 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4334 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4335 * work and all host name resolutions will fail. This is by design so an application doesn't
4336 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4337 * To clear binding pass {@code null} for {@code network}. Using individually bound
4338 * Sockets created by Network.getSocketFactory().createSocket() and
4339 * performing network-specific host name resolutions via
4340 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04004341 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004342 *
4343 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4344 * the current binding.
4345 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4346 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004347 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09004348 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04004349 // instantiated.
4350 return setProcessDefaultNetwork(network);
4351 }
4352
4353 /**
4354 * Binds the current process to {@code network}. All Sockets created in the future
4355 * (and not explicitly bound via a bound SocketFactory from
4356 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4357 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4358 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4359 * work and all host name resolutions will fail. This is by design so an application doesn't
4360 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4361 * To clear binding pass {@code null} for {@code network}. Using individually bound
4362 * Sockets created by Network.getSocketFactory().createSocket() and
4363 * performing network-specific host name resolutions via
4364 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4365 * {@code setProcessDefaultNetwork}.
4366 *
4367 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4368 * the current binding.
4369 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4370 * @deprecated This function can throw {@link IllegalStateException}. Use
4371 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4372 * is a direct replacement.
4373 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004374 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004375 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04004376 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004377 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4378
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09004379 if (netId != NETID_UNSET) {
4380 netId = network.getNetIdForResolv();
Paul Jensenc91b5342014-08-27 12:38:45 -04004381 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004382
4383 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4384 return false;
4385 }
4386
4387 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05004388 // Set HTTP proxy system properties to match network.
4389 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09004390 try {
4391 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4392 } catch (SecurityException e) {
4393 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4394 Log.e(TAG, "Can't set proxy properties", e);
4395 }
Paul Jensenc91b5342014-08-27 12:38:45 -04004396 // Must flush DNS cache as new network may have different DNS resolutions.
4397 InetAddress.clearDnsCache();
4398 // Must flush socket pool as idle sockets will be bound to previous network and may
4399 // cause subsequent fetches to be performed on old network.
4400 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04004401 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004402
4403 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004404 }
4405
4406 /**
4407 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004408 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004409 *
4410 * @return {@code Network} to which this process is bound, or {@code null}.
4411 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004412 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004413 public Network getBoundNetworkForProcess() {
4414 // Forcing callers to call thru non-static function ensures ConnectivityManager
4415 // instantiated.
4416 return getProcessDefaultNetwork();
4417 }
4418
4419 /**
4420 * Returns the {@link Network} currently bound to this process via
4421 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4422 *
4423 * @return {@code Network} to which this process is bound, or {@code null}.
4424 * @deprecated Using this function can lead to other functions throwing
4425 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4426 * {@code getBoundNetworkForProcess} is a direct replacement.
4427 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004428 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004429 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004430 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004431 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004432 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004433 return new Network(netId);
4434 }
4435
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004436 private void unsupportedStartingFrom(int version) {
4437 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004438 // The getApplicationInfo() call we make below is not supported in system context. Let
4439 // the call through here, and rely on the fact that ConnectivityService will refuse to
4440 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004441 return;
4442 }
4443
4444 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4445 throw new UnsupportedOperationException(
4446 "This method is not supported in target SDK version " + version + " and above");
4447 }
4448 }
4449
4450 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4451 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004452 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004453 // remove these exemptions. Note that this check is not secure, and apps can still access these
4454 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4455 // so is unsupported and may break in the future. http://b/22728205
4456 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004457 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004458 }
4459
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004460 /**
4461 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004462 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004463 *
4464 * @param network The {@link Network} to bind host resolutions from the current process to, or
4465 * {@code null} to clear the current binding.
4466 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4467 * @hide
4468 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4469 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004470 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004471 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004472 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004473 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004474 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004475 }
Felipe Leme1b103232016-01-22 09:44:57 -08004476
4477 /**
4478 * Device is not restricting metered network activity while application is running on
4479 * background.
4480 */
4481 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4482
4483 /**
4484 * Device is restricting metered network activity while application is running on background,
4485 * but application is allowed to bypass it.
4486 * <p>
4487 * In this state, application should take action to mitigate metered network access.
4488 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4489 */
4490 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4491
4492 /**
4493 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004494 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004495 * In this state, application should not try to use the network while running on background,
4496 * because it would be denied.
4497 */
4498 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4499
Felipe Leme9778f762016-01-27 14:46:39 -08004500 /**
4501 * A change in the background metered network activity restriction has occurred.
4502 * <p>
4503 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4504 * applies to them.
4505 * <p>
4506 * This is only sent to registered receivers, not manifest receivers.
4507 */
4508 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4509 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4510 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4511
Felipe Lemeecfccea2016-01-25 11:48:04 -08004512 /** @hide */
4513 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004514 @IntDef(flag = false, value = {
4515 RESTRICT_BACKGROUND_STATUS_DISABLED,
4516 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4517 RESTRICT_BACKGROUND_STATUS_ENABLED,
4518 })
Felipe Leme1b103232016-01-22 09:44:57 -08004519 public @interface RestrictBackgroundStatus {
4520 }
4521
4522 private INetworkPolicyManager getNetworkPolicyManager() {
4523 synchronized (this) {
4524 if (mNPManager != null) {
4525 return mNPManager;
4526 }
4527 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4528 .getService(Context.NETWORK_POLICY_SERVICE));
4529 return mNPManager;
4530 }
4531 }
4532
4533 /**
4534 * Determines if the calling application is subject to metered network restrictions while
4535 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004536 *
4537 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4538 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4539 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004540 */
4541 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4542 try {
4543 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4544 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004545 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004546 }
4547 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004548
4549 /**
4550 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004551 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4552 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004553 *
4554 * @return Hash of network watchlist config file. Null if config does not exist.
4555 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004556 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004557 public byte[] getNetworkWatchlistConfigHash() {
4558 try {
4559 return mService.getNetworkWatchlistConfigHash();
4560 } catch (RemoteException e) {
4561 Log.e(TAG, "Unable to get watchlist config hash");
4562 throw e.rethrowFromSystemServer();
4563 }
4564 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004565
4566 /**
4567 * Returns the {@code uid} of the owner of a network connection.
4568 *
4569 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and
4570 * {@code IPPROTO_UDP} currently supported.
4571 * @param local The local {@link InetSocketAddress} of a connection.
4572 * @param remote The remote {@link InetSocketAddress} of a connection.
4573 *
4574 * @return {@code uid} if the connection is found and the app has permission to observe it
4575 * (e.g., if it is associated with the calling VPN app's tunnel) or
4576 * {@link android.os.Process#INVALID_UID} if the connection is not found.
Jeff Vander Stoepb58d3fe2019-02-27 13:31:22 -08004577 * Throws {@link SecurityException} if the caller is not the active VPN for the current user.
4578 * Throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004579 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004580 public int getConnectionOwnerUid(int protocol, @NonNull InetSocketAddress local,
4581 @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004582 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4583 try {
4584 return mService.getConnectionOwnerUid(connectionInfo);
4585 } catch (RemoteException e) {
4586 throw e.rethrowFromSystemServer();
4587 }
4588 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004589
4590 private void printStackTrace() {
4591 if (DEBUG) {
4592 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4593 final StringBuffer sb = new StringBuffer();
4594 for (int i = 3; i < callStack.length; i++) {
4595 final String stackTrace = callStack[i].toString();
4596 if (stackTrace == null || stackTrace.contains("android.os")) {
4597 break;
4598 }
4599 sb.append(" [").append(stackTrace).append("]");
4600 }
4601 Log.d(TAG, "StackLog:" + sb.toString());
4602 }
4603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604}