blob: fad53180128fbc19369829bf53babc04dde47a89 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080016package android.net;
17
junyulai215b8772019-01-15 11:32:44 +080018import static android.net.IpSecManager.INVALID_RESOURCE_ID;
19
junyulai48eac1d42018-12-27 17:25:29 +080020import android.annotation.CallbackExecutor;
Felipe Leme1b103232016-01-22 09:44:57 -080021import android.annotation.IntDef;
Chalard Jean50bea3d2019-01-07 19:26:34 +090022import android.annotation.NonNull;
Robin Lee244ce8e2016-01-05 18:03:46 +000023import android.annotation.Nullable;
Jeff Sharkey30e06bb2017-04-24 11:18:03 -060024import android.annotation.RequiresPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.annotation.SdkConstant;
26import android.annotation.SdkConstant.SdkConstantType;
Udam Sainib7c24872016-01-04 12:16:14 -080027import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060028import android.annotation.SystemService;
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +090029import android.annotation.TestApi;
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010030import android.annotation.UnsupportedAppUsage;
Robert Greenwalt9258c642014-03-26 16:47:06 -070031import android.app.PendingIntent;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070032import android.content.Context;
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070033import android.content.Intent;
junyulai48eac1d42018-12-27 17:25:29 +080034import android.net.IpSecManager.UdpEncapsulationSocket;
35import android.net.SocketKeepalive.Callback;
Robert Greenwalt42acef32009-08-12 16:08:25 -070036import android.os.Binder;
Mathew Inwood55418ea2018-12-20 15:30:45 +000037import android.os.Build;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070038import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080039import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070040import android.os.Handler;
41import android.os.HandlerThread;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080042import android.os.IBinder;
43import android.os.INetworkActivityListener;
44import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070045import android.os.Looper;
46import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070047import android.os.Messenger;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090048import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080050import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080051import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090052import android.os.ServiceSpecificException;
Jeff Sharkey961e3042011-08-29 16:02:57 -070053import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080054import android.telephony.SubscriptionManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080055import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070056import android.util.Log;
Erik Kline35bf06c2017-01-26 18:08:28 +090057import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058
Robert Greenwaltafa05c02014-05-21 20:04:36 -070059import com.android.internal.telephony.ITelephony;
Robert Greenwalt562cc542014-05-15 18:07:26 -070060import com.android.internal.telephony.PhoneConstants;
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;
Felipe Leme1b103232016-01-22 09:44:57 -080067import java.lang.annotation.Retention;
68import java.lang.annotation.RetentionPolicy;
Jeremy Kleind42209d2015-12-28 15:11:58 -080069import java.net.InetAddress;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070070import java.net.InetSocketAddress;
Hugo Benichidafed3d2017-03-06 09:17:06 +090071import java.util.ArrayList;
Jeremy Kleind42209d2015-12-28 15:11:58 -080072import java.util.HashMap;
Hugo Benichidafed3d2017-03-06 09:17:06 +090073import java.util.List;
74import java.util.Map;
junyulai48eac1d42018-12-27 17:25:29 +080075import java.util.concurrent.Executor;
Jeremy Kleind42209d2015-12-28 15:11:58 -080076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077/**
78 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060079 * notifies applications when network connectivity changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 * <p>
81 * The primary responsibilities of this class are to:
82 * <ol>
83 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
84 * <li>Send broadcast intents when network connectivity changes</li>
85 * <li>Attempt to "fail over" to another network when connectivity to a network
86 * is lost</li>
87 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
88 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070089 * <li>Provide an API that allows applications to request and select networks for their data
90 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 * </ol>
92 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060093@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070094public class ConnectivityManager {
95 private static final String TAG = "ConnectivityManager";
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +090096 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070099 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 * been established or lost. The NetworkInfo for the affected network is
101 * sent as an extra; it should be consulted to see what kind of
102 * connectivity event occurred.
103 * <p/>
Mark Lu33ec1062016-12-05 10:57:55 -0800104 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
105 * broadcast if they declare the broadcast receiver in their manifest. Apps
106 * will still receive broadcasts if they register their
107 * {@link android.content.BroadcastReceiver} with
108 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
109 * and that context is still valid.
110 * <p/>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 * If this is a connection that was the result of failing over from a
112 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
113 * set to true.
114 * <p/>
115 * For a loss of connectivity, if the connectivity manager is attempting
116 * to connect (or has already connected) to another network, the
117 * NetworkInfo for the new network is also passed as an extra. This lets
118 * any receivers of the broadcast know that they should not necessarily
119 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800120 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * the failover attempt succeeded (and so there is still overall data
122 * connectivity), or that the failover attempt failed, meaning that all
123 * connectivity has been lost.
124 * <p/>
125 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
126 * is set to {@code true} if there are no connected networks at all.
Chalard Jean054cd162018-02-10 05:33:50 +0900127 *
128 * @deprecated apps should use the more versatile {@link #requestNetwork},
129 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
130 * functions instead for faster and more detailed updates about the network
131 * changes they care about.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800133 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean054cd162018-02-10 05:33:50 +0900134 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 /**
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700138 * A temporary hack until SUPL system can get off the legacy APIS.
139 * They do too many network requests and the long list of apps listening
Chalard Jean4d660112018-06-04 16:52:49 +0900140 * and waking due to the CONNECTIVITY_ACTION broadcast makes it expensive.
141 * Use this broadcast intent instead for SUPL requests.
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700142 * @hide
143 */
144 public static final String CONNECTIVITY_ACTION_SUPL =
145 "android.net.conn.CONNECTIVITY_CHANGE_SUPL";
146
147 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500148 * The device has connected to a network that has presented a captive
149 * portal, which is blocking Internet connectivity. The user was presented
150 * with a notification that network sign in is required,
151 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400152 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500153 * facilitate signing in to the network. This action includes a
154 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
155 * the network presenting the captive portal; all communication with the
156 * captive portal must be done using this {@code Network} object.
157 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400158 * This activity includes a {@link CaptivePortal} extra named
159 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
160 * outcomes of the captive portal sign in to the system:
161 * <ul>
162 * <li> When the app handling this action believes the user has signed in to
163 * the network and the captive portal has been dismissed, the app should
164 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
165 * reevaluate the network. If reevaluation finds the network no longer
166 * subject to a captive portal, the network may become the default active
Chalard Jean4d660112018-06-04 16:52:49 +0900167 * data network.</li>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400168 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500169 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400170 * {@link CaptivePortal#ignoreNetwork}. </li>
171 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500172 */
173 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
174 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
175
176 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 * The lookup key for a {@link NetworkInfo} object. Retrieve with
178 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700179 *
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900180 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
181 * can't accurately represent modern network characteristics.
182 * Please obtain information about networks from the {@link NetworkCapabilities}
183 * or {@link LinkProperties} objects instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700185 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700189 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700190 *
191 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900192 * @deprecated The network type is not rich enough to represent the characteristics
193 * of modern networks. Please use {@link NetworkCapabilities} instead,
194 * in particular the transports.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700195 */
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900196 @Deprecated
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700197 public static final String EXTRA_NETWORK_TYPE = "networkType";
198
199 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 * The lookup key for a boolean that indicates whether a connect event
201 * is for a network to which the connectivity manager was failing over
202 * following a disconnect on another network.
203 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai3822c8a2018-12-13 12:47:51 +0800204 *
205 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 */
junyulai3822c8a2018-12-13 12:47:51 +0800207 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 public static final String EXTRA_IS_FAILOVER = "isFailover";
209 /**
210 * The lookup key for a {@link NetworkInfo} object. This is supplied when
211 * there is another network that it may be possible to connect to. Retrieve with
212 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800213 *
214 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 */
junyulai3822c8a2018-12-13 12:47:51 +0800216 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
218 /**
219 * The lookup key for a boolean that indicates whether there is a
220 * complete lack of connectivity, i.e., no network is available.
221 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
222 */
223 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
224 /**
225 * The lookup key for a string that indicates why an attempt to connect
226 * to a network failed. The string has no particular structure. It is
227 * intended to be used in notifications presented to users. Retrieve
228 * it with {@link android.content.Intent#getStringExtra(String)}.
229 */
230 public static final String EXTRA_REASON = "reason";
231 /**
232 * The lookup key for a string that provides optionally supplied
233 * extra information about the network state. The information
234 * may be passed up from the lower networking layers, and its
235 * meaning may be specific to a particular network type. Retrieve
236 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800237 *
238 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 */
junyulai3822c8a2018-12-13 12:47:51 +0800240 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700242 /**
243 * The lookup key for an int that provides information about
244 * our connection to the internet at large. 0 indicates no connection,
245 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700246 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700247 * {@hide}
248 */
249 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400251 * The lookup key for a {@link CaptivePortal} object included with the
252 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
253 * object can be used to either indicate to the system that the captive
254 * portal has been dismissed or that the user does not want to pursue
255 * signing in to captive portal. Retrieve it with
256 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500257 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400258 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700259
260 /**
261 * Key for passing a URL to the captive portal login activity.
262 */
263 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
264
Paul Jensen25a217c2015-02-27 22:55:47 -0500265 /**
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900266 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
267 * portal login activity.
268 * {@hide}
269 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900270 @SystemApi
271 @TestApi
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900272 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
273 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
274
275 /**
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900276 * Key for passing a user agent string to the captive portal login activity.
277 * {@hide}
278 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900279 @SystemApi
280 @TestApi
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900281 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
282 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
283
284 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700285 * Broadcast action to indicate the change of data activity status
286 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800287 * The network becomes active when data transmission is started, or
288 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700289 * {@hide}
290 */
291 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean4d660112018-06-04 16:52:49 +0900292 public static final String ACTION_DATA_ACTIVITY_CHANGE =
293 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700294 /**
295 * The lookup key for an enum that indicates the network device type on which this data activity
296 * change happens.
297 * {@hide}
298 */
299 public static final String EXTRA_DEVICE_TYPE = "deviceType";
300 /**
301 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
302 * it is actively sending or receiving data and {@code false} means it is idle.
303 * {@hide}
304 */
305 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700306 /**
307 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
308 * {@hide}
309 */
310 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700311
312 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 * Broadcast Action: The setting for background data usage has changed
314 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
315 * <p>
316 * If an application uses the network in the background, it should listen
317 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700318 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800319 * <p>
320 *
321 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
322 * of background data depends on several combined factors, and
323 * this broadcast is no longer sent. Instead, when background
324 * data is unavailable, {@link #getActiveNetworkInfo()} will now
325 * appear disconnected. During first boot after a platform
326 * upgrade, this broadcast will be sent once if
327 * {@link #getBackgroundDataSetting()} was {@code false} before
328 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 */
330 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800331 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
333 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
334
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700335 /**
336 * Broadcast Action: The network connection may not be good
337 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
338 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
339 * the network and it's condition.
340 * @hide
341 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800342 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100343 @UnsupportedAppUsage
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700344 public static final String INET_CONDITION_ACTION =
345 "android.net.conn.INET_CONDITION_ACTION";
346
Robert Greenwalt42acef32009-08-12 16:08:25 -0700347 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800348 * Broadcast Action: A tetherable connection has come or gone.
349 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline8351faa2017-04-17 16:47:23 +0900350 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
351 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800352 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
353 * the current state of tethering. Each include a list of
354 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800355 * @hide
356 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800357 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100358 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800359 public static final String ACTION_TETHER_STATE_CHANGED =
360 "android.net.conn.TETHER_STATE_CHANGED";
361
362 /**
363 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800364 * gives a String[] listing all the interfaces configured for
365 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800366 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100367 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800368 public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800369
370 /**
371 * @hide
Erik Kline8351faa2017-04-17 16:47:23 +0900372 * gives a String[] listing all the interfaces currently in local-only
373 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800374 */
Erik Kline8351faa2017-04-17 16:47:23 +0900375 public static final String EXTRA_ACTIVE_LOCAL_ONLY = "localOnlyArray";
376
377 /**
378 * @hide
379 * gives a String[] listing all the interfaces currently tethered
380 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
381 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100382 @UnsupportedAppUsage
Erik Kline8351faa2017-04-17 16:47:23 +0900383 public static final String EXTRA_ACTIVE_TETHER = "tetherArray";
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800384
385 /**
386 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800387 * gives a String[] listing all the interfaces we tried to tether and
388 * failed. Use {@link #getLastTetherError} to find the error code
389 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800390 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100391 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800392 public static final String EXTRA_ERRORED_TETHER = "erroredArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800393
394 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800395 * Broadcast Action: The captive portal tracker has finished its test.
396 * Sent only while running Setup Wizard, in lieu of showing a user
397 * notification.
398 * @hide
399 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800400 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800401 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
402 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
403 /**
404 * The lookup key for a boolean that indicates whether a captive portal was detected.
405 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
406 * @hide
407 */
408 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
409
410 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900411 * Action used to display a dialog that asks the user whether to connect to a network that is
412 * not validated. This intent is used to start the dialog in settings via startActivity.
413 *
414 * @hide
415 */
416 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
417
418 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900419 * Action used to display a dialog that asks the user whether to avoid a network that is no
420 * longer validated. This intent is used to start the dialog in settings via startActivity.
421 *
422 * @hide
423 */
424 public static final String ACTION_PROMPT_LOST_VALIDATION =
425 "android.net.conn.PROMPT_LOST_VALIDATION";
426
427 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800428 * Invalid tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900429 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800430 * @hide
431 */
432 public static final int TETHERING_INVALID = -1;
433
434 /**
435 * Wifi tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900436 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800437 * @hide
438 */
439 @SystemApi
440 public static final int TETHERING_WIFI = 0;
441
442 /**
443 * USB tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900444 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800445 * @hide
446 */
447 @SystemApi
448 public static final int TETHERING_USB = 1;
449
450 /**
451 * Bluetooth 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_BLUETOOTH = 2;
457
458 /**
459 * Extra used for communicating with the TetherService. Includes the type of tethering to
460 * enable if any.
461 * @hide
462 */
463 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
464
465 /**
466 * Extra used for communicating with the TetherService. Includes the type of tethering for
467 * which to cancel provisioning.
468 * @hide
469 */
470 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
471
472 /**
473 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
474 * provisioning.
475 * @hide
476 */
477 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
478
479 /**
480 * Tells the TetherService to run a provision check now.
481 * @hide
482 */
483 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
484
485 /**
486 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
487 * which will receive provisioning results. Can be left empty.
488 * @hide
489 */
490 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
491
492 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800493 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700494 * @hide
495 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100496 @UnsupportedAppUsage
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700497 public static final int TYPE_NONE = -1;
498
499 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900500 * A Mobile data connection. Devices may support more than one.
501 *
502 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
503 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
504 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700505 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900506 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700507 public static final int TYPE_MOBILE = 0;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900508
Robert Greenwalt42acef32009-08-12 16:08:25 -0700509 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900510 * A WIFI data connection. Devices may support more than one.
511 *
512 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
513 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
514 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700515 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900516 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700517 public static final int TYPE_WIFI = 1;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900518
Robert Greenwalt42acef32009-08-12 16:08:25 -0700519 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800520 * An MMS-specific Mobile data connection. This network type may use the
521 * same network interface as {@link #TYPE_MOBILE} or it may use a different
522 * one. This is used by applications needing to talk to the carrier's
523 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900524 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900525 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900526 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900527 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700528 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700529 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700530 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900531
Robert Greenwalt42acef32009-08-12 16:08:25 -0700532 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800533 * A SUPL-specific Mobile data connection. This network type may use the
534 * same network interface as {@link #TYPE_MOBILE} or it may use a different
535 * one. This is used by applications needing to talk to the carrier's
536 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900537 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900538 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900539 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900540 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700541 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700542 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700543 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900544
Robert Greenwalt42acef32009-08-12 16:08:25 -0700545 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800546 * A DUN-specific Mobile data connection. This network type may use the
547 * same network interface as {@link #TYPE_MOBILE} or it may use a different
548 * one. This is sometimes by the system when setting up an upstream connection
549 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900550 *
551 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
552 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
553 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700554 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900555 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700556 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900557
Robert Greenwalt42acef32009-08-12 16:08:25 -0700558 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800559 * A High Priority Mobile data connection. This network type uses the
560 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900561 * is different.
562 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900563 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
564 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
565 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700566 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700567 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700568 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900569
jsh8214deb2010-03-11 15:04:43 -0800570 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900571 * A WiMAX data connection.
572 *
573 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
574 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
575 * appropriate network. {@see NetworkCapabilities} for supported transports.
jsh8214deb2010-03-11 15:04:43 -0800576 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900577 @Deprecated
jsh8214deb2010-03-11 15:04:43 -0800578 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800579
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800580 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900581 * A Bluetooth data connection.
582 *
583 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
584 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
585 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800586 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900587 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800588 public static final int TYPE_BLUETOOTH = 7;
589
Robert Greenwalt60810842011-04-22 15:28:18 -0700590 /**
591 * Dummy data connection. This should not be used on shipping devices.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900592 * @deprecated This is not used any more.
Robert Greenwalt60810842011-04-22 15:28:18 -0700593 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900594 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800595 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800596
Robert Greenwalt60810842011-04-22 15:28:18 -0700597 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900598 * An Ethernet data connection.
599 *
600 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
601 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
602 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt60810842011-04-22 15:28:18 -0700603 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900604 @Deprecated
Robert Greenwalte12aec92011-01-28 14:48:37 -0800605 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700606
Wink Saville9d7d6282011-03-12 14:52:01 -0800607 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800608 * Over the air Administration.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900609 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800610 * {@hide}
611 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900612 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100613 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800614 public static final int TYPE_MOBILE_FOTA = 10;
615
616 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800617 * IP Multimedia Subsystem.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900618 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800619 * {@hide}
620 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900621 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100622 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800623 public static final int TYPE_MOBILE_IMS = 11;
624
625 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800626 * Carrier Branded Services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900627 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800628 * {@hide}
629 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900630 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100631 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800632 public static final int TYPE_MOBILE_CBS = 12;
633
repo syncaea743a2011-07-29 23:55:49 -0700634 /**
635 * A Wi-Fi p2p connection. Only requesting processes will have access to
636 * the peers connected.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900637 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncaea743a2011-07-29 23:55:49 -0700638 * {@hide}
639 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900640 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100641 @UnsupportedAppUsage
repo syncaea743a2011-07-29 23:55:49 -0700642 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800643
Wink Saville5e56bc52013-07-29 15:00:57 -0700644 /**
645 * The network to use for initially attaching to the network
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900646 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville5e56bc52013-07-29 15:00:57 -0700647 * {@hide}
648 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900649 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100650 @UnsupportedAppUsage
Wink Saville5e56bc52013-07-29 15:00:57 -0700651 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700652
Lorenzo Colittie285b432015-04-23 15:32:42 +0900653 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700654 * Emergency PDN connection for emergency services. This
655 * may include IMS and MMS in emergency situations.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900656 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram3e0e3bc2014-06-26 11:03:44 -0700657 * {@hide}
658 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900659 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100660 @UnsupportedAppUsage
Ram3e0e3bc2014-06-26 11:03:44 -0700661 public static final int TYPE_MOBILE_EMERGENCY = 15;
662
Hui Lu1c5624a2014-01-15 11:05:36 -0500663 /**
664 * The network that uses proxy to achieve connectivity.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900665 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu1c5624a2014-01-15 11:05:36 -0500666 * {@hide}
667 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900668 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100669 @UnsupportedAppUsage
Hui Lu1c5624a2014-01-15 11:05:36 -0500670 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700671
Robert Greenwalt8283f882014-07-07 17:09:01 -0700672 /**
673 * A virtual network using one or more native bearers.
674 * It may or may not be providing security services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900675 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700676 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900677 @Deprecated
Robert Greenwalt8283f882014-07-07 17:09:01 -0700678 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500679
680 /** {@hide} */
Robert Greenwalt8283f882014-07-07 17:09:01 -0700681 public static final int MAX_RADIO_TYPE = TYPE_VPN;
682
683 /** {@hide} */
684 public static final int MAX_NETWORK_TYPE = TYPE_VPN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685
Hugo Benichi16f0a942017-06-20 14:07:59 +0900686 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
687
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800688 /**
689 * If you want to set the default network preference,you can directly
690 * change the networkAttributes array in framework's config.xml.
691 *
692 * @deprecated Since we support so many more networks now, the single
693 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800694 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800695 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800696 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800697 * from an App.
698 */
699 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
701
Jeff Sharkey625239a2012-09-26 22:03:49 -0700702 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700703 * @hide
704 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900705 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700706
Paul Jensen5d59e782014-07-11 12:28:19 -0400707 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900708 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
709 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean4d660112018-06-04 16:52:49 +0900710 * registered from those that were already unregistered.
Hugo Benichi31c176d2017-06-17 13:14:12 +0900711 * @hide
712 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900713 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900714 new NetworkRequest.Builder().clearCapabilities().build();
715
716 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400717 * A NetID indicating no Network is selected.
718 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
719 * @hide
720 */
721 public static final int NETID_UNSET = 0;
722
Erik Kline4d092232017-10-30 15:29:44 +0900723 /**
724 * Private DNS Mode values.
725 *
726 * The "private_dns_mode" global setting stores a String value which is
727 * expected to be one of the following.
728 */
729
730 /**
731 * @hide
732 */
733 public static final String PRIVATE_DNS_MODE_OFF = "off";
734 /**
735 * @hide
736 */
737 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
738 /**
739 * @hide
740 */
741 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
742 /**
743 * The default Private DNS mode.
744 *
745 * This may change from release to release or may become dependent upon
746 * the capabilities of the underlying platform.
747 *
748 * @hide
749 */
Erik Kline19841792018-05-16 16:41:57 +0900750 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline4d092232017-10-30 15:29:44 +0900751
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100752 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700753 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500754 /**
755 * A kludge to facilitate static access where a Context pointer isn't available, like in the
756 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
757 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
758 * methods that take a Context argument.
759 */
760 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900762 private final Context mContext;
763
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800764 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800765 private INetworkPolicyManager mNPManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800766
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800767 /**
768 * Tests if a given integer represents a valid network type.
769 * @param networkType the type to be tested
770 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400771 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
772 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800773 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700774 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700775 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900776 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
778
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800779 /**
780 * Returns a non-localized string representing a given network type.
781 * ONLY used for debugging output.
782 * @param type the type needing naming
783 * @return a String for the given type, or a string version of the type ("87")
784 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900785 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800786 * {@hide}
787 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900788 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100789 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700790 public static String getNetworkTypeName(int type) {
791 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900792 case TYPE_NONE:
793 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700794 case TYPE_MOBILE:
795 return "MOBILE";
796 case TYPE_WIFI:
797 return "WIFI";
798 case TYPE_MOBILE_MMS:
799 return "MOBILE_MMS";
800 case TYPE_MOBILE_SUPL:
801 return "MOBILE_SUPL";
802 case TYPE_MOBILE_DUN:
803 return "MOBILE_DUN";
804 case TYPE_MOBILE_HIPRI:
805 return "MOBILE_HIPRI";
806 case TYPE_WIMAX:
807 return "WIMAX";
808 case TYPE_BLUETOOTH:
809 return "BLUETOOTH";
810 case TYPE_DUMMY:
811 return "DUMMY";
812 case TYPE_ETHERNET:
813 return "ETHERNET";
814 case TYPE_MOBILE_FOTA:
815 return "MOBILE_FOTA";
816 case TYPE_MOBILE_IMS:
817 return "MOBILE_IMS";
818 case TYPE_MOBILE_CBS:
819 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700820 case TYPE_WIFI_P2P:
821 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700822 case TYPE_MOBILE_IA:
823 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700824 case TYPE_MOBILE_EMERGENCY:
825 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500826 case TYPE_PROXY:
827 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900828 case TYPE_VPN:
829 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700830 default:
831 return Integer.toString(type);
832 }
833 }
834
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800835 /**
836 * Checks if a given type uses the cellular data connection.
837 * This should be replaced in the future by a network property.
838 * @param networkType the type to check
839 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900840 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800841 * {@hide}
842 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900843 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100844 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700845 public static boolean isNetworkTypeMobile(int networkType) {
846 switch (networkType) {
847 case TYPE_MOBILE:
848 case TYPE_MOBILE_MMS:
849 case TYPE_MOBILE_SUPL:
850 case TYPE_MOBILE_DUN:
851 case TYPE_MOBILE_HIPRI:
852 case TYPE_MOBILE_FOTA:
853 case TYPE_MOBILE_IMS:
854 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700855 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700856 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700857 return true;
858 default:
859 return false;
860 }
861 }
862
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800863 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700864 * Checks if the given network type is backed by a Wi-Fi radio.
865 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900866 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700867 * @hide
868 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900869 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700870 public static boolean isNetworkTypeWifi(int networkType) {
871 switch (networkType) {
872 case TYPE_WIFI:
873 case TYPE_WIFI_P2P:
874 return true;
875 default:
876 return false;
877 }
878 }
879
880 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800881 * Specifies the preferred network type. When the device has more
882 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800883 *
884 * @param preference the network type to prefer over all others. It is
885 * unspecified what happens to the old preferred network in the
886 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700887 * @deprecated Functionality has been removed as it no longer makes sense,
888 * with many more than two networks - we'd need an array to express
889 * preference. Instead we use dynamic network properties of
890 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800891 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700892 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
895
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800896 /**
897 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800898 *
899 * @return an integer representing the preferred network type
900 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700901 * @deprecated Functionality has been removed as it no longer makes sense,
902 * with many more than two networks - we'd need an array to express
903 * preference. Instead we use dynamic network properties of
904 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800905 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700906 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600907 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700909 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
911
Scott Main671644c2011-10-06 19:02:28 -0700912 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800913 * Returns details about the currently active default data network. When
914 * connected, this network is the default route for outgoing connections.
915 * You should always check {@link NetworkInfo#isConnected()} before initiating
916 * network traffic. This may return {@code null} when there is no default
917 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900918 * Note that if the default network is a VPN, this method will return the
919 * NetworkInfo for one of its underlying networks instead, or null if the
920 * VPN agent did not specify any. Apps interested in learning about VPNs
921 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800922 *
923 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500924 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800925 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700926 */
junyulai3822c8a2018-12-13 12:47:51 +0800927 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600928 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900929 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 public NetworkInfo getActiveNetworkInfo() {
931 try {
932 return mService.getActiveNetworkInfo();
933 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700934 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936 }
937
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800938 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500939 * Returns a {@link Network} object corresponding to the currently active
940 * default data network. In the event that the current active default data
941 * network disconnects, the returned {@code Network} object will no longer
942 * be usable. This will return {@code null} when there is no default
943 * network.
944 *
945 * @return a {@link Network} object for the current default network or
946 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500947 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600948 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900949 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -0500950 public Network getActiveNetwork() {
951 try {
952 return mService.getActiveNetwork();
953 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700954 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500955 }
956 }
957
958 /**
Robin Leed2baf792016-03-24 12:07:00 +0000959 * Returns a {@link Network} object corresponding to the currently active
960 * default data network for a specific UID. In the event that the default data
961 * network disconnects, the returned {@code Network} object will no longer
962 * be usable. This will return {@code null} when there is no default
963 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +0000964 *
965 * @return a {@link Network} object for the current default network for the
966 * given UID or {@code null} if no default network is currently active
967 *
968 * @hide
969 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600970 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900971 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +0000972 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600973 return getActiveNetworkForUid(uid, false);
974 }
975
976 /** {@hide} */
977 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +0000978 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600979 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +0000980 } catch (RemoteException e) {
981 throw e.rethrowFromSystemServer();
982 }
983 }
984
985 /**
Charles He36738632017-05-15 17:07:18 +0100986 * Checks if a VPN app supports always-on mode.
987 *
988 * In order to support the always-on feature, an app has to
989 * <ul>
990 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +0100991 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
992 * meta-data field.
Charles He36738632017-05-15 17:07:18 +0100993 * </ul>
994 *
995 * @param userId The identifier of the user for whom the VPN app is installed.
996 * @param vpnPackage The canonical package name of the VPN app.
997 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
998 * @hide
999 */
1000 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1001 try {
1002 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1003 } catch (RemoteException e) {
1004 throw e.rethrowFromSystemServer();
1005 }
1006 }
1007
1008 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001009 * Configures an always-on VPN connection through a specific application.
1010 * This connection is automatically granted and persisted after a reboot.
1011 *
1012 * <p>The designated package should declare a {@link VpnService} in its
1013 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1014 * otherwise the call will fail.
1015 *
1016 * @param userId The identifier of the user to set an always-on VPN for.
1017 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1018 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001019 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1020 * {@code false} otherwise.
Pavel Grafova462bcb2019-01-25 08:50:06 +00001021 * @param lockdownWhitelist The list of packages that are allowed to access network directly
1022 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
1023 * this method must be called when a package that should be whitelisted is installed or
1024 * uninstalled.
Robin Lee244ce8e2016-01-05 18:03:46 +00001025 * @return {@code true} if the package is set as always-on VPN controller;
1026 * {@code false} otherwise.
1027 * @hide
1028 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001029 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leedc679712016-05-03 13:23:03 +01001030 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001031 boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001032 try {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001033 return mService.setAlwaysOnVpnPackage(
1034 userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
Robin Lee244ce8e2016-01-05 18:03:46 +00001035 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001036 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001037 }
1038 }
1039
Pavel Grafova462bcb2019-01-25 08:50:06 +00001040 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001041 * Returns the package name of the currently set always-on VPN application.
1042 * If there is no always-on VPN set, or the VPN is provided by the system instead
1043 * of by an app, {@code null} will be returned.
1044 *
1045 * @return Package name of VPN controller responsible for always-on VPN,
1046 * or {@code null} if none is set.
1047 * @hide
1048 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001049 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee244ce8e2016-01-05 18:03:46 +00001050 public String getAlwaysOnVpnPackageForUser(int userId) {
1051 try {
1052 return mService.getAlwaysOnVpnPackage(userId);
1053 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001054 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001055 }
1056 }
1057
1058 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001059 * @return whether always-on VPN is in lockdown mode.
1060 *
1061 * @hide
1062 **/
1063 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1064 public boolean isVpnLockdownEnabled(int userId) {
1065 try {
1066 return mService.isVpnLockdownEnabled(userId);
1067 } catch (RemoteException e) {
1068 throw e.rethrowFromSystemServer();
1069 }
1070
1071 }
1072
1073 /**
1074 * @return the list of packages that are allowed to access network when always-on VPN is in
1075 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1076 *
1077 * @hide
1078 **/
1079 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1080 public List<String> getVpnLockdownWhitelist(int userId) {
1081 try {
1082 return mService.getVpnLockdownWhitelist(userId);
1083 } catch (RemoteException e) {
1084 throw e.rethrowFromSystemServer();
1085 }
1086 }
1087
1088 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001089 * Returns details about the currently active default data network
1090 * for a given uid. This is for internal use only to avoid spying
1091 * other apps.
1092 *
1093 * @return a {@link NetworkInfo} object for the current default network
1094 * for the given uid or {@code null} if no default network is
1095 * available for the specified uid.
1096 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001097 * {@hide}
1098 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001099 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001100 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001101 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001102 return getActiveNetworkInfoForUid(uid, false);
1103 }
1104
1105 /** {@hide} */
1106 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001107 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001108 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001109 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001110 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 }
1112 }
1113
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001114 /**
1115 * Returns connection status information about a particular
1116 * network type.
1117 *
1118 * @param networkType integer specifying which networkType in
1119 * which you're interested.
1120 * @return a {@link NetworkInfo} object for the requested
1121 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001122 * supported by the device. If {@code networkType} is
1123 * TYPE_VPN and a VPN is active for the calling app,
1124 * then this method will try to return one of the
1125 * underlying networks for the VPN or null if the
1126 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001127 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001128 * @deprecated This method does not support multiple connected networks
1129 * of the same type. Use {@link #getAllNetworks} and
1130 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001131 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001132 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001133 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001134 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 public NetworkInfo getNetworkInfo(int networkType) {
1136 try {
1137 return mService.getNetworkInfo(networkType);
1138 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001139 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
1141 }
1142
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001143 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001144 * Returns connection status information about a particular
1145 * Network.
1146 *
1147 * @param network {@link Network} specifying which network
1148 * in which you're interested.
1149 * @return a {@link NetworkInfo} object for the requested
1150 * network or {@code null} if the {@code Network}
1151 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001152 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001153 */
junyulai3822c8a2018-12-13 12:47:51 +08001154 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001155 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001156 @Nullable
1157 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001158 return getNetworkInfoForUid(network, Process.myUid(), false);
1159 }
1160
1161 /** {@hide} */
1162 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001163 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001164 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001165 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001166 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001167 }
1168 }
1169
1170 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001171 * Returns connection status information about all network
1172 * types supported by the device.
1173 *
1174 * @return an array of {@link NetworkInfo} objects. Check each
1175 * {@link NetworkInfo#getType} for which type each applies.
1176 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001177 * @deprecated This method does not support multiple connected networks
1178 * of the same type. Use {@link #getAllNetworks} and
1179 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001180 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001181 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001182 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001183 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 public NetworkInfo[] getAllNetworkInfo() {
1185 try {
1186 return mService.getAllNetworkInfo();
1187 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001188 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
1190 }
1191
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001192 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001193 * Returns the {@link Network} object currently serving a given type, or
1194 * null if the given type is not connected.
1195 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001196 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001197 * @deprecated This method does not support multiple connected networks
1198 * of the same type. Use {@link #getAllNetworks} and
1199 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001200 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001201 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001202 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001203 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001204 public Network getNetworkForType(int networkType) {
1205 try {
1206 return mService.getNetworkForType(networkType);
1207 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001208 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001209 }
1210 }
1211
1212 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001213 * Returns an array of all {@link Network} currently tracked by the
1214 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001215 *
1216 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001217 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001218 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001219 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001220 public Network[] getAllNetworks() {
1221 try {
1222 return mService.getAllNetworks();
1223 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001224 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001225 }
1226 }
1227
1228 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001229 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001230 * the Networks that applications run by the given user will use by default.
1231 * @hide
1232 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001233 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001234 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1235 try {
1236 return mService.getDefaultNetworkCapabilitiesForUser(userId);
1237 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001238 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001239 }
1240 }
1241
1242 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001243 * Returns the IP information for the current default network.
1244 *
1245 * @return a {@link LinkProperties} object describing the IP info
1246 * for the current default network, or {@code null} if there
1247 * is no current default network.
1248 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001249 * {@hide}
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001250 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1251 * value of {@link #getActiveNetwork()} instead. In particular,
1252 * this method will return non-null LinkProperties even if the
1253 * app is blocked by policy from using this network.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001254 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001255 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001256 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001257 public LinkProperties getActiveLinkProperties() {
1258 try {
1259 return mService.getActiveLinkProperties();
1260 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001261 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001262 }
1263 }
1264
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001265 /**
1266 * Returns the IP information for a given network type.
1267 *
1268 * @param networkType the network type of interest.
1269 * @return a {@link LinkProperties} object describing the IP info
1270 * for the given networkType, or {@code null} if there is
1271 * no current default network.
1272 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001273 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001274 * @deprecated This method does not support multiple connected networks
1275 * of the same type. Use {@link #getAllNetworks},
1276 * {@link #getNetworkInfo(android.net.Network)}, and
1277 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001278 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001279 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001280 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001281 @UnsupportedAppUsage
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001282 public LinkProperties getLinkProperties(int networkType) {
1283 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001284 return mService.getLinkPropertiesForType(networkType);
1285 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001286 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001287 }
1288 }
1289
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001290 /**
1291 * Get the {@link LinkProperties} for the given {@link Network}. This
1292 * will return {@code null} if the network is unknown.
1293 *
1294 * @param network The {@link Network} object identifying the network in question.
1295 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001296 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001297 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001298 @Nullable
1299 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001300 try {
1301 return mService.getLinkProperties(network);
1302 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001303 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001304 }
1305 }
1306
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001307 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001308 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001309 * will return {@code null} if the network is unknown.
1310 *
1311 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001312 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001313 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001314 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001315 @Nullable
1316 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001317 try {
1318 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001319 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001320 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001321 }
1322 }
1323
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001324 /**
Udam Sainib7c24872016-01-04 12:16:14 -08001325 * Gets the URL that should be used for resolving whether a captive portal is present.
1326 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1327 * portal is present.
1328 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1329 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1330 *
1331 * @hide
1332 */
1333 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07001334 @RequiresPermission(android.Manifest.permission.LOCAL_MAC_ADDRESS)
Udam Sainib7c24872016-01-04 12:16:14 -08001335 public String getCaptivePortalServerUrl() {
1336 try {
1337 return mService.getCaptivePortalServerUrl();
1338 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001339 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001340 }
1341 }
1342
1343 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 * Tells the underlying networking system that the caller wants to
1345 * begin using the named feature. The interpretation of {@code feature}
1346 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001347 *
1348 * <p>This method requires the caller to hold either the
1349 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1350 * or the ability to modify system settings as determined by
1351 * {@link android.provider.Settings.System#canWrite}.</p>
1352 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 * @param networkType specifies which network the request pertains to
1354 * @param feature the name of the feature to be used
1355 * @return an integer value representing the outcome of the request.
1356 * The interpretation of this value is specific to each networking
1357 * implementation+feature combination, except that the value {@code -1}
1358 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001359 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001360 * @deprecated Deprecated in favor of the cleaner
1361 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001362 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001363 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001364 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001366 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001368 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001369 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1370 if (netCap == null) {
1371 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1372 feature);
1373 return PhoneConstants.APN_REQUEST_FAILED;
1374 }
1375
1376 NetworkRequest request = null;
1377 synchronized (sLegacyRequests) {
1378 LegacyRequest l = sLegacyRequests.get(netCap);
1379 if (l != null) {
1380 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1381 renewRequestLocked(l);
1382 if (l.currentNetwork != null) {
1383 return PhoneConstants.APN_ALREADY_ACTIVE;
1384 } else {
1385 return PhoneConstants.APN_REQUEST_STARTED;
1386 }
1387 }
1388
1389 request = requestNetworkForFeatureLocked(netCap);
1390 }
1391 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001392 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001393 return PhoneConstants.APN_REQUEST_STARTED;
1394 } else {
1395 Log.d(TAG, " request Failed");
1396 return PhoneConstants.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 }
1398 }
1399
1400 /**
1401 * Tells the underlying networking system that the caller is finished
1402 * using the named feature. The interpretation of {@code feature}
1403 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001404 *
1405 * <p>This method requires the caller to hold either the
1406 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1407 * or the ability to modify system settings as determined by
1408 * {@link android.provider.Settings.System#canWrite}.</p>
1409 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 * @param networkType specifies which network the request pertains to
1411 * @param feature the name of the feature that is no longer needed
1412 * @return an integer value representing the outcome of the request.
1413 * The interpretation of this value is specific to each networking
1414 * implementation+feature combination, except that the value {@code -1}
1415 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001416 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001417 * @deprecated Deprecated in favor of the cleaner
1418 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001419 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001420 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001421 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001423 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001425 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001426 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1427 if (netCap == null) {
1428 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1429 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 return -1;
1431 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001432
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001433 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001434 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001435 }
1436 return 1;
1437 }
1438
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001439 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001440 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1441 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001442 switch (feature) {
1443 case "enableCBS":
1444 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1445 case "enableDUN":
1446 case "enableDUNAlways":
1447 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1448 case "enableFOTA":
1449 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1450 case "enableHIPRI":
1451 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1452 case "enableIMS":
1453 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1454 case "enableMMS":
1455 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1456 case "enableSUPL":
1457 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1458 default:
1459 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001460 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001461 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1462 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001463 }
1464 return null;
1465 }
1466
Robert Greenwalt06314e42014-10-29 14:04:06 -07001467 /**
1468 * Guess what the network request was trying to say so that the resulting
1469 * network is accessible via the legacy (deprecated) API such as
1470 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001471 *
1472 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001473 * capability but ignore things such as networkSpecifier.
1474 * If the request has more than one transport or capability it doesn't
1475 * match the old legacy requests (they selected only single transport/capability)
1476 * so this function cannot map the request to a single legacy type and
1477 * the resulting network will not be available to the legacy APIs.
1478 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001479 * This code is only called from the requestNetwork API (L and above).
1480 *
1481 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1482 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1483 * do this for SUPL requests, which are the only ones that we know need it. If
1484 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1485 * compatibility we can send them:
1486 *
1487 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1488 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1489 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001490 * TODO - This should be removed when the legacy APIs are removed.
1491 */
Ye Wenb87875e2014-07-21 14:19:01 -07001492 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1493 if (netCap == null) {
1494 return TYPE_NONE;
1495 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001496
Ye Wenb87875e2014-07-21 14:19:01 -07001497 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1498 return TYPE_NONE;
1499 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001500
Lifu Tang30f95a72016-01-07 23:20:38 -08001501 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001502 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1503 // NOTE: if this causes app breakage, we should not just comment out this early return;
1504 // instead, we should make this early return conditional on the requesting app's target
1505 // SDK version, as described in the comment above.
1506 return TYPE_NONE;
1507 }
1508
Robert Greenwalt06314e42014-10-29 14:04:06 -07001509 String type = null;
1510 int result = TYPE_NONE;
1511
Ye Wenb87875e2014-07-21 14:19:01 -07001512 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001513 type = "enableCBS";
1514 result = TYPE_MOBILE_CBS;
1515 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1516 type = "enableIMS";
1517 result = TYPE_MOBILE_IMS;
1518 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1519 type = "enableFOTA";
1520 result = TYPE_MOBILE_FOTA;
1521 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1522 type = "enableDUN";
1523 result = TYPE_MOBILE_DUN;
1524 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001525 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001526 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001527 // back out this hack for mms as they no longer need this and it's causing
1528 // device slowdowns - b/23350688 (note, supl still needs this)
1529 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1530 // type = "enableMMS";
1531 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001532 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1533 type = "enableHIPRI";
1534 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001535 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001536 if (type != null) {
1537 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1538 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1539 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001540 }
1541 }
1542 return TYPE_NONE;
1543 }
1544
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001545 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001546 if (netCap == null) return TYPE_NONE;
1547 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1548 return TYPE_MOBILE_CBS;
1549 }
1550 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1551 return TYPE_MOBILE_IMS;
1552 }
1553 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1554 return TYPE_MOBILE_FOTA;
1555 }
1556 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1557 return TYPE_MOBILE_DUN;
1558 }
1559 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1560 return TYPE_MOBILE_SUPL;
1561 }
1562 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1563 return TYPE_MOBILE_MMS;
1564 }
1565 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1566 return TYPE_MOBILE_HIPRI;
1567 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001568 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1569 return TYPE_WIFI_P2P;
1570 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001571 return TYPE_NONE;
1572 }
1573
1574 private static class LegacyRequest {
1575 NetworkCapabilities networkCapabilities;
1576 NetworkRequest networkRequest;
1577 int expireSequenceNumber;
1578 Network currentNetwork;
1579 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001580
1581 private void clearDnsBinding() {
1582 if (currentNetwork != null) {
1583 currentNetwork = null;
1584 setProcessDefaultNetworkForHostResolution(null);
1585 }
1586 }
1587
Robert Greenwalt6078b502014-06-11 16:05:07 -07001588 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001589 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001590 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001591 currentNetwork = network;
1592 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001593 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001594 }
1595 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001596 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001597 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001598 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1599 }
1600 };
1601 }
1602
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001603 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001604 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1605 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001606
1607 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1608 synchronized (sLegacyRequests) {
1609 LegacyRequest l = sLegacyRequests.get(netCap);
1610 if (l != null) return l.networkRequest;
1611 }
1612 return null;
1613 }
1614
1615 private void renewRequestLocked(LegacyRequest l) {
1616 l.expireSequenceNumber++;
1617 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1618 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1619 }
1620
1621 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1622 int ourSeqNum = -1;
1623 synchronized (sLegacyRequests) {
1624 LegacyRequest l = sLegacyRequests.get(netCap);
1625 if (l == null) return;
1626 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001627 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001628 }
1629 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1630 }
1631
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001632 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001633 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1634 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001635 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001636 try {
1637 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001638 } catch (RemoteException e) {
1639 throw e.rethrowFromSystemServer();
1640 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001641 LegacyRequest l = new LegacyRequest();
1642 l.networkCapabilities = netCap;
1643 l.delay = delay;
1644 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001645 l.networkRequest = sendRequestForNetwork(
1646 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001647 if (l.networkRequest == null) return null;
1648 sLegacyRequests.put(netCap, l);
1649 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1650 return l.networkRequest;
1651 }
1652
1653 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1654 if (delay >= 0) {
1655 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001656 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001657 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1658 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001659 }
1660 }
1661
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001662 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001663 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1664 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001665 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001666 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001667 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001668 if (l == null) return false;
1669 unregisterNetworkCallback(l.networkCallback);
1670 l.clearDnsBinding();
1671 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673
Erik Kline35bf06c2017-01-26 18:08:28 +09001674 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1675 static {
1676 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1677 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1678 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1679 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1680 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1681 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1682 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1683 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1684 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1685 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1686 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1687 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1688 }
1689
1690 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1691 static {
1692 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1693 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1694 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1695 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1696 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1697 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1698 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1699 }
1700
1701 /**
1702 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1703 * instance suitable for registering a request or callback. Throws an
1704 * IllegalArgumentException if no mapping from the legacy type to
1705 * NetworkCapabilities is known.
1706 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001707 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1708 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001709 * @hide
1710 */
1711 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1712 final NetworkCapabilities nc = new NetworkCapabilities();
1713
1714 // Map from type to transports.
1715 final int NOT_FOUND = -1;
1716 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001717 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001718 nc.addTransportType(transport);
1719
1720 // Map from type to capabilities.
1721 nc.addCapability(sLegacyTypeToCapability.get(
1722 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1723 nc.maybeMarkCapabilitiesRestricted();
1724 return nc;
1725 }
1726
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001727 /** @hide */
1728 public static class PacketKeepaliveCallback {
1729 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001730 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001731 public void onStarted() {}
1732 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001733 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001734 public void onStopped() {}
1735 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001736 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001737 public void onError(int error) {}
1738 }
1739
1740 /**
1741 * Allows applications to request that the system periodically send specific packets on their
1742 * behalf, using hardware offload to save battery power.
1743 *
1744 * To request that the system send keepalives, call one of the methods that return a
1745 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1746 * passing in a non-null callback. If the callback is successfully started, the callback's
1747 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1748 * specifying one of the {@code ERROR_*} constants in this class.
1749 *
Chalard Jean4d660112018-06-04 16:52:49 +09001750 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1751 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1752 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001753 *
junyulai48eac1d42018-12-27 17:25:29 +08001754 * @deprecated Use {@link SocketKeepalive} instead.
1755 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001756 * @hide
1757 */
1758 public class PacketKeepalive {
1759
1760 private static final String TAG = "PacketKeepalive";
1761
1762 /** @hide */
1763 public static final int SUCCESS = 0;
1764
1765 /** @hide */
1766 public static final int NO_KEEPALIVE = -1;
1767
1768 /** @hide */
1769 public static final int BINDER_DIED = -10;
1770
1771 /** The specified {@code Network} is not connected. */
1772 public static final int ERROR_INVALID_NETWORK = -20;
1773 /** The specified IP addresses are invalid. For example, the specified source IP address is
1774 * not configured on the specified {@code Network}. */
1775 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1776 /** The requested port is invalid. */
1777 public static final int ERROR_INVALID_PORT = -22;
1778 /** The packet length is invalid (e.g., too long). */
1779 public static final int ERROR_INVALID_LENGTH = -23;
1780 /** The packet transmission interval is invalid (e.g., too short). */
1781 public static final int ERROR_INVALID_INTERVAL = -24;
1782
1783 /** The hardware does not support this request. */
1784 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001785 /** The hardware returned an error. */
1786 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001787
Nathan Harold63dd8132018-02-14 13:09:45 -08001788 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001789 public static final int NATT_PORT = 4500;
1790
Nathan Harold63dd8132018-02-14 13:09:45 -08001791 /** The minimum interval in seconds between keepalive packet transmissions */
1792 public static final int MIN_INTERVAL = 10;
1793
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001794 private final Network mNetwork;
1795 private final PacketKeepaliveCallback mCallback;
1796 private final Looper mLooper;
1797 private final Messenger mMessenger;
1798
1799 private volatile Integer mSlot;
1800
1801 void stopLooper() {
1802 mLooper.quit();
1803 }
1804
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001805 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001806 public void stop() {
1807 try {
1808 mService.stopKeepalive(mNetwork, mSlot);
1809 } catch (RemoteException e) {
1810 Log.e(TAG, "Error stopping packet keepalive: ", e);
1811 stopLooper();
1812 }
1813 }
1814
1815 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001816 Preconditions.checkNotNull(network, "network cannot be null");
1817 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001818 mNetwork = network;
1819 mCallback = callback;
1820 HandlerThread thread = new HandlerThread(TAG);
1821 thread.start();
1822 mLooper = thread.getLooper();
1823 mMessenger = new Messenger(new Handler(mLooper) {
1824 @Override
1825 public void handleMessage(Message message) {
1826 switch (message.what) {
junyulai06835112019-01-03 18:50:15 +08001827 case NetworkAgent.EVENT_SOCKET_KEEPALIVE:
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001828 int error = message.arg2;
1829 try {
1830 if (error == SUCCESS) {
1831 if (mSlot == null) {
1832 mSlot = message.arg1;
1833 mCallback.onStarted();
1834 } else {
1835 mSlot = null;
1836 stopLooper();
1837 mCallback.onStopped();
1838 }
1839 } else {
1840 stopLooper();
1841 mCallback.onError(error);
1842 }
1843 } catch (Exception e) {
1844 Log.e(TAG, "Exception in keepalive callback(" + error + ")", e);
1845 }
1846 break;
1847 default:
1848 Log.e(TAG, "Unhandled message " + Integer.toHexString(message.what));
1849 break;
1850 }
1851 }
1852 });
1853 }
1854 }
1855
1856 /**
1857 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1858 *
junyulai48eac1d42018-12-27 17:25:29 +08001859 * @deprecated Use {@link #createSocketKeepalive} instead.
1860 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001861 * @hide
1862 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001863 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001864 public PacketKeepalive startNattKeepalive(
1865 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1866 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1867 final PacketKeepalive k = new PacketKeepalive(network, callback);
1868 try {
1869 mService.startNattKeepalive(network, intervalSeconds, k.mMessenger, new Binder(),
1870 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1871 } catch (RemoteException e) {
1872 Log.e(TAG, "Error starting packet keepalive: ", e);
1873 k.stopLooper();
1874 return null;
1875 }
1876 return k;
1877 }
1878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 /**
junyulai48eac1d42018-12-27 17:25:29 +08001880 * Request that keepalives be started on a IPsec NAT-T socket.
1881 *
1882 * @param network The {@link Network} the socket is on.
1883 * @param socket The socket that needs to be kept alive.
1884 * @param source The source address of the {@link UdpEncapsulationSocket}.
1885 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1886 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1887 * must run callback sequentially, otherwise the order of callbacks cannot be
1888 * guaranteed.
1889 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1890 * changes. Must be extended by applications that use this API.
1891 *
1892 * @return A {@link SocketKeepalive} object, which can be used to control this keepalive object.
1893 **/
1894 public SocketKeepalive createSocketKeepalive(@NonNull Network network,
1895 @NonNull UdpEncapsulationSocket socket,
1896 @NonNull InetAddress source,
1897 @NonNull InetAddress destination,
1898 @NonNull @CallbackExecutor Executor executor,
1899 @NonNull Callback callback) {
junyulai215b8772019-01-15 11:32:44 +08001900 return new NattSocketKeepalive(mService, network, socket.getFileDescriptor(),
1901 socket.getResourceId(), source, destination, executor, callback);
1902 }
1903
1904 /**
1905 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1906 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1907 *
1908 * @param network The {@link Network} the socket is on.
1909 * @param fd The {@link FileDescriptor} that needs to be kept alive. The provided
1910 * {@link FileDescriptor} must be bound to a port and the keepalives will be sent from
1911 * that port.
1912 * @param source The source address of the {@link UdpEncapsulationSocket}.
1913 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1914 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1915 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1916 * must run callback sequentially, otherwise the order of callbacks cannot be
1917 * guaranteed.
1918 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1919 * changes. Must be extended by applications that use this API.
1920 *
1921 * @hide
1922 */
1923 @SystemApi
1924 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
1925 public SocketKeepalive createNattKeepalive(@NonNull Network network,
1926 @NonNull FileDescriptor fd,
1927 @NonNull InetAddress source,
1928 @NonNull InetAddress destination,
1929 @NonNull @CallbackExecutor Executor executor,
1930 @NonNull Callback callback) {
1931 return new NattSocketKeepalive(mService, network, fd, INVALID_RESOURCE_ID /* Unused */,
1932 source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08001933 }
1934
1935 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 * Ensure that a network route exists to deliver traffic to the specified
1937 * host via the specified network interface. An attempt to add a route that
1938 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001939 *
1940 * <p>This method requires the caller to hold either the
1941 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1942 * or the ability to modify system settings as determined by
1943 * {@link android.provider.Settings.System#canWrite}.</p>
1944 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 * @param networkType the type of the network over which traffic to the specified
1946 * host is to be routed
1947 * @param hostAddress the IP address of the host to which the route is desired
1948 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001949 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001950 * @deprecated Deprecated in favor of the
1951 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
1952 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001953 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001954 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001955 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001957 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001959 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001960 }
1961
1962 /**
1963 * Ensure that a network route exists to deliver traffic to the specified
1964 * host via the specified network interface. An attempt to add a route that
1965 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001966 *
1967 * <p>This method requires the caller to hold either the
1968 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1969 * or the ability to modify system settings as determined by
1970 * {@link android.provider.Settings.System#canWrite}.</p>
1971 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001972 * @param networkType the type of the network over which traffic to the specified
1973 * host is to be routed
1974 * @param hostAddress the IP address of the host to which the route is desired
1975 * @return {@code true} on success, {@code false} on failure
1976 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001977 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001978 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001979 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001980 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001981 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001982 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001983 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001985 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001987 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 }
1989 }
1990
1991 /**
1992 * Returns the value of the setting for background data usage. If false,
1993 * applications should not use the network if the application is not in the
1994 * foreground. Developers should respect this setting, and check the value
1995 * of this before performing any background data operations.
1996 * <p>
1997 * All applications that have background services that use the network
1998 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001999 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002000 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002001 * background data depends on several combined factors, and this method will
2002 * always return {@code true}. Instead, when background data is unavailable,
2003 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002004 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 * @return Whether background data usage is allowed.
2006 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002007 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002009 // assume that background data is allowed; final authority is
2010 // NetworkInfo which may be blocked.
2011 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 }
2013
2014 /**
2015 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002016 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 * @param allowBackgroundData Whether an application should use data while
2018 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002019 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2021 * @see #getBackgroundDataSetting()
2022 * @hide
2023 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002024 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002025 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002027 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002029
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002030 /** {@hide} */
2031 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002032 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002033 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2034 try {
2035 return mService.getActiveNetworkQuotaInfo();
2036 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002037 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002038 }
2039 }
2040
2041 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002042 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002043 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002044 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002045 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002046 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002047 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002048 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
2049 if (b != null) {
2050 try {
2051 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08002052 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08002053 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
Malcolm Chenb455e722017-11-28 15:57:14 -08002054 boolean retVal = it.isUserDataEnabled(subId);
Wink Saville36ffb042014-12-05 11:10:30 -08002055 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2056 + " retVal=" + retVal);
2057 return retVal;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002058 } catch (RemoteException e) {
2059 throw e.rethrowFromSystemServer();
2060 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002061 }
Wink Saville36ffb042014-12-05 11:10:30 -08002062 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002063 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002064 }
2065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002067 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002068 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002069 */
2070 public interface OnNetworkActiveListener {
2071 /**
2072 * Called on the main thread of the process to report that the current data network
2073 * has become active, and it is now a good time to perform any pending network
2074 * operations. Note that this listener only tells you when the network becomes
2075 * active; if at any other time you want to know whether it is active (and thus okay
2076 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002077 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002078 */
Chalard Jean4d660112018-06-04 16:52:49 +09002079 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002080 }
2081
2082 private INetworkManagementService getNetworkManagementService() {
2083 synchronized (this) {
2084 if (mNMService != null) {
2085 return mNMService;
2086 }
2087 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2088 mNMService = INetworkManagementService.Stub.asInterface(b);
2089 return mNMService;
2090 }
2091 }
2092
2093 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002094 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002095
2096 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002097 * Start listening to reports when the system's default data network is active, meaning it is
2098 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2099 * to determine the current state of the system's default network after registering the
2100 * listener.
2101 * <p>
2102 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002103 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002104 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002105 *
2106 * @param l The listener to be told when the network is active.
2107 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002108 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002109 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2110 @Override
2111 public void onNetworkActive() throws RemoteException {
2112 l.onNetworkActive();
2113 }
2114 };
2115
2116 try {
2117 getNetworkManagementService().registerNetworkActivityListener(rl);
2118 mNetworkActivityListeners.put(l, rl);
2119 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002120 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002121 }
2122 }
2123
2124 /**
2125 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002126 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002127 *
2128 * @param l Previously registered listener.
2129 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002130 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002131 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002132 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002133 try {
2134 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2135 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002136 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002137 }
2138 }
2139
2140 /**
2141 * Return whether the data network is currently active. An active network means that
2142 * it is currently in a high power state for performing data transmission. On some
2143 * types of networks, it may be expensive to move and stay in such a state, so it is
2144 * more power efficient to batch network traffic together when the radio is already in
2145 * this state. This method tells you whether right now is currently a good time to
2146 * initiate network traffic, as the network is already active.
2147 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002148 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002149 try {
2150 return getNetworkManagementService().isNetworkActive();
2151 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002152 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002153 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002154 }
2155
2156 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 * {@hide}
2158 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002159 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002160 mContext = Preconditions.checkNotNull(context, "missing context");
2161 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05002162 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002164
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002165 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002166 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002167 public static ConnectivityManager from(Context context) {
2168 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2169 }
2170
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002171 /** @hide */
2172 public NetworkRequest getDefaultRequest() {
2173 try {
2174 // This is not racy as the default request is final in ConnectivityService.
2175 return mService.getDefaultRequest();
2176 } catch (RemoteException e) {
2177 throw e.rethrowFromSystemServer();
2178 }
2179 }
2180
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002181 /* TODO: These permissions checks don't belong in client-side code. Move them to
2182 * services.jar, possibly in com.android.server.net. */
2183
2184 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002185 public static final void enforceChangePermission(Context context) {
2186 int uid = Binder.getCallingUid();
2187 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2188 .getPackageNameForUid(context, uid), true /* throwException */);
2189 }
2190
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002191 /** {@hide} */
2192 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002193 Preconditions.checkNotNull(context, "Context cannot be null");
2194 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002195
Robert Greenwaltedb47662014-09-16 17:54:19 -07002196 if (context.getResources().getStringArray(
2197 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2198 // Have a provisioning app - must only let system apps (which check this app)
2199 // turn on tethering
2200 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002201 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002202 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002203 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002204 // If callingPkg's uid is not same as Binder.getCallingUid(),
2205 // AppOpsService throws SecurityException.
2206 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2207 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002208 }
2209 }
2210
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002211 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002212 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2213 * situations where a Context pointer is unavailable.
2214 * @hide
2215 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002216 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002217 static ConnectivityManager getInstanceOrNull() {
2218 return sInstance;
2219 }
2220
2221 /**
2222 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2223 * situations where a Context pointer is unavailable.
2224 * @hide
2225 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002226 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002227 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002228 private static ConnectivityManager getInstance() {
2229 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002230 throw new IllegalStateException("No ConnectivityManager yet constructed");
2231 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002232 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002233 }
2234
2235 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002236 * Get the set of tetherable, available interfaces. This list is limited by
2237 * device configuration and current interface existence.
2238 *
2239 * @return an array of 0 or more Strings of tetherable interface names.
2240 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002241 * {@hide}
2242 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002243 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002244 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002245 public String[] getTetherableIfaces() {
2246 try {
2247 return mService.getTetherableIfaces();
2248 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002249 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002250 }
2251 }
2252
2253 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002254 * Get the set of tethered interfaces.
2255 *
2256 * @return an array of 0 or more String of currently tethered interface names.
2257 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002258 * {@hide}
2259 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002260 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002261 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002262 public String[] getTetheredIfaces() {
2263 try {
2264 return mService.getTetheredIfaces();
2265 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002266 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002267 }
2268 }
2269
2270 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002271 * Get the set of interface names which attempted to tether but
2272 * failed. Re-attempting to tether may cause them to reset to the Tethered
2273 * state. Alternatively, causing the interface to be destroyed and recreated
2274 * may cause them to reset to the available state.
2275 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2276 * information on the cause of the errors.
2277 *
2278 * @return an array of 0 or more String indicating the interface names
2279 * which failed to tether.
2280 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002281 * {@hide}
2282 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002283 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002284 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002285 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002286 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08002287 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002288 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002289 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002290 }
2291 }
2292
2293 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002294 * Get the set of tethered dhcp ranges.
2295 *
2296 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
2297 * {@hide}
2298 */
2299 public String[] getTetheredDhcpRanges() {
2300 try {
2301 return mService.getTetheredDhcpRanges();
2302 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002303 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002304 }
2305 }
2306
2307 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002308 * Attempt to tether the named interface. This will setup a dhcp server
2309 * on the interface, forward and NAT IP packets and forward DNS requests
2310 * to the best active upstream network interface. Note that if no upstream
2311 * IP network interface is available, dhcp will still run and traffic will be
2312 * allowed between the tethered devices and this device, though upstream net
2313 * access will of course fail until an upstream network interface becomes
2314 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002315 *
2316 * <p>This method requires the caller to hold either the
2317 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2318 * or the ability to modify system settings as determined by
2319 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002320 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002321 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2322 * and WifiStateMachine which need direct access. All other clients should use
2323 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2324 * logic.</p>
2325 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002326 * @param iface the interface name to tether.
2327 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2328 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002329 * {@hide}
2330 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002331 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002332 public int tether(String iface) {
2333 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002334 String pkgName = mContext.getOpPackageName();
2335 Log.i(TAG, "tether caller:" + pkgName);
2336 return mService.tether(iface, pkgName);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002337 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002338 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002339 }
2340 }
2341
2342 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002343 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002344 *
2345 * <p>This method requires the caller to hold either the
2346 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2347 * or the ability to modify system settings as determined by
2348 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002349 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002350 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2351 * and WifiStateMachine which need direct access. All other clients should use
2352 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2353 * logic.</p>
2354 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002355 * @param iface the interface name to untether.
2356 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2357 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002358 * {@hide}
2359 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002360 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002361 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002362 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002363 String pkgName = mContext.getOpPackageName();
2364 Log.i(TAG, "untether caller:" + pkgName);
2365 return mService.untether(iface, pkgName);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002366 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002367 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002368 }
2369 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002370
2371 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002372 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002373 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002374 * due to device configuration.
2375 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002376 * <p>If this app does not have permission to use this API, it will always
2377 * return false rather than throw an exception.</p>
2378 *
2379 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2380 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2381 *
2382 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2383 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2384 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002385 * @return a boolean - {@code true} indicating Tethering is supported.
2386 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002387 * {@hide}
2388 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002389 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002390 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2391 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002392 public boolean isTetheringSupported() {
Chalard Jean8f76fc32017-09-26 15:45:18 +09002393 String pkgName = mContext.getOpPackageName();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002394 try {
Udam Saini0e94c362017-06-07 12:06:28 -07002395 return mService.isTetheringSupported(pkgName);
Chalard Jean8f76fc32017-09-26 15:45:18 +09002396 } catch (SecurityException e) {
2397 // This API is not available to this caller, but for backward-compatibility
2398 // this will just return false instead of throwing.
2399 return false;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002400 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002401 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002402 }
2403 }
2404
2405 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002406 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2407 * @hide
2408 */
2409 @SystemApi
2410 public static abstract class OnStartTetheringCallback {
2411 /**
2412 * Called when tethering has been successfully started.
2413 */
Chalard Jean4d660112018-06-04 16:52:49 +09002414 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002415
2416 /**
2417 * Called when starting tethering failed.
2418 */
Chalard Jean4d660112018-06-04 16:52:49 +09002419 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002420 }
2421
2422 /**
2423 * Convenient overload for
2424 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2425 * handler to run on the current thread's {@link Looper}.
2426 * @hide
2427 */
2428 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07002429 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002430 public void startTethering(int type, boolean showProvisioningUi,
2431 final OnStartTetheringCallback callback) {
2432 startTethering(type, showProvisioningUi, callback, null);
2433 }
2434
2435 /**
2436 * Runs tether provisioning for the given type if needed and then starts tethering if
2437 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2438 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2439 * schedules tether provisioning re-checks if appropriate.
2440 *
2441 * @param type The type of tethering to start. Must be one of
2442 * {@link ConnectivityManager.TETHERING_WIFI},
2443 * {@link ConnectivityManager.TETHERING_USB}, or
2444 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2445 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2446 * is one. This should be true the first time this function is called and also any time
2447 * the user can see this UI. It gives users information from their carrier about the
2448 * check failing and how they can sign up for tethering if possible.
2449 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2450 * of the result of trying to tether.
2451 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2452 * @hide
2453 */
2454 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002455 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002456 public void startTethering(int type, boolean showProvisioningUi,
2457 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002458 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002459
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002460 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2461 @Override
2462 protected void onReceiveResult(int resultCode, Bundle resultData) {
2463 if (resultCode == TETHER_ERROR_NO_ERROR) {
2464 callback.onTetheringStarted();
2465 } else {
2466 callback.onTetheringFailed();
2467 }
2468 }
2469 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002470
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002471 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002472 String pkgName = mContext.getOpPackageName();
2473 Log.i(TAG, "startTethering caller:" + pkgName);
2474 mService.startTethering(type, wrappedCallback, showProvisioningUi, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002475 } catch (RemoteException e) {
2476 Log.e(TAG, "Exception trying to start tethering.", e);
2477 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2478 }
2479 }
2480
2481 /**
2482 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2483 * applicable.
2484 *
2485 * @param type The type of tethering to stop. Must be one of
2486 * {@link ConnectivityManager.TETHERING_WIFI},
2487 * {@link ConnectivityManager.TETHERING_USB}, or
2488 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2489 * @hide
2490 */
2491 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002492 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002493 public void stopTethering(int type) {
2494 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002495 String pkgName = mContext.getOpPackageName();
2496 Log.i(TAG, "stopTethering caller:" + pkgName);
2497 mService.stopTethering(type, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002498 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002499 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002500 }
2501 }
2502
2503 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002504 * Get the list of regular expressions that define any tetherable
2505 * USB network interfaces. If USB tethering is not supported by the
2506 * device, this list should be empty.
2507 *
2508 * @return an array of 0 or more regular expression Strings defining
2509 * what interfaces are considered tetherable usb interfaces.
2510 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002511 * {@hide}
2512 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002513 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002514 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002515 public String[] getTetherableUsbRegexs() {
2516 try {
2517 return mService.getTetherableUsbRegexs();
2518 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002519 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002520 }
2521 }
2522
2523 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002524 * Get the list of regular expressions that define any tetherable
2525 * Wifi network interfaces. If Wifi tethering is not supported by the
2526 * device, this list should be empty.
2527 *
2528 * @return an array of 0 or more regular expression Strings defining
2529 * what interfaces are considered tetherable wifi interfaces.
2530 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002531 * {@hide}
2532 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002533 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002534 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002535 public String[] getTetherableWifiRegexs() {
2536 try {
2537 return mService.getTetherableWifiRegexs();
2538 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002539 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002540 }
2541 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002542
Danica Chang6fdd0c62010-08-11 14:54:43 -07002543 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002544 * Get the list of regular expressions that define any tetherable
2545 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2546 * device, this list should be empty.
2547 *
2548 * @return an array of 0 or more regular expression Strings defining
2549 * what interfaces are considered tetherable bluetooth interfaces.
2550 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002551 * {@hide}
2552 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002553 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002554 @UnsupportedAppUsage
Danica Chang6fdd0c62010-08-11 14:54:43 -07002555 public String[] getTetherableBluetoothRegexs() {
2556 try {
2557 return mService.getTetherableBluetoothRegexs();
2558 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002559 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002560 }
2561 }
2562
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002563 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002564 * Attempt to both alter the mode of USB and Tethering of USB. A
2565 * utility method to deal with some of the complexity of USB - will
2566 * attempt to switch to Rndis and subsequently tether the resulting
2567 * interface on {@code true} or turn off tethering and switch off
2568 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002569 *
2570 * <p>This method requires the caller to hold either the
2571 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2572 * or the ability to modify system settings as determined by
2573 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002574 *
2575 * @param enable a boolean - {@code true} to enable tethering
2576 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2577 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002578 * {@hide}
2579 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002580 @UnsupportedAppUsage
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002581 public int setUsbTethering(boolean enable) {
2582 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002583 String pkgName = mContext.getOpPackageName();
2584 Log.i(TAG, "setUsbTethering caller:" + pkgName);
2585 return mService.setUsbTethering(enable, pkgName);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002586 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002587 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002588 }
2589 }
2590
Robert Greenwalt5a735062010-03-02 17:25:02 -08002591 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002592 @SystemApi
Robert Greenwalt5a735062010-03-02 17:25:02 -08002593 public static final int TETHER_ERROR_NO_ERROR = 0;
2594 /** {@hide} */
2595 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2596 /** {@hide} */
2597 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2598 /** {@hide} */
2599 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2600 /** {@hide} */
2601 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2602 /** {@hide} */
2603 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2604 /** {@hide} */
2605 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2606 /** {@hide} */
2607 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2608 /** {@hide} */
2609 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2610 /** {@hide} */
2611 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2612 /** {@hide} */
2613 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002614 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002615 @SystemApi
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002616 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +09002617 /** {@hide} */
2618 public static final int TETHER_ERROR_DHCPSERVER_ERROR = 12;
markchienf2731272019-01-16 17:44:13 +08002619 /** {@hide} */
2620 @SystemApi
2621 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002622
2623 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002624 * Get a more detailed error code after a Tethering or Untethering
2625 * request asynchronously failed.
2626 *
2627 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002628 * @return error The error code of the last error tethering or untethering the named
2629 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002630 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002631 * {@hide}
2632 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002633 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002634 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002635 public int getLastTetherError(String iface) {
2636 try {
2637 return mService.getLastTetherError(iface);
2638 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002639 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002640 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002641 }
2642
2643 /**
markchienf2731272019-01-16 17:44:13 +08002644 * Callback for use with {@link #getLatestTetheringEntitlementValue} to find out whether
2645 * entitlement succeeded.
2646 * @hide
2647 */
2648 @SystemApi
2649 public abstract static class TetheringEntitlementValueListener {
2650 /**
2651 * Called to notify entitlement result.
2652 *
2653 * @param resultCode a int value of entitlement result. It may be one of
2654 * {@link #TETHER_ERROR_NO_ERROR},
2655 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2656 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2657 */
2658 public void onEntitlementResult(int resultCode) {}
2659 }
2660
2661 /**
2662 * Get the last value of the entitlement check on this downstream. If the cached value is
2663 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2664 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2665 * guaranteed that the UI-based entitlement check will complete in any specific time period
2666 * and may in fact never complete. Any successful entitlement check the platform performs for
2667 * any reason will update the cached value.
2668 *
2669 * @param type the downstream type of tethering. Must be one of
2670 * {@link #TETHERING_WIFI},
2671 * {@link #TETHERING_USB}, or
2672 * {@link #TETHERING_BLUETOOTH}.
2673 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
2674 * @param listener an {@link TetheringEntitlementValueListener} which will be called to notify
2675 * the caller of the result of entitlement check. The listener may be called zero or
2676 * one time.
2677 * @param handler {@link Handler} to specify the thread upon which the listener will be invoked.
2678 * {@hide}
2679 */
2680 @SystemApi
2681 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2682 public void getLatestTetheringEntitlementValue(int type, boolean showEntitlementUi,
2683 @NonNull final TetheringEntitlementValueListener listener, @Nullable Handler handler) {
2684 Preconditions.checkNotNull(listener, "TetheringEntitlementValueListener cannot be null.");
2685 ResultReceiver wrappedListener = new ResultReceiver(handler) {
2686 @Override
2687 protected void onReceiveResult(int resultCode, Bundle resultData) {
2688 listener.onEntitlementResult(resultCode);
2689 }
2690 };
2691
2692 try {
2693 String pkgName = mContext.getOpPackageName();
2694 Log.i(TAG, "getLatestTetheringEntitlementValue:" + pkgName);
2695 mService.getLatestTetheringEntitlementValue(type, wrappedListener,
2696 showEntitlementUi, pkgName);
2697 } catch (RemoteException e) {
2698 throw e.rethrowFromSystemServer();
2699 }
2700 }
2701
2702 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002703 * Report network connectivity status. This is currently used only
2704 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002705 * <p>This method requires the caller to hold the permission
2706 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002707 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002708 * @param networkType The type of network you want to report on
2709 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002710 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002711 * {@hide}
2712 */
2713 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002714 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002715 try {
2716 mService.reportInetCondition(networkType, percentage);
2717 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002718 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002719 }
2720 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002721
2722 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002723 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002724 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002725 * the framework to re-evaluate network connectivity and/or switch to another
2726 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002727 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002728 * @param network The {@link Network} the application was attempting to use
2729 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002730 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2731 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002732 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002733 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002734 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002735 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002736 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002737 // One of these will be ignored because it matches system's current state.
2738 // The other will trigger the necessary reevaluation.
2739 mService.reportNetworkConnectivity(network, true);
2740 mService.reportNetworkConnectivity(network, false);
2741 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002742 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002743 }
2744 }
2745
2746 /**
2747 * Report to the framework whether a network has working connectivity.
2748 * This provides a hint to the system that a particular network is providing
2749 * working connectivity or not. In response the framework may re-evaluate
2750 * the network's connectivity and might take further action thereafter.
2751 *
2752 * @param network The {@link Network} the application was attempting to use
2753 * or {@code null} to indicate the current default network.
2754 * @param hasConnectivity {@code true} if the application was able to successfully access the
2755 * Internet using {@code network} or {@code false} if not.
2756 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002757 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002758 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002759 try {
2760 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002761 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002762 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002763 }
2764 }
2765
2766 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002767 * Set a network-independent global http proxy. This is not normally what you want
2768 * for typical HTTP proxies - they are general network dependent. However if you're
2769 * doing something unusual like general internal filtering this may be useful. On
2770 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002771 *
2772 * @param p A {@link ProxyInfo} object defining the new global
2773 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002774 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002775 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002776 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Jason Monk207900c2014-04-25 15:00:09 -04002777 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002778 try {
2779 mService.setGlobalProxy(p);
2780 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002781 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002782 }
2783 }
2784
2785 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002786 * Retrieve any network-independent global HTTP proxy.
2787 *
Jason Monk207900c2014-04-25 15:00:09 -04002788 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002789 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002790 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002791 */
Jason Monk207900c2014-04-25 15:00:09 -04002792 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002793 try {
2794 return mService.getGlobalProxy();
2795 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002796 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002797 }
2798 }
2799
2800 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002801 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2802 * network-specific HTTP proxy. If {@code network} is null, the
2803 * network-specific proxy returned is the proxy of the default active
2804 * network.
2805 *
2806 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2807 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2808 * or when {@code network} is {@code null},
2809 * the {@code ProxyInfo} for the default active network. Returns
2810 * {@code null} when no proxy applies or the caller doesn't have
2811 * permission to use {@code network}.
2812 * @hide
2813 */
2814 public ProxyInfo getProxyForNetwork(Network network) {
2815 try {
2816 return mService.getProxyForNetwork(network);
2817 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002818 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04002819 }
2820 }
2821
2822 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002823 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
2824 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04002825 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05002826 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002827 *
Jason Monk207900c2014-04-25 15:00:09 -04002828 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002829 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07002830 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002831 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05002832 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04002833 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07002834 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002835
2836 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002837 * Returns true if the hardware supports the given network type
2838 * else it returns false. This doesn't indicate we have coverage
2839 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002840 * hardware supports it. For example a GSM phone without a SIM
2841 * should still return {@code true} for mobile data, but a wifi only
2842 * tablet would return {@code false}.
2843 *
2844 * @param networkType The network type we'd like to check
2845 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002846 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002847 * @hide
2848 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002849 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002850 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002851 @UnsupportedAppUsage
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002852 public boolean isNetworkSupported(int networkType) {
2853 try {
2854 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002855 } catch (RemoteException e) {
2856 throw e.rethrowFromSystemServer();
2857 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002858 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002859
2860 /**
2861 * Returns if the currently active data network is metered. A network is
2862 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002863 * that connection due to monetary costs, data limitations or
2864 * battery/performance issues. You should check this before doing large
2865 * data transfers, and warn the user or delay the operation until another
2866 * network is available.
2867 *
2868 * @return {@code true} if large transfers should be avoided, otherwise
2869 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002870 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002871 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002872 public boolean isActiveNetworkMetered() {
2873 try {
2874 return mService.isActiveNetworkMetered();
2875 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002876 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002877 }
2878 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002879
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002880 /**
2881 * If the LockdownVpn mechanism is enabled, updates the vpn
2882 * with a reload of its profile.
2883 *
2884 * @return a boolean with {@code} indicating success
2885 *
2886 * <p>This method can only be called by the system UID
2887 * {@hide}
2888 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002889 public boolean updateLockdownVpn() {
2890 try {
2891 return mService.updateLockdownVpn();
2892 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002893 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002894 }
2895 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002896
2897 /**
Wink Saville948282b2013-08-29 08:55:16 -07002898 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07002899 *
Wink Savilleab9321d2013-06-29 21:10:57 -07002900 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07002901 *
2902 * @return time out that will be used, maybe less that suggestedTimeOutMs
2903 * -1 if an error.
2904 *
2905 * {@hide}
2906 */
Wink Saville948282b2013-08-29 08:55:16 -07002907 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07002908 int timeOutMs = -1;
2909 try {
Wink Saville948282b2013-08-29 08:55:16 -07002910 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07002911 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002912 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07002913 }
2914 return timeOutMs;
2915 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002916
2917 /**
Wink Saville42d4f082013-07-20 20:31:59 -07002918 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002919 * {@hide}
2920 */
2921 public String getMobileProvisioningUrl() {
2922 try {
2923 return mService.getMobileProvisioningUrl();
2924 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002925 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002926 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002927 }
Wink Saville42d4f082013-07-20 20:31:59 -07002928
2929 /**
Wink Saville948282b2013-08-29 08:55:16 -07002930 * Set sign in error notification to visible or in visible
2931 *
Wink Saville948282b2013-08-29 08:55:16 -07002932 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04002933 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07002934 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002935 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07002936 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04002937 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07002938 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04002939 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07002940 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002941 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07002942 }
2943 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002944
2945 /**
2946 * Set the value for enabling/disabling airplane mode
2947 *
2948 * @param enable whether to enable airplane mode or not
2949 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002950 * @hide
2951 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09002952 @RequiresPermission(anyOf = {
2953 android.Manifest.permission.NETWORK_SETTINGS,
2954 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2955 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09002956 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002957 public void setAirplaneMode(boolean enable) {
2958 try {
2959 mService.setAirplaneMode(enable);
2960 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002961 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002962 }
2963 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002964
2965 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002966 @UnsupportedAppUsage
Robert Greenwalta67be032014-05-16 15:49:14 -07002967 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07002968 try {
Robert Greenwalta67be032014-05-16 15:49:14 -07002969 mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002970 } catch (RemoteException e) {
2971 throw e.rethrowFromSystemServer();
2972 }
Robert Greenwalta67be032014-05-16 15:49:14 -07002973 }
2974
2975 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00002976 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Robert Greenwalta67be032014-05-16 15:49:14 -07002977 public void unregisterNetworkFactory(Messenger messenger) {
2978 try {
2979 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002980 } catch (RemoteException e) {
2981 throw e.rethrowFromSystemServer();
2982 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002983 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002984
Paul Jensen31a94f42015-02-13 14:18:39 -05002985 /**
2986 * @hide
2987 * Register a NetworkAgent with ConnectivityService.
2988 * @return NetID corresponding to NetworkAgent.
2989 */
2990 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002991 NetworkCapabilities nc, int score, NetworkMisc misc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002992 try {
Paul Jensen31a94f42015-02-13 14:18:39 -05002993 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc);
2994 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002995 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05002996 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002997 }
2998
Robert Greenwalt9258c642014-03-26 16:47:06 -07002999 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003000 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3001 * changes. Should be extended by applications wanting notifications.
3002 *
3003 * A {@code NetworkCallback} is registered by calling
3004 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3005 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09003006 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09003007 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3008 * A {@code NetworkCallback} should be registered at most once at any time.
3009 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003010 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003011 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003012 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003013 * Called when the framework connects to a new network to evaluate whether it satisfies this
3014 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3015 * callback. There is no guarantee that this new network will satisfy any requests, or that
3016 * the network will stay connected for longer than the time necessary to evaluate it.
3017 * <p>
3018 * Most applications <b>should not</b> act on this callback, and should instead use
3019 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3020 * the framework in properly evaluating the network &mdash; for example, an application that
3021 * can automatically log in to a captive portal without user intervention.
3022 *
3023 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09003024 *
3025 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07003026 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003027 public void onPreCheck(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003028
3029 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003030 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003031 * This callback may be called more than once if the {@link Network} that is
3032 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003033 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003034 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003035 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3036 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08003037 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003038 * @hide
3039 */
3040 public void onAvailable(Network network, NetworkCapabilities networkCapabilities,
junyulai05986c62018-08-07 19:50:45 +08003041 LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003042 // Internally only this method is called when a new network is available, and
3043 // it calls the callback in the same way and order that older versions used
3044 // to call so as not to change the behavior.
3045 onAvailable(network);
3046 if (!networkCapabilities.hasCapability(
3047 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3048 onNetworkSuspended(network);
3049 }
3050 onCapabilitiesChanged(network, networkCapabilities);
3051 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003052 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003053 }
3054
3055 /**
3056 * Called when the framework connects and has declared a new network ready for use.
3057 * This callback may be called more than once if the {@link Network} that is
3058 * satisfying the request changes. This will always immediately be followed by a
3059 * call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} then by a
junyulai05986c62018-08-07 19:50:45 +08003060 * call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call to
3061 * {@link #onBlockedStatusChanged(Network, boolean)}.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003062 *
3063 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003064 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003065 public void onAvailable(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003066
3067 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003068 * Called when the network is about to be disconnected. Often paired with an
Robert Greenwalt6078b502014-06-11 16:05:07 -07003069 * {@link NetworkCallback#onAvailable} call with the new replacement network
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003070 * for graceful handover. This may not be called if we have a hard loss
3071 * (loss without warning). This may be followed by either a
Robert Greenwalt6078b502014-06-11 16:05:07 -07003072 * {@link NetworkCallback#onLost} call or a
3073 * {@link NetworkCallback#onAvailable} call for this network depending
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003074 * on whether we lose or regain it.
3075 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003076 * @param network The {@link Network} that is about to be disconnected.
3077 * @param maxMsToLive The time in ms the framework will attempt to keep the
3078 * network connected. Note that the network may suffer a
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003079 * hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003080 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003081 public void onLosing(Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003082
3083 /**
3084 * Called when the framework has a hard loss of the network or when the
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003085 * graceful failure ends.
3086 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003087 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003088 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003089 public void onLost(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003090
3091 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003092 * Called if no network is found in the timeout time specified in
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003093 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call. This callback is not
Etan Cohenaebf17e2017-03-01 12:47:28 -08003094 * called for the version of {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3095 * without timeout. When this callback is invoked the associated
3096 * {@link NetworkRequest} will have already been removed and released, as if
3097 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003098 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003099 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003100
3101 /**
3102 * Called when the network the framework connected to for this request
3103 * changes capabilities but still satisfies the stated need.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003104 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003105 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003106 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3107 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003108 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003109 public void onCapabilitiesChanged(Network network,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003110 NetworkCapabilities networkCapabilities) {}
3111
3112 /**
3113 * Called when the network the framework connected to for this request
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003114 * changes {@link LinkProperties}.
3115 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003116 * @param network The {@link Network} whose link properties have changed.
3117 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003118 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003119 public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003120
Robert Greenwalt8d482522015-06-24 13:23:42 -07003121 /**
3122 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003123 * goes into {@link NetworkInfo.State#SUSPENDED}.
Robert Greenwalt8d482522015-06-24 13:23:42 -07003124 * This generally means that while the TCP connections are still live,
3125 * temporarily network data fails to transfer. Specifically this is used
3126 * on cellular networks to mask temporary outages when driving through
3127 * a tunnel, etc.
3128 * @hide
3129 */
3130 public void onNetworkSuspended(Network network) {}
3131
3132 /**
3133 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003134 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3135 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Robert Greenwalt8d482522015-06-24 13:23:42 -07003136 * @hide
3137 */
3138 public void onNetworkResumed(Network network) {}
3139
junyulai05986c62018-08-07 19:50:45 +08003140 /**
3141 * Called when access to the specified network is blocked or unblocked.
3142 *
3143 * @param network The {@link Network} whose blocked status has changed.
3144 * @param blocked The blocked status of this {@link Network}.
3145 */
3146 public void onBlockedStatusChanged(Network network, boolean blocked) {}
3147
Robert Greenwalt6078b502014-06-11 16:05:07 -07003148 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003149 }
3150
Hugo Benichicb883232017-05-11 13:16:17 +09003151 /**
3152 * Constant error codes used by ConnectivityService to communicate about failures and errors
3153 * across a Binder boundary.
3154 * @hide
3155 */
3156 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003157 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003158 }
3159
3160 /** @hide */
3161 public static class TooManyRequestsException extends RuntimeException {}
3162
3163 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3164 switch (e.errorCode) {
3165 case Errors.TOO_MANY_REQUESTS:
3166 return new TooManyRequestsException();
3167 default:
3168 Log.w(TAG, "Unknown service error code " + e.errorCode);
3169 return new RuntimeException(e);
3170 }
3171 }
3172
Robert Greenwalt9258c642014-03-26 16:47:06 -07003173 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003174 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003175 public static final int CALLBACK_PRECHECK = BASE + 1;
3176 /** @hide */
3177 public static final int CALLBACK_AVAILABLE = BASE + 2;
3178 /** @hide arg1 = TTL */
3179 public static final int CALLBACK_LOSING = BASE + 3;
3180 /** @hide */
3181 public static final int CALLBACK_LOST = BASE + 4;
3182 /** @hide */
3183 public static final int CALLBACK_UNAVAIL = BASE + 5;
3184 /** @hide */
3185 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3186 /** @hide */
3187 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003188 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003189 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003190 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003191 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003192 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003193 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003194 /** @hide */
3195 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003196
Erik Kline57faba92015-11-25 12:49:38 +09003197 /** @hide */
3198 public static String getCallbackName(int whichCallback) {
3199 switch (whichCallback) {
3200 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3201 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3202 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3203 case CALLBACK_LOST: return "CALLBACK_LOST";
3204 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3205 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3206 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003207 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3208 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3209 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003210 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003211 default:
3212 return Integer.toString(whichCallback);
3213 }
3214 }
3215
Robert Greenwalt562cc542014-05-15 18:07:26 -07003216 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003217 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003218 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003219
Hugo Benichid42650f2016-07-06 22:53:17 +09003220 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003221 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003222 }
3223
Hugo Benichi2583ef02017-02-02 17:02:36 +09003224 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003225 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003226 }
3227
Robert Greenwalt9258c642014-03-26 16:47:06 -07003228 @Override
3229 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003230 if (message.what == EXPIRE_LEGACY_REQUEST) {
3231 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3232 return;
3233 }
3234
3235 final NetworkRequest request = getObject(message, NetworkRequest.class);
3236 final Network network = getObject(message, Network.class);
3237 final NetworkCallback callback;
3238 synchronized (sCallbacks) {
3239 callback = sCallbacks.get(request);
3240 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003241 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003242 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003243 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003244 if (callback == null) {
3245 Log.w(TAG, "callback not found for " + getCallbackName(message.what) + " message");
3246 return;
3247 }
3248
Robert Greenwalt9258c642014-03-26 16:47:06 -07003249 switch (message.what) {
3250 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003251 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003252 break;
3253 }
3254 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003255 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3256 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003257 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003258 break;
3259 }
3260 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003261 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003262 break;
3263 }
3264 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003265 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003266 break;
3267 }
3268 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003269 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003270 break;
3271 }
3272 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003273 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3274 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003275 break;
3276 }
3277 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003278 LinkProperties lp = getObject(message, LinkProperties.class);
3279 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003280 break;
3281 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003282 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003283 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003284 break;
3285 }
3286 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003287 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003288 break;
3289 }
junyulai05986c62018-08-07 19:50:45 +08003290 case CALLBACK_BLK_CHANGED: {
3291 boolean blocked = message.arg1 != 0;
3292 callback.onBlockedStatusChanged(network, blocked);
3293 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003294 }
3295 }
3296
Hugo Benichid42650f2016-07-06 22:53:17 +09003297 private <T> T getObject(Message msg, Class<T> c) {
3298 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003299 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003300 }
3301
Hugo Benichi2583ef02017-02-02 17:02:36 +09003302 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003303 synchronized (sCallbacks) {
3304 if (sCallbackHandler == null) {
3305 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003306 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003307 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003308 }
3309 }
3310
Hugo Benichi6f260f32017-02-03 14:18:44 +09003311 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3312 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003313
Hugo Benichi6f260f32017-02-03 14:18:44 +09003314 private static final int LISTEN = 1;
3315 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003316
Hugo Benichi6f260f32017-02-03 14:18:44 +09003317 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3318 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003319 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003320 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003321 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003322 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003323 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003324 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003325 if (callback.networkRequest != null
3326 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003327 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3328 // and requests (http://b/20701525).
3329 Log.e(TAG, "NetworkCallback was already registered");
3330 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003331 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003332 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003333 if (action == LISTEN) {
Hugo Benichid42650f2016-07-06 22:53:17 +09003334 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04003335 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003336 request = mService.requestNetwork(
3337 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04003338 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003339 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003340 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003341 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003342 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003343 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003344 } catch (RemoteException e) {
3345 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003346 } catch (ServiceSpecificException e) {
3347 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003348 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003349 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003350 }
3351
3352 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003353 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003354 *
3355 * This is temporarily public @hide so it can be called by system code that uses the
3356 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
3357 * instead network notifications.
3358 *
3359 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
3360 *
3361 * @hide
3362 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003363 public void requestNetwork(@NonNull NetworkRequest request,
3364 @NonNull NetworkCallback networkCallback, int timeoutMs, int legacyType,
3365 @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003366 CallbackHandler cbHandler = new CallbackHandler(handler);
3367 NetworkCapabilities nc = request.networkCapabilities;
3368 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003369 }
3370
3371 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003372 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003373 *
3374 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003375 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3376 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003377 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003378 * Status of the request can be followed by listening to the various
Robert Greenwalt6078b502014-06-11 16:05:07 -07003379 * callbacks described in {@link NetworkCallback}. The {@link Network}
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003380 * can be used to direct traffic to the network.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003381 * <p>It is presently unsupported to request a network with mutable
3382 * {@link NetworkCapabilities} such as
3383 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3384 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3385 * as these {@code NetworkCapabilities} represent states that a particular
3386 * network may never attain, and whether a network will attain these states
3387 * is unknown prior to bringing up the network so the framework does not
3388 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003389 *
3390 * <p>This method requires the caller to hold either the
3391 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3392 * or the ability to modify system settings as determined by
3393 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003394 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003395 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003396 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3397 * the callback must not be shared - it uniquely specifies this request.
3398 * The callback is invoked on the default internal Handler.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003399 * @throws IllegalArgumentException if {@code request} specifies any mutable
3400 * {@code NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003401 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003402 public void requestNetwork(@NonNull NetworkRequest request,
3403 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003404 requestNetwork(request, networkCallback, getDefaultHandler());
3405 }
3406
3407 /**
3408 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3409 *
3410 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003411 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3412 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003413 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003414 * Status of the request can be followed by listening to the various
3415 * callbacks described in {@link NetworkCallback}. The {@link Network}
3416 * can be used to direct traffic to the network.
3417 * <p>It is presently unsupported to request a network with mutable
3418 * {@link NetworkCapabilities} such as
3419 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3420 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3421 * as these {@code NetworkCapabilities} represent states that a particular
3422 * network may never attain, and whether a network will attain these states
3423 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003424 * know how to go about satisfying a request with these capabilities.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003425 *
3426 * <p>This method requires the caller to hold either the
3427 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3428 * or the ability to modify system settings as determined by
3429 * {@link android.provider.Settings.System#canWrite}.</p>
3430 *
3431 * @param request {@link NetworkRequest} describing this request.
3432 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3433 * the callback must not be shared - it uniquely specifies this request.
3434 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3435 * @throws IllegalArgumentException if {@code request} specifies any mutable
3436 * {@code NetworkCapabilities}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003437 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003438 public void requestNetwork(@NonNull NetworkRequest request,
3439 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003440 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3441 CallbackHandler cbHandler = new CallbackHandler(handler);
3442 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003443 }
3444
3445 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003446 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3447 * by a timeout.
3448 *
3449 * This function behaves identically to the non-timed-out version
3450 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3451 * is not found within the given time (in milliseconds) the
3452 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3453 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3454 * not have to be released if timed-out (it is automatically released). Unregistering a
3455 * request that timed out is not an error.
3456 *
3457 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3458 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3459 * for that purpose. Calling this method will attempt to bring up the requested network.
3460 *
3461 * <p>This method requires the caller to hold either the
3462 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3463 * or the ability to modify system settings as determined by
3464 * {@link android.provider.Settings.System#canWrite}.</p>
3465 *
3466 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003467 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3468 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003469 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3470 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3471 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003472 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003473 public void requestNetwork(@NonNull NetworkRequest request,
3474 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003475 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003476 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003477 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003478 }
3479
Hugo Benichi2583ef02017-02-02 17:02:36 +09003480 /**
3481 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3482 * by a timeout.
3483 *
Chalard Jean4d660112018-06-04 16:52:49 +09003484 * This function behaves identically to the version without timeout, but if a suitable
Hugo Benichi2583ef02017-02-02 17:02:36 +09003485 * network is not found within the given time (in milliseconds) the
Etan Cohenaebf17e2017-03-01 12:47:28 -08003486 * {@link NetworkCallback#onUnavailable} callback is called. The request can still be
3487 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3488 * not have to be released if timed-out (it is automatically released). Unregistering a
3489 * request that timed out is not an error.
3490 *
3491 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3492 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3493 * for that purpose. Calling this method will attempt to bring up the requested network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003494 *
3495 * <p>This method requires the caller to hold either the
3496 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3497 * or the ability to modify system settings as determined by
3498 * {@link android.provider.Settings.System#canWrite}.</p>
3499 *
3500 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003501 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3502 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003503 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003504 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3505 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003506 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003507 public void requestNetwork(@NonNull NetworkRequest request,
3508 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003509 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003510 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3511 CallbackHandler cbHandler = new CallbackHandler(handler);
3512 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003513 }
3514
3515 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003516 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003517 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003518 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003519 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003520 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3521 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003522 */
Erik Kline90e93072014-11-19 12:12:24 +09003523 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003524
3525 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003526 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003527 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003528 * {@link android.content.Intent#getParcelableExtra(String)}.
3529 */
Erik Kline90e93072014-11-19 12:12:24 +09003530 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003531
3532
3533 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003534 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003535 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003536 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003537 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003538 * the request may outlive the calling application and get called back when a suitable
3539 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003540 * <p>
3541 * The operation is an Intent broadcast that goes to a broadcast receiver that
3542 * you registered with {@link Context#registerReceiver} or through the
3543 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3544 * <p>
3545 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003546 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3547 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003548 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003549 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003550 * Intent to reserve the network or it will be released shortly after the Intent
3551 * is processed.
3552 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003553 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003554 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003555 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003556 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003557 * The request may be released normally by calling
3558 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003559 * <p>It is presently unsupported to request a network with either
3560 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3561 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3562 * as these {@code NetworkCapabilities} represent states that a particular
3563 * network may never attain, and whether a network will attain these states
3564 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003565 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003566 *
3567 * <p>This method requires the caller to hold either the
3568 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3569 * or the ability to modify system settings as determined by
3570 * {@link android.provider.Settings.System#canWrite}.</p>
3571 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003572 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003573 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003574 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003575 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003576 * @throws IllegalArgumentException if {@code request} contains either
3577 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3578 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003579 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003580 public void requestNetwork(@NonNull NetworkRequest request,
3581 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003582 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003583 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003584 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003585 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003586 } catch (RemoteException e) {
3587 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003588 } catch (ServiceSpecificException e) {
3589 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003590 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003591 }
3592
3593 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003594 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3595 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003596 * This method has the same behavior as
3597 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003598 * releasing network resources and disconnecting.
3599 *
3600 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3601 * PendingIntent passed to
3602 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3603 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3604 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003605 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003606 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003607 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003608 try {
3609 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003610 } catch (RemoteException e) {
3611 throw e.rethrowFromSystemServer();
3612 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003613 }
3614
Hugo Benichie7678512017-05-09 15:19:01 +09003615 private static void checkPendingIntentNotNull(PendingIntent intent) {
3616 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3617 }
3618
3619 private static void checkCallbackNotNull(NetworkCallback callback) {
3620 Preconditions.checkNotNull(callback, "null NetworkCallback");
3621 }
3622
3623 private static void checkTimeout(int timeoutMs) {
3624 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003625 }
3626
3627 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003628 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003629 * {@link NetworkRequest}. The callbacks will continue to be called until
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003630 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003631 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003632 * @param request {@link NetworkRequest} describing this request.
3633 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3634 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003635 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003636 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003637 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003638 public void registerNetworkCallback(@NonNull NetworkRequest request,
3639 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003640 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3641 }
3642
3643 /**
3644 * Registers to receive notifications about all networks which satisfy the given
3645 * {@link NetworkRequest}. The callbacks will continue to be called until
3646 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003647 *
3648 * @param request {@link NetworkRequest} describing this request.
3649 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3650 * networks change state.
3651 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003652 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003653 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003654 public void registerNetworkCallback(@NonNull NetworkRequest request,
3655 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003656 CallbackHandler cbHandler = new CallbackHandler(handler);
3657 NetworkCapabilities nc = request.networkCapabilities;
3658 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003659 }
3660
3661 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003662 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3663 * {@link NetworkRequest}.
3664 *
3665 * This function behaves identically to the version that takes a NetworkCallback, but instead
3666 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3667 * the request may outlive the calling application and get called back when a suitable
3668 * network is found.
3669 * <p>
3670 * The operation is an Intent broadcast that goes to a broadcast receiver that
3671 * you registered with {@link Context#registerReceiver} or through the
3672 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3673 * <p>
3674 * The operation Intent is delivered with two extras, a {@link Network} typed
3675 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3676 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3677 * the original requests parameters.
3678 * <p>
3679 * If there is already a request for this Intent registered (with the equality of
3680 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3681 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3682 * <p>
3683 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003684 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003685 * @param request {@link NetworkRequest} describing this request.
3686 * @param operation Action to perform when the network is available (corresponds
3687 * to the {@link NetworkCallback#onAvailable} call. Typically
3688 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3689 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003690 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003691 public void registerNetworkCallback(@NonNull NetworkRequest request,
3692 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003693 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003694 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04003695 try {
3696 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003697 } catch (RemoteException e) {
3698 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003699 } catch (ServiceSpecificException e) {
3700 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003701 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003702 }
3703
3704 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003705 * Registers to receive notifications about changes in the system default network. The callbacks
3706 * will continue to be called until either the application exits or
3707 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09003708 *
3709 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3710 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003711 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09003712 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003713 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003714 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003715 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
3716 }
3717
3718 /**
3719 * Registers to receive notifications about changes in the system default network. The callbacks
3720 * will continue to be called until either the application exits or
3721 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003722 *
3723 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3724 * system default network changes.
3725 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003726 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003727 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003728 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
3729 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09003730 // This works because if the NetworkCapabilities are null,
3731 // ConnectivityService takes them from the default request.
3732 //
3733 // Since the capabilities are exactly the same as the default request's
3734 // capabilities, this request is guaranteed, at all times, to be
3735 // satisfied by the same network, if any, that satisfies the default
3736 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003737 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09003738 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
3739 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09003740 }
3741
3742 /**
fengludb571472015-04-21 17:12:05 -07003743 * Requests bandwidth update for a given {@link Network} and returns whether the update request
3744 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
3745 * network connection for updated bandwidth information. The caller will be notified via
3746 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003747 * method assumes that the caller has previously called
3748 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
3749 * changes.
fenglub15e72b2015-03-20 11:29:56 -07003750 *
fengluae519192015-04-27 14:28:04 -07003751 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07003752 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07003753 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003754 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003755 try {
fengludb571472015-04-21 17:12:05 -07003756 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07003757 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003758 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07003759 }
3760 }
3761
3762 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003763 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003764 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
3765 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
3766 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09003767 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
3768 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003769 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09003770 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
3771 * triggering it as soon as this call returns.
3772 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003773 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003774 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003775 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003776 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003777 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003778 final List<NetworkRequest> reqs = new ArrayList<>();
3779 // Find all requests associated to this callback and stop callback triggers immediately.
3780 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
3781 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003782 Preconditions.checkArgument(networkCallback.networkRequest != null,
3783 "NetworkCallback was not registered");
3784 Preconditions.checkArgument(networkCallback.networkRequest != ALREADY_UNREGISTERED,
3785 "NetworkCallback was already unregistered");
Hugo Benichidafed3d2017-03-06 09:17:06 +09003786 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
3787 if (e.getValue() == networkCallback) {
3788 reqs.add(e.getKey());
3789 }
3790 }
3791 // TODO: throw exception if callback was registered more than once (http://b/20701525).
3792 for (NetworkRequest r : reqs) {
3793 try {
3794 mService.releaseNetworkRequest(r);
3795 } catch (RemoteException e) {
3796 throw e.rethrowFromSystemServer();
3797 }
3798 // Only remove mapping if rpc was successful.
3799 sCallbacks.remove(r);
3800 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09003801 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003802 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003803 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003804
3805 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003806 * Unregisters a callback previously registered via
3807 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3808 *
3809 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3810 * PendingIntent passed to
3811 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3812 * Cannot be null.
3813 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003814 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003815 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003816 releaseNetworkRequest(operation);
3817 }
3818
3819 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003820 * Informs the system whether it should switch to {@code network} regardless of whether it is
3821 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
3822 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
3823 * the system default network regardless of any other network that's currently connected. If
3824 * {@code always} is true, then the choice is remembered, so that the next time the user
3825 * connects to this network, the system will switch to it.
3826 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003827 * @param network The network to accept.
3828 * @param accept Whether to accept the network even if unvalidated.
3829 * @param always Whether to remember this choice in the future.
3830 *
3831 * @hide
3832 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003833 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003834 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3835 try {
3836 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003837 } catch (RemoteException e) {
3838 throw e.rethrowFromSystemServer();
3839 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003840 }
3841
3842 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003843 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
3844 * only meaningful if the system is configured not to penalize such networks, e.g., if the
3845 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
3846 * NETWORK_AVOID_BAD_WIFI setting is unset}.
3847 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003848 * @param network The network to accept.
3849 *
3850 * @hide
3851 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003852 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003853 public void setAvoidUnvalidated(Network network) {
3854 try {
3855 mService.setAvoidUnvalidated(network);
3856 } catch (RemoteException e) {
3857 throw e.rethrowFromSystemServer();
3858 }
3859 }
3860
3861 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003862 * Requests that the system open the captive portal app on the specified network.
3863 *
3864 * @param network The network to log into.
3865 *
3866 * @hide
3867 */
3868 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
3869 public void startCaptivePortalApp(Network network) {
3870 try {
3871 mService.startCaptivePortalApp(network);
3872 } catch (RemoteException e) {
3873 throw e.rethrowFromSystemServer();
3874 }
3875 }
3876
3877 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003878 * Determine whether the device is configured to avoid bad wifi.
3879 * @hide
3880 */
3881 @SystemApi
3882 public boolean getAvoidBadWifi() {
3883 try {
3884 return mService.getAvoidBadWifi();
3885 } catch (RemoteException e) {
3886 throw e.rethrowFromSystemServer();
3887 }
3888 }
3889
3890 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003891 * It is acceptable to briefly use multipath data to provide seamless connectivity for
3892 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003893 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
3894 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003895 *
3896 * An example of such an operation might be a time-sensitive foreground activity, such as a
3897 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
3898 */
3899 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
3900
3901 /**
3902 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
3903 * a backup channel for traffic that is primarily going over another network.
3904 *
3905 * An example might be maintaining backup connections to peers or servers for the purpose of
3906 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
3907 * on backup paths should be negligible compared to the traffic on the main path.
3908 */
3909 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
3910
3911 /**
3912 * It is acceptable to use metered data to improve network latency and performance.
3913 */
3914 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
3915
3916 /**
3917 * Return value to use for unmetered networks. On such networks we currently set all the flags
3918 * to true.
3919 * @hide
3920 */
3921 public static final int MULTIPATH_PREFERENCE_UNMETERED =
3922 MULTIPATH_PREFERENCE_HANDOVER |
3923 MULTIPATH_PREFERENCE_RELIABILITY |
3924 MULTIPATH_PREFERENCE_PERFORMANCE;
3925
3926 /** @hide */
3927 @Retention(RetentionPolicy.SOURCE)
3928 @IntDef(flag = true, value = {
3929 MULTIPATH_PREFERENCE_HANDOVER,
3930 MULTIPATH_PREFERENCE_RELIABILITY,
3931 MULTIPATH_PREFERENCE_PERFORMANCE,
3932 })
3933 public @interface MultipathPreference {
3934 }
3935
3936 /**
3937 * Provides a hint to the calling application on whether it is desirable to use the
3938 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
3939 * for multipath data transfer on this network when it is not the system default network.
3940 * Applications desiring to use multipath network protocols should call this method before
3941 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003942 *
3943 * @param network The network on which the application desires to use multipath data.
3944 * If {@code null}, this method will return the a preference that will generally
3945 * apply to metered networks.
3946 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
3947 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003948 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003949 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003950 try {
3951 return mService.getMultipathPreference(network);
3952 } catch (RemoteException e) {
3953 throw e.rethrowFromSystemServer();
3954 }
3955 }
3956
3957 /**
Stuart Scott984dc852015-03-30 13:17:11 -07003958 * Resets all connectivity manager settings back to factory defaults.
3959 * @hide
3960 */
3961 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07003962 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07003963 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07003964 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003965 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07003966 }
3967 }
3968
3969 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003970 * Binds the current process to {@code network}. All Sockets created in the future
3971 * (and not explicitly bound via a bound SocketFactory from
3972 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3973 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3974 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3975 * work and all host name resolutions will fail. This is by design so an application doesn't
3976 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3977 * To clear binding pass {@code null} for {@code network}. Using individually bound
3978 * Sockets created by Network.getSocketFactory().createSocket() and
3979 * performing network-specific host name resolutions via
3980 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04003981 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003982 *
3983 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3984 * the current binding.
3985 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3986 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003987 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09003988 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04003989 // instantiated.
3990 return setProcessDefaultNetwork(network);
3991 }
3992
3993 /**
3994 * Binds the current process to {@code network}. All Sockets created in the future
3995 * (and not explicitly bound via a bound SocketFactory from
3996 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3997 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3998 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3999 * work and all host name resolutions will fail. This is by design so an application doesn't
4000 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4001 * To clear binding pass {@code null} for {@code network}. Using individually bound
4002 * Sockets created by Network.getSocketFactory().createSocket() and
4003 * performing network-specific host name resolutions via
4004 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4005 * {@code setProcessDefaultNetwork}.
4006 *
4007 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4008 * the current binding.
4009 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4010 * @deprecated This function can throw {@link IllegalStateException}. Use
4011 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4012 * is a direct replacement.
4013 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004014 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004015 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04004016 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004017 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4018
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09004019 if (netId != NETID_UNSET) {
4020 netId = network.getNetIdForResolv();
Paul Jensenc91b5342014-08-27 12:38:45 -04004021 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004022
4023 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4024 return false;
4025 }
4026
4027 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05004028 // Set HTTP proxy system properties to match network.
4029 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09004030 try {
4031 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4032 } catch (SecurityException e) {
4033 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4034 Log.e(TAG, "Can't set proxy properties", e);
4035 }
Paul Jensenc91b5342014-08-27 12:38:45 -04004036 // Must flush DNS cache as new network may have different DNS resolutions.
4037 InetAddress.clearDnsCache();
4038 // Must flush socket pool as idle sockets will be bound to previous network and may
4039 // cause subsequent fetches to be performed on old network.
4040 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04004041 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004042
4043 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004044 }
4045
4046 /**
4047 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004048 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004049 *
4050 * @return {@code Network} to which this process is bound, or {@code null}.
4051 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004052 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004053 public Network getBoundNetworkForProcess() {
4054 // Forcing callers to call thru non-static function ensures ConnectivityManager
4055 // instantiated.
4056 return getProcessDefaultNetwork();
4057 }
4058
4059 /**
4060 * Returns the {@link Network} currently bound to this process via
4061 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4062 *
4063 * @return {@code Network} to which this process is bound, or {@code null}.
4064 * @deprecated Using this function can lead to other functions throwing
4065 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4066 * {@code getBoundNetworkForProcess} is a direct replacement.
4067 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004068 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004069 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004070 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004071 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004072 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004073 return new Network(netId);
4074 }
4075
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004076 private void unsupportedStartingFrom(int version) {
4077 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004078 // The getApplicationInfo() call we make below is not supported in system context. Let
4079 // the call through here, and rely on the fact that ConnectivityService will refuse to
4080 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004081 return;
4082 }
4083
4084 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4085 throw new UnsupportedOperationException(
4086 "This method is not supported in target SDK version " + version + " and above");
4087 }
4088 }
4089
4090 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4091 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004092 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004093 // remove these exemptions. Note that this check is not secure, and apps can still access these
4094 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4095 // so is unsupported and may break in the future. http://b/22728205
4096 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004097 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004098 }
4099
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004100 /**
4101 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004102 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004103 *
4104 * @param network The {@link Network} to bind host resolutions from the current process to, or
4105 * {@code null} to clear the current binding.
4106 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4107 * @hide
4108 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4109 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004110 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004111 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004112 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004113 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004114 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004115 }
Felipe Leme1b103232016-01-22 09:44:57 -08004116
4117 /**
4118 * Device is not restricting metered network activity while application is running on
4119 * background.
4120 */
4121 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4122
4123 /**
4124 * Device is restricting metered network activity while application is running on background,
4125 * but application is allowed to bypass it.
4126 * <p>
4127 * In this state, application should take action to mitigate metered network access.
4128 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4129 */
4130 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4131
4132 /**
4133 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004134 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004135 * In this state, application should not try to use the network while running on background,
4136 * because it would be denied.
4137 */
4138 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4139
Felipe Leme9778f762016-01-27 14:46:39 -08004140 /**
4141 * A change in the background metered network activity restriction has occurred.
4142 * <p>
4143 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4144 * applies to them.
4145 * <p>
4146 * This is only sent to registered receivers, not manifest receivers.
4147 */
4148 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4149 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4150 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4151
Felipe Lemeecfccea2016-01-25 11:48:04 -08004152 /** @hide */
4153 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004154 @IntDef(flag = false, value = {
4155 RESTRICT_BACKGROUND_STATUS_DISABLED,
4156 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4157 RESTRICT_BACKGROUND_STATUS_ENABLED,
4158 })
Felipe Leme1b103232016-01-22 09:44:57 -08004159 public @interface RestrictBackgroundStatus {
4160 }
4161
4162 private INetworkPolicyManager getNetworkPolicyManager() {
4163 synchronized (this) {
4164 if (mNPManager != null) {
4165 return mNPManager;
4166 }
4167 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4168 .getService(Context.NETWORK_POLICY_SERVICE));
4169 return mNPManager;
4170 }
4171 }
4172
4173 /**
4174 * Determines if the calling application is subject to metered network restrictions while
4175 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004176 *
4177 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4178 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4179 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004180 */
4181 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4182 try {
4183 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4184 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004185 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004186 }
4187 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004188
4189 /**
4190 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004191 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4192 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004193 *
4194 * @return Hash of network watchlist config file. Null if config does not exist.
4195 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004196 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004197 public byte[] getNetworkWatchlistConfigHash() {
4198 try {
4199 return mService.getNetworkWatchlistConfigHash();
4200 } catch (RemoteException e) {
4201 Log.e(TAG, "Unable to get watchlist config hash");
4202 throw e.rethrowFromSystemServer();
4203 }
4204 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004205
4206 /**
4207 * Returns the {@code uid} of the owner of a network connection.
4208 *
4209 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and
4210 * {@code IPPROTO_UDP} currently supported.
4211 * @param local The local {@link InetSocketAddress} of a connection.
4212 * @param remote The remote {@link InetSocketAddress} of a connection.
4213 *
4214 * @return {@code uid} if the connection is found and the app has permission to observe it
4215 * (e.g., if it is associated with the calling VPN app's tunnel) or
4216 * {@link android.os.Process#INVALID_UID} if the connection is not found.
4217 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004218 public int getConnectionOwnerUid(int protocol, @NonNull InetSocketAddress local,
4219 @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004220 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4221 try {
4222 return mService.getConnectionOwnerUid(connectionInfo);
4223 } catch (RemoteException e) {
4224 throw e.rethrowFromSystemServer();
4225 }
4226 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004227
4228 private void printStackTrace() {
4229 if (DEBUG) {
4230 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4231 final StringBuffer sb = new StringBuffer();
4232 for (int i = 3; i < callStack.length; i++) {
4233 final String stackTrace = callStack[i].toString();
4234 if (stackTrace == null || stackTrace.contains("android.os")) {
4235 break;
4236 }
4237 sb.append(" [").append(stackTrace).append("]");
4238 }
4239 Log.d(TAG, "StackLog:" + sb.toString());
4240 }
4241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242}