blob: c809ccad59074aea9de6b236e9b931b16b59a08e [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
Felipe Leme1b103232016-01-22 09:44:57 -080018import android.annotation.IntDef;
Chalard Jean50bea3d2019-01-07 19:26:34 +090019import android.annotation.NonNull;
Robin Lee244ce8e2016-01-05 18:03:46 +000020import android.annotation.Nullable;
Jeff Sharkey30e06bb2017-04-24 11:18:03 -060021import android.annotation.RequiresPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.annotation.SdkConstant;
23import android.annotation.SdkConstant.SdkConstantType;
Udam Sainib7c24872016-01-04 12:16:14 -080024import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060025import android.annotation.SystemService;
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +090026import android.annotation.TestApi;
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010027import android.annotation.UnsupportedAppUsage;
Robert Greenwalt9258c642014-03-26 16:47:06 -070028import android.app.PendingIntent;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070029import android.content.Context;
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070030import android.content.Intent;
Robert Greenwalt42acef32009-08-12 16:08:25 -070031import android.os.Binder;
Mathew Inwood55418ea2018-12-20 15:30:45 +000032import android.os.Build;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070033import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080034import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070035import android.os.Handler;
36import android.os.HandlerThread;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080037import android.os.IBinder;
38import android.os.INetworkActivityListener;
39import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070040import android.os.Looper;
41import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070042import android.os.Messenger;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090043import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080045import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080046import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090047import android.os.ServiceSpecificException;
Jeff Sharkey961e3042011-08-29 16:02:57 -070048import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080049import android.telephony.SubscriptionManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080050import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070051import android.util.Log;
Erik Kline35bf06c2017-01-26 18:08:28 +090052import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053
Robert Greenwaltafa05c02014-05-21 20:04:36 -070054import com.android.internal.telephony.ITelephony;
Robert Greenwalt562cc542014-05-15 18:07:26 -070055import com.android.internal.telephony.PhoneConstants;
Hugo Benichidafed3d2017-03-06 09:17:06 +090056import com.android.internal.util.Preconditions;
57import com.android.internal.util.Protocol;
Robert Greenwaltafa05c02014-05-21 20:04:36 -070058
Paul Jensenc91b5342014-08-27 12:38:45 -040059import libcore.net.event.NetworkEventDispatcher;
60
Felipe Leme1b103232016-01-22 09:44:57 -080061import java.lang.annotation.Retention;
62import java.lang.annotation.RetentionPolicy;
Jeremy Kleind42209d2015-12-28 15:11:58 -080063import java.net.InetAddress;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070064import java.net.InetSocketAddress;
Hugo Benichidafed3d2017-03-06 09:17:06 +090065import java.util.ArrayList;
Jeremy Kleind42209d2015-12-28 15:11:58 -080066import java.util.HashMap;
Hugo Benichidafed3d2017-03-06 09:17:06 +090067import java.util.List;
68import java.util.Map;
Jeremy Kleind42209d2015-12-28 15:11:58 -080069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070/**
71 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060072 * notifies applications when network connectivity changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 * <p>
74 * The primary responsibilities of this class are to:
75 * <ol>
76 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
77 * <li>Send broadcast intents when network connectivity changes</li>
78 * <li>Attempt to "fail over" to another network when connectivity to a network
79 * is lost</li>
80 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
81 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070082 * <li>Provide an API that allows applications to request and select networks for their data
83 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 * </ol>
85 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060086@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070087public class ConnectivityManager {
88 private static final String TAG = "ConnectivityManager";
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +090089 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070092 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * been established or lost. The NetworkInfo for the affected network is
94 * sent as an extra; it should be consulted to see what kind of
95 * connectivity event occurred.
96 * <p/>
Mark Lu33ec1062016-12-05 10:57:55 -080097 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
98 * broadcast if they declare the broadcast receiver in their manifest. Apps
99 * will still receive broadcasts if they register their
100 * {@link android.content.BroadcastReceiver} with
101 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
102 * and that context is still valid.
103 * <p/>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 * If this is a connection that was the result of failing over from a
105 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
106 * set to true.
107 * <p/>
108 * For a loss of connectivity, if the connectivity manager is attempting
109 * to connect (or has already connected) to another network, the
110 * NetworkInfo for the new network is also passed as an extra. This lets
111 * any receivers of the broadcast know that they should not necessarily
112 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800113 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 * the failover attempt succeeded (and so there is still overall data
115 * connectivity), or that the failover attempt failed, meaning that all
116 * connectivity has been lost.
117 * <p/>
118 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
119 * is set to {@code true} if there are no connected networks at all.
Chalard Jean054cd162018-02-10 05:33:50 +0900120 *
121 * @deprecated apps should use the more versatile {@link #requestNetwork},
122 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
123 * functions instead for faster and more detailed updates about the network
124 * changes they care about.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800126 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean054cd162018-02-10 05:33:50 +0900127 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 /**
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700131 * A temporary hack until SUPL system can get off the legacy APIS.
132 * They do too many network requests and the long list of apps listening
Chalard Jean4d660112018-06-04 16:52:49 +0900133 * and waking due to the CONNECTIVITY_ACTION broadcast makes it expensive.
134 * Use this broadcast intent instead for SUPL requests.
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700135 * @hide
136 */
137 public static final String CONNECTIVITY_ACTION_SUPL =
138 "android.net.conn.CONNECTIVITY_CHANGE_SUPL";
139
140 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500141 * The device has connected to a network that has presented a captive
142 * portal, which is blocking Internet connectivity. The user was presented
143 * with a notification that network sign in is required,
144 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400145 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500146 * facilitate signing in to the network. This action includes a
147 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
148 * the network presenting the captive portal; all communication with the
149 * captive portal must be done using this {@code Network} object.
150 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400151 * This activity includes a {@link CaptivePortal} extra named
152 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
153 * outcomes of the captive portal sign in to the system:
154 * <ul>
155 * <li> When the app handling this action believes the user has signed in to
156 * the network and the captive portal has been dismissed, the app should
157 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
158 * reevaluate the network. If reevaluation finds the network no longer
159 * subject to a captive portal, the network may become the default active
Chalard Jean4d660112018-06-04 16:52:49 +0900160 * data network.</li>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400161 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500162 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400163 * {@link CaptivePortal#ignoreNetwork}. </li>
164 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500165 */
166 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
167 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
168
169 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 * The lookup key for a {@link NetworkInfo} object. Retrieve with
171 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700172 *
173 * @deprecated Since {@link NetworkInfo} can vary based on UID, applications
174 * should always obtain network information through
Paul Jensen3541e9f2015-03-18 12:23:02 -0400175 * {@link #getActiveNetworkInfo()}.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700176 * @see #EXTRA_NETWORK_TYPE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700178 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700182 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700183 *
184 * @see android.content.Intent#getIntExtra(String, int)
185 */
186 public static final String EXTRA_NETWORK_TYPE = "networkType";
187
188 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 * The lookup key for a boolean that indicates whether a connect event
190 * is for a network to which the connectivity manager was failing over
191 * following a disconnect on another network.
192 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai3822c8a2018-12-13 12:47:51 +0800193 *
194 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 */
junyulai3822c8a2018-12-13 12:47:51 +0800196 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 public static final String EXTRA_IS_FAILOVER = "isFailover";
198 /**
199 * The lookup key for a {@link NetworkInfo} object. This is supplied when
200 * there is another network that it may be possible to connect to. Retrieve with
201 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800202 *
203 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 */
junyulai3822c8a2018-12-13 12:47:51 +0800205 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
207 /**
208 * The lookup key for a boolean that indicates whether there is a
209 * complete lack of connectivity, i.e., no network is available.
210 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
211 */
212 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
213 /**
214 * The lookup key for a string that indicates why an attempt to connect
215 * to a network failed. The string has no particular structure. It is
216 * intended to be used in notifications presented to users. Retrieve
217 * it with {@link android.content.Intent#getStringExtra(String)}.
218 */
219 public static final String EXTRA_REASON = "reason";
220 /**
221 * The lookup key for a string that provides optionally supplied
222 * extra information about the network state. The information
223 * may be passed up from the lower networking layers, and its
224 * meaning may be specific to a particular network type. Retrieve
225 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800226 *
227 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 */
junyulai3822c8a2018-12-13 12:47:51 +0800229 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700231 /**
232 * The lookup key for an int that provides information about
233 * our connection to the internet at large. 0 indicates no connection,
234 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700235 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700236 * {@hide}
237 */
238 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400240 * The lookup key for a {@link CaptivePortal} object included with the
241 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
242 * object can be used to either indicate to the system that the captive
243 * portal has been dismissed or that the user does not want to pursue
244 * signing in to captive portal. Retrieve it with
245 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500246 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400247 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700248
249 /**
250 * Key for passing a URL to the captive portal login activity.
251 */
252 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
253
Paul Jensen25a217c2015-02-27 22:55:47 -0500254 /**
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900255 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
256 * portal login activity.
257 * {@hide}
258 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900259 @SystemApi
260 @TestApi
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900261 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
262 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
263
264 /**
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900265 * Key for passing a user agent string to the captive portal login activity.
266 * {@hide}
267 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900268 @SystemApi
269 @TestApi
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900270 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
271 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
272
273 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700274 * Broadcast action to indicate the change of data activity status
275 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800276 * The network becomes active when data transmission is started, or
277 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700278 * {@hide}
279 */
280 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean4d660112018-06-04 16:52:49 +0900281 public static final String ACTION_DATA_ACTIVITY_CHANGE =
282 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700283 /**
284 * The lookup key for an enum that indicates the network device type on which this data activity
285 * change happens.
286 * {@hide}
287 */
288 public static final String EXTRA_DEVICE_TYPE = "deviceType";
289 /**
290 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
291 * it is actively sending or receiving data and {@code false} means it is idle.
292 * {@hide}
293 */
294 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700295 /**
296 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
297 * {@hide}
298 */
299 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700300
301 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 * Broadcast Action: The setting for background data usage has changed
303 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
304 * <p>
305 * If an application uses the network in the background, it should listen
306 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700307 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800308 * <p>
309 *
310 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
311 * of background data depends on several combined factors, and
312 * this broadcast is no longer sent. Instead, when background
313 * data is unavailable, {@link #getActiveNetworkInfo()} will now
314 * appear disconnected. During first boot after a platform
315 * upgrade, this broadcast will be sent once if
316 * {@link #getBackgroundDataSetting()} was {@code false} before
317 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 */
319 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800320 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
322 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
323
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700324 /**
325 * Broadcast Action: The network connection may not be good
326 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
327 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
328 * the network and it's condition.
329 * @hide
330 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800331 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100332 @UnsupportedAppUsage
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700333 public static final String INET_CONDITION_ACTION =
334 "android.net.conn.INET_CONDITION_ACTION";
335
Robert Greenwalt42acef32009-08-12 16:08:25 -0700336 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800337 * Broadcast Action: A tetherable connection has come or gone.
338 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline8351faa2017-04-17 16:47:23 +0900339 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
340 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800341 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
342 * the current state of tethering. Each include a list of
343 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800344 * @hide
345 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800346 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100347 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800348 public static final String ACTION_TETHER_STATE_CHANGED =
349 "android.net.conn.TETHER_STATE_CHANGED";
350
351 /**
352 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800353 * gives a String[] listing all the interfaces configured for
354 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800355 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100356 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800357 public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800358
359 /**
360 * @hide
Erik Kline8351faa2017-04-17 16:47:23 +0900361 * gives a String[] listing all the interfaces currently in local-only
362 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800363 */
Erik Kline8351faa2017-04-17 16:47:23 +0900364 public static final String EXTRA_ACTIVE_LOCAL_ONLY = "localOnlyArray";
365
366 /**
367 * @hide
368 * gives a String[] listing all the interfaces currently tethered
369 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
370 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100371 @UnsupportedAppUsage
Erik Kline8351faa2017-04-17 16:47:23 +0900372 public static final String EXTRA_ACTIVE_TETHER = "tetherArray";
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800373
374 /**
375 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800376 * gives a String[] listing all the interfaces we tried to tether and
377 * failed. Use {@link #getLastTetherError} to find the error code
378 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800379 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100380 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800381 public static final String EXTRA_ERRORED_TETHER = "erroredArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800382
383 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800384 * Broadcast Action: The captive portal tracker has finished its test.
385 * Sent only while running Setup Wizard, in lieu of showing a user
386 * notification.
387 * @hide
388 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800389 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800390 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
391 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
392 /**
393 * The lookup key for a boolean that indicates whether a captive portal was detected.
394 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
395 * @hide
396 */
397 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
398
399 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900400 * Action used to display a dialog that asks the user whether to connect to a network that is
401 * not validated. This intent is used to start the dialog in settings via startActivity.
402 *
403 * @hide
404 */
405 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
406
407 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900408 * Action used to display a dialog that asks the user whether to avoid a network that is no
409 * longer validated. This intent is used to start the dialog in settings via startActivity.
410 *
411 * @hide
412 */
413 public static final String ACTION_PROMPT_LOST_VALIDATION =
414 "android.net.conn.PROMPT_LOST_VALIDATION";
415
416 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800417 * Invalid tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900418 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800419 * @hide
420 */
421 public static final int TETHERING_INVALID = -1;
422
423 /**
424 * Wifi tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900425 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800426 * @hide
427 */
428 @SystemApi
429 public static final int TETHERING_WIFI = 0;
430
431 /**
432 * USB tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900433 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800434 * @hide
435 */
436 @SystemApi
437 public static final int TETHERING_USB = 1;
438
439 /**
440 * Bluetooth tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900441 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800442 * @hide
443 */
444 @SystemApi
445 public static final int TETHERING_BLUETOOTH = 2;
446
447 /**
448 * Extra used for communicating with the TetherService. Includes the type of tethering to
449 * enable if any.
450 * @hide
451 */
452 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
453
454 /**
455 * Extra used for communicating with the TetherService. Includes the type of tethering for
456 * which to cancel provisioning.
457 * @hide
458 */
459 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
460
461 /**
462 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
463 * provisioning.
464 * @hide
465 */
466 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
467
468 /**
469 * Tells the TetherService to run a provision check now.
470 * @hide
471 */
472 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
473
474 /**
475 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
476 * which will receive provisioning results. Can be left empty.
477 * @hide
478 */
479 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
480
481 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800482 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700483 * @hide
484 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100485 @UnsupportedAppUsage
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700486 public static final int TYPE_NONE = -1;
487
488 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900489 * A Mobile data connection. Devices may support more than one.
490 *
491 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
492 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
493 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700494 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900495 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700496 public static final int TYPE_MOBILE = 0;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900497
Robert Greenwalt42acef32009-08-12 16:08:25 -0700498 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900499 * A WIFI data connection. Devices may support more than one.
500 *
501 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
502 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
503 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700504 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900505 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700506 public static final int TYPE_WIFI = 1;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900507
Robert Greenwalt42acef32009-08-12 16:08:25 -0700508 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800509 * An MMS-specific Mobile data connection. This network type may use the
510 * same network interface as {@link #TYPE_MOBILE} or it may use a different
511 * one. This is used by applications needing to talk to the carrier's
512 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900513 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900514 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900515 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900516 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700517 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700518 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700519 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900520
Robert Greenwalt42acef32009-08-12 16:08:25 -0700521 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800522 * A SUPL-specific Mobile data connection. This network type may use the
523 * same network interface as {@link #TYPE_MOBILE} or it may use a different
524 * one. This is used by applications needing to talk to the carrier's
525 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900526 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900527 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900528 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900529 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700530 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700531 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700532 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900533
Robert Greenwalt42acef32009-08-12 16:08:25 -0700534 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800535 * A DUN-specific Mobile data connection. This network type may use the
536 * same network interface as {@link #TYPE_MOBILE} or it may use a different
537 * one. This is sometimes by the system when setting up an upstream connection
538 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900539 *
540 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
541 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
542 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700543 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900544 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700545 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900546
Robert Greenwalt42acef32009-08-12 16:08:25 -0700547 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800548 * A High Priority Mobile data connection. This network type uses the
549 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900550 * is different.
551 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900552 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
553 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
554 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700555 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700556 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700557 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900558
jsh8214deb2010-03-11 15:04:43 -0800559 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900560 * A WiMAX data connection.
561 *
562 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
563 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
564 * appropriate network. {@see NetworkCapabilities} for supported transports.
jsh8214deb2010-03-11 15:04:43 -0800565 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900566 @Deprecated
jsh8214deb2010-03-11 15:04:43 -0800567 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800568
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800569 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900570 * A Bluetooth data connection.
571 *
572 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
573 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
574 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800575 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900576 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800577 public static final int TYPE_BLUETOOTH = 7;
578
Robert Greenwalt60810842011-04-22 15:28:18 -0700579 /**
580 * Dummy data connection. This should not be used on shipping devices.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900581 * @deprecated This is not used any more.
Robert Greenwalt60810842011-04-22 15:28:18 -0700582 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900583 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800584 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800585
Robert Greenwalt60810842011-04-22 15:28:18 -0700586 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900587 * An Ethernet data connection.
588 *
589 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
590 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
591 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt60810842011-04-22 15:28:18 -0700592 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900593 @Deprecated
Robert Greenwalte12aec92011-01-28 14:48:37 -0800594 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700595
Wink Saville9d7d6282011-03-12 14:52:01 -0800596 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800597 * Over the air Administration.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900598 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800599 * {@hide}
600 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900601 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100602 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800603 public static final int TYPE_MOBILE_FOTA = 10;
604
605 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800606 * IP Multimedia Subsystem.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900607 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800608 * {@hide}
609 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900610 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100611 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800612 public static final int TYPE_MOBILE_IMS = 11;
613
614 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800615 * Carrier Branded Services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900616 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800617 * {@hide}
618 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900619 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100620 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800621 public static final int TYPE_MOBILE_CBS = 12;
622
repo syncaea743a2011-07-29 23:55:49 -0700623 /**
624 * A Wi-Fi p2p connection. Only requesting processes will have access to
625 * the peers connected.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900626 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncaea743a2011-07-29 23:55:49 -0700627 * {@hide}
628 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900629 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100630 @UnsupportedAppUsage
repo syncaea743a2011-07-29 23:55:49 -0700631 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800632
Wink Saville5e56bc52013-07-29 15:00:57 -0700633 /**
634 * The network to use for initially attaching to the network
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900635 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville5e56bc52013-07-29 15:00:57 -0700636 * {@hide}
637 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900638 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100639 @UnsupportedAppUsage
Wink Saville5e56bc52013-07-29 15:00:57 -0700640 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700641
Lorenzo Colittie285b432015-04-23 15:32:42 +0900642 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700643 * Emergency PDN connection for emergency services. This
644 * may include IMS and MMS in emergency situations.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900645 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram3e0e3bc2014-06-26 11:03:44 -0700646 * {@hide}
647 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900648 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100649 @UnsupportedAppUsage
Ram3e0e3bc2014-06-26 11:03:44 -0700650 public static final int TYPE_MOBILE_EMERGENCY = 15;
651
Hui Lu1c5624a2014-01-15 11:05:36 -0500652 /**
653 * The network that uses proxy to achieve connectivity.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900654 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu1c5624a2014-01-15 11:05:36 -0500655 * {@hide}
656 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900657 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100658 @UnsupportedAppUsage
Hui Lu1c5624a2014-01-15 11:05:36 -0500659 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700660
Robert Greenwalt8283f882014-07-07 17:09:01 -0700661 /**
662 * A virtual network using one or more native bearers.
663 * It may or may not be providing security services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900664 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700665 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900666 @Deprecated
Robert Greenwalt8283f882014-07-07 17:09:01 -0700667 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500668
669 /** {@hide} */
Robert Greenwalt8283f882014-07-07 17:09:01 -0700670 public static final int MAX_RADIO_TYPE = TYPE_VPN;
671
672 /** {@hide} */
673 public static final int MAX_NETWORK_TYPE = TYPE_VPN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674
Hugo Benichi16f0a942017-06-20 14:07:59 +0900675 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
676
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800677 /**
678 * If you want to set the default network preference,you can directly
679 * change the networkAttributes array in framework's config.xml.
680 *
681 * @deprecated Since we support so many more networks now, the single
682 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800683 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800684 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800685 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800686 * from an App.
687 */
688 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
690
Jeff Sharkey625239a2012-09-26 22:03:49 -0700691 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700692 * @hide
693 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900694 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700695
Paul Jensen5d59e782014-07-11 12:28:19 -0400696 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900697 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
698 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean4d660112018-06-04 16:52:49 +0900699 * registered from those that were already unregistered.
Hugo Benichi31c176d2017-06-17 13:14:12 +0900700 * @hide
701 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900702 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900703 new NetworkRequest.Builder().clearCapabilities().build();
704
705 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400706 * A NetID indicating no Network is selected.
707 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
708 * @hide
709 */
710 public static final int NETID_UNSET = 0;
711
Erik Kline4d092232017-10-30 15:29:44 +0900712 /**
713 * Private DNS Mode values.
714 *
715 * The "private_dns_mode" global setting stores a String value which is
716 * expected to be one of the following.
717 */
718
719 /**
720 * @hide
721 */
722 public static final String PRIVATE_DNS_MODE_OFF = "off";
723 /**
724 * @hide
725 */
726 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
727 /**
728 * @hide
729 */
730 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
731 /**
732 * The default Private DNS mode.
733 *
734 * This may change from release to release or may become dependent upon
735 * the capabilities of the underlying platform.
736 *
737 * @hide
738 */
Erik Kline19841792018-05-16 16:41:57 +0900739 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline4d092232017-10-30 15:29:44 +0900740
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100741 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700742 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500743 /**
744 * A kludge to facilitate static access where a Context pointer isn't available, like in the
745 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
746 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
747 * methods that take a Context argument.
748 */
749 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900751 private final Context mContext;
752
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800753 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800754 private INetworkPolicyManager mNPManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800755
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800756 /**
757 * Tests if a given integer represents a valid network type.
758 * @param networkType the type to be tested
759 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400760 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
761 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800762 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700763 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700764 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900765 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 }
767
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800768 /**
769 * Returns a non-localized string representing a given network type.
770 * ONLY used for debugging output.
771 * @param type the type needing naming
772 * @return a String for the given type, or a string version of the type ("87")
773 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900774 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800775 * {@hide}
776 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900777 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100778 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700779 public static String getNetworkTypeName(int type) {
780 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900781 case TYPE_NONE:
782 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700783 case TYPE_MOBILE:
784 return "MOBILE";
785 case TYPE_WIFI:
786 return "WIFI";
787 case TYPE_MOBILE_MMS:
788 return "MOBILE_MMS";
789 case TYPE_MOBILE_SUPL:
790 return "MOBILE_SUPL";
791 case TYPE_MOBILE_DUN:
792 return "MOBILE_DUN";
793 case TYPE_MOBILE_HIPRI:
794 return "MOBILE_HIPRI";
795 case TYPE_WIMAX:
796 return "WIMAX";
797 case TYPE_BLUETOOTH:
798 return "BLUETOOTH";
799 case TYPE_DUMMY:
800 return "DUMMY";
801 case TYPE_ETHERNET:
802 return "ETHERNET";
803 case TYPE_MOBILE_FOTA:
804 return "MOBILE_FOTA";
805 case TYPE_MOBILE_IMS:
806 return "MOBILE_IMS";
807 case TYPE_MOBILE_CBS:
808 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700809 case TYPE_WIFI_P2P:
810 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700811 case TYPE_MOBILE_IA:
812 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700813 case TYPE_MOBILE_EMERGENCY:
814 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500815 case TYPE_PROXY:
816 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900817 case TYPE_VPN:
818 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700819 default:
820 return Integer.toString(type);
821 }
822 }
823
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800824 /**
825 * Checks if a given type uses the cellular data connection.
826 * This should be replaced in the future by a network property.
827 * @param networkType the type to check
828 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900829 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800830 * {@hide}
831 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900832 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100833 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700834 public static boolean isNetworkTypeMobile(int networkType) {
835 switch (networkType) {
836 case TYPE_MOBILE:
837 case TYPE_MOBILE_MMS:
838 case TYPE_MOBILE_SUPL:
839 case TYPE_MOBILE_DUN:
840 case TYPE_MOBILE_HIPRI:
841 case TYPE_MOBILE_FOTA:
842 case TYPE_MOBILE_IMS:
843 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700844 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700845 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700846 return true;
847 default:
848 return false;
849 }
850 }
851
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800852 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700853 * Checks if the given network type is backed by a Wi-Fi radio.
854 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900855 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700856 * @hide
857 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900858 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700859 public static boolean isNetworkTypeWifi(int networkType) {
860 switch (networkType) {
861 case TYPE_WIFI:
862 case TYPE_WIFI_P2P:
863 return true;
864 default:
865 return false;
866 }
867 }
868
869 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800870 * Specifies the preferred network type. When the device has more
871 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800872 *
873 * @param preference the network type to prefer over all others. It is
874 * unspecified what happens to the old preferred network in the
875 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700876 * @deprecated Functionality has been removed as it no longer makes sense,
877 * with many more than two networks - we'd need an array to express
878 * preference. Instead we use dynamic network properties of
879 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800880 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700881 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
884
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800885 /**
886 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800887 *
888 * @return an integer representing the preferred network type
889 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700890 * @deprecated Functionality has been removed as it no longer makes sense,
891 * with many more than two networks - we'd need an array to express
892 * preference. Instead we use dynamic network properties of
893 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800894 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700895 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600896 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700898 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 }
900
Scott Main671644c2011-10-06 19:02:28 -0700901 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800902 * Returns details about the currently active default data network. When
903 * connected, this network is the default route for outgoing connections.
904 * You should always check {@link NetworkInfo#isConnected()} before initiating
905 * network traffic. This may return {@code null} when there is no default
906 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900907 * Note that if the default network is a VPN, this method will return the
908 * NetworkInfo for one of its underlying networks instead, or null if the
909 * VPN agent did not specify any. Apps interested in learning about VPNs
910 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800911 *
912 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500913 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800914 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700915 */
junyulai3822c8a2018-12-13 12:47:51 +0800916 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600917 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900918 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 public NetworkInfo getActiveNetworkInfo() {
920 try {
921 return mService.getActiveNetworkInfo();
922 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700923 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 }
925 }
926
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800927 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500928 * Returns a {@link Network} object corresponding to the currently active
929 * default data network. In the event that the current active default data
930 * network disconnects, the returned {@code Network} object will no longer
931 * be usable. This will return {@code null} when there is no default
932 * network.
933 *
934 * @return a {@link Network} object for the current default network or
935 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500936 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600937 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900938 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -0500939 public Network getActiveNetwork() {
940 try {
941 return mService.getActiveNetwork();
942 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700943 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500944 }
945 }
946
947 /**
Robin Leed2baf792016-03-24 12:07:00 +0000948 * Returns a {@link Network} object corresponding to the currently active
949 * default data network for a specific UID. In the event that the default data
950 * network disconnects, the returned {@code Network} object will no longer
951 * be usable. This will return {@code null} when there is no default
952 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +0000953 *
954 * @return a {@link Network} object for the current default network for the
955 * given UID or {@code null} if no default network is currently active
956 *
957 * @hide
958 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600959 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900960 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +0000961 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600962 return getActiveNetworkForUid(uid, false);
963 }
964
965 /** {@hide} */
966 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +0000967 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600968 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +0000969 } catch (RemoteException e) {
970 throw e.rethrowFromSystemServer();
971 }
972 }
973
974 /**
Charles He36738632017-05-15 17:07:18 +0100975 * Checks if a VPN app supports always-on mode.
976 *
977 * In order to support the always-on feature, an app has to
978 * <ul>
979 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +0100980 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
981 * meta-data field.
Charles He36738632017-05-15 17:07:18 +0100982 * </ul>
983 *
984 * @param userId The identifier of the user for whom the VPN app is installed.
985 * @param vpnPackage The canonical package name of the VPN app.
986 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
987 * @hide
988 */
989 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
990 try {
991 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
992 } catch (RemoteException e) {
993 throw e.rethrowFromSystemServer();
994 }
995 }
996
997 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000998 * Configures an always-on VPN connection through a specific application.
999 * This connection is automatically granted and persisted after a reboot.
1000 *
1001 * <p>The designated package should declare a {@link VpnService} in its
1002 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1003 * otherwise the call will fail.
1004 *
1005 * @param userId The identifier of the user to set an always-on VPN for.
1006 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1007 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001008 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1009 * {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00001010 * @return {@code true} if the package is set as always-on VPN controller;
1011 * {@code false} otherwise.
1012 * @hide
1013 */
Robin Leedc679712016-05-03 13:23:03 +01001014 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
1015 boolean lockdownEnabled) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001016 try {
Robin Leedc679712016-05-03 13:23:03 +01001017 return mService.setAlwaysOnVpnPackage(userId, vpnPackage, lockdownEnabled);
Robin Lee244ce8e2016-01-05 18:03:46 +00001018 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001019 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001020 }
1021 }
1022
1023 /**
1024 * Returns the package name of the currently set always-on VPN application.
1025 * If there is no always-on VPN set, or the VPN is provided by the system instead
1026 * of by an app, {@code null} will be returned.
1027 *
1028 * @return Package name of VPN controller responsible for always-on VPN,
1029 * or {@code null} if none is set.
1030 * @hide
1031 */
1032 public String getAlwaysOnVpnPackageForUser(int userId) {
1033 try {
1034 return mService.getAlwaysOnVpnPackage(userId);
1035 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001036 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001037 }
1038 }
1039
1040 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001041 * Returns details about the currently active default data network
1042 * for a given uid. This is for internal use only to avoid spying
1043 * other apps.
1044 *
1045 * @return a {@link NetworkInfo} object for the current default network
1046 * for the given uid or {@code null} if no default network is
1047 * available for the specified uid.
1048 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001049 * {@hide}
1050 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001051 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001052 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001053 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001054 return getActiveNetworkInfoForUid(uid, false);
1055 }
1056
1057 /** {@hide} */
1058 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001059 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001060 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001061 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001062 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001063 }
1064 }
1065
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001066 /**
1067 * Returns connection status information about a particular
1068 * network type.
1069 *
1070 * @param networkType integer specifying which networkType in
1071 * which you're interested.
1072 * @return a {@link NetworkInfo} object for the requested
1073 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001074 * supported by the device. If {@code networkType} is
1075 * TYPE_VPN and a VPN is active for the calling app,
1076 * then this method will try to return one of the
1077 * underlying networks for the VPN or null if the
1078 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001079 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001080 * @deprecated This method does not support multiple connected networks
1081 * of the same type. Use {@link #getAllNetworks} and
1082 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001083 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001084 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001085 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001086 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 public NetworkInfo getNetworkInfo(int networkType) {
1088 try {
1089 return mService.getNetworkInfo(networkType);
1090 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001091 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
1093 }
1094
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001095 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001096 * Returns connection status information about a particular
1097 * Network.
1098 *
1099 * @param network {@link Network} specifying which network
1100 * in which you're interested.
1101 * @return a {@link NetworkInfo} object for the requested
1102 * network or {@code null} if the {@code Network}
1103 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001104 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001105 */
junyulai3822c8a2018-12-13 12:47:51 +08001106 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001107 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001108 @Nullable
1109 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001110 return getNetworkInfoForUid(network, Process.myUid(), false);
1111 }
1112
1113 /** {@hide} */
1114 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001115 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001116 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001117 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001118 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001119 }
1120 }
1121
1122 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001123 * Returns connection status information about all network
1124 * types supported by the device.
1125 *
1126 * @return an array of {@link NetworkInfo} objects. Check each
1127 * {@link NetworkInfo#getType} for which type each applies.
1128 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001129 * @deprecated This method does not support multiple connected networks
1130 * of the same type. Use {@link #getAllNetworks} and
1131 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001132 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001133 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001134 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001135 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 public NetworkInfo[] getAllNetworkInfo() {
1137 try {
1138 return mService.getAllNetworkInfo();
1139 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001140 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 }
1142 }
1143
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001144 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001145 * Returns the {@link Network} object currently serving a given type, or
1146 * null if the given type is not connected.
1147 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001148 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001149 * @deprecated This method does not support multiple connected networks
1150 * of the same type. Use {@link #getAllNetworks} and
1151 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001152 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001153 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001154 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001155 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001156 public Network getNetworkForType(int networkType) {
1157 try {
1158 return mService.getNetworkForType(networkType);
1159 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001160 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001161 }
1162 }
1163
1164 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001165 * Returns an array of all {@link Network} currently tracked by the
1166 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001167 *
1168 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001169 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001170 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001171 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001172 public Network[] getAllNetworks() {
1173 try {
1174 return mService.getAllNetworks();
1175 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001176 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001177 }
1178 }
1179
1180 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001181 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001182 * the Networks that applications run by the given user will use by default.
1183 * @hide
1184 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001185 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001186 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1187 try {
1188 return mService.getDefaultNetworkCapabilitiesForUser(userId);
1189 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001190 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001191 }
1192 }
1193
1194 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001195 * Returns the IP information for the current default network.
1196 *
1197 * @return a {@link LinkProperties} object describing the IP info
1198 * for the current default network, or {@code null} if there
1199 * is no current default network.
1200 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001201 * {@hide}
1202 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001203 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001204 @UnsupportedAppUsage
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001205 public LinkProperties getActiveLinkProperties() {
1206 try {
1207 return mService.getActiveLinkProperties();
1208 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001209 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001210 }
1211 }
1212
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001213 /**
1214 * Returns the IP information for a given network type.
1215 *
1216 * @param networkType the network type of interest.
1217 * @return a {@link LinkProperties} object describing the IP info
1218 * for the given networkType, or {@code null} if there is
1219 * no current default network.
1220 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001221 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001222 * @deprecated This method does not support multiple connected networks
1223 * of the same type. Use {@link #getAllNetworks},
1224 * {@link #getNetworkInfo(android.net.Network)}, and
1225 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001226 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001227 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001228 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001229 @UnsupportedAppUsage
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001230 public LinkProperties getLinkProperties(int networkType) {
1231 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001232 return mService.getLinkPropertiesForType(networkType);
1233 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001234 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001235 }
1236 }
1237
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001238 /**
1239 * Get the {@link LinkProperties} for the given {@link Network}. This
1240 * will return {@code null} if the network is unknown.
1241 *
1242 * @param network The {@link Network} object identifying the network in question.
1243 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001244 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001245 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001246 @Nullable
1247 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001248 try {
1249 return mService.getLinkProperties(network);
1250 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001251 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001252 }
1253 }
1254
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001255 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001256 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001257 * will return {@code null} if the network is unknown.
1258 *
1259 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001260 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001261 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001262 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001263 @Nullable
1264 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001265 try {
1266 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001267 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001268 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001269 }
1270 }
1271
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001272 /**
Udam Sainib7c24872016-01-04 12:16:14 -08001273 * Gets the URL that should be used for resolving whether a captive portal is present.
1274 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1275 * portal is present.
1276 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1277 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1278 *
1279 * @hide
1280 */
1281 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07001282 @RequiresPermission(android.Manifest.permission.LOCAL_MAC_ADDRESS)
Udam Sainib7c24872016-01-04 12:16:14 -08001283 public String getCaptivePortalServerUrl() {
1284 try {
1285 return mService.getCaptivePortalServerUrl();
1286 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001287 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001288 }
1289 }
1290
1291 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 * Tells the underlying networking system that the caller wants to
1293 * begin using the named feature. The interpretation of {@code feature}
1294 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001295 *
1296 * <p>This method requires the caller to hold either the
1297 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1298 * or the ability to modify system settings as determined by
1299 * {@link android.provider.Settings.System#canWrite}.</p>
1300 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 * @param networkType specifies which network the request pertains to
1302 * @param feature the name of the feature to be used
1303 * @return an integer value representing the outcome of the request.
1304 * The interpretation of this value is specific to each networking
1305 * implementation+feature combination, except that the value {@code -1}
1306 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001307 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001308 * @deprecated Deprecated in favor of the cleaner
1309 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001310 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001311 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001312 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001314 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001316 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001317 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1318 if (netCap == null) {
1319 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1320 feature);
1321 return PhoneConstants.APN_REQUEST_FAILED;
1322 }
1323
1324 NetworkRequest request = null;
1325 synchronized (sLegacyRequests) {
1326 LegacyRequest l = sLegacyRequests.get(netCap);
1327 if (l != null) {
1328 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1329 renewRequestLocked(l);
1330 if (l.currentNetwork != null) {
1331 return PhoneConstants.APN_ALREADY_ACTIVE;
1332 } else {
1333 return PhoneConstants.APN_REQUEST_STARTED;
1334 }
1335 }
1336
1337 request = requestNetworkForFeatureLocked(netCap);
1338 }
1339 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001340 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001341 return PhoneConstants.APN_REQUEST_STARTED;
1342 } else {
1343 Log.d(TAG, " request Failed");
1344 return PhoneConstants.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 }
1346 }
1347
1348 /**
1349 * Tells the underlying networking system that the caller is finished
1350 * using the named feature. The interpretation of {@code feature}
1351 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001352 *
1353 * <p>This method requires the caller to hold either the
1354 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1355 * or the ability to modify system settings as determined by
1356 * {@link android.provider.Settings.System#canWrite}.</p>
1357 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 * @param networkType specifies which network the request pertains to
1359 * @param feature the name of the feature that is no longer needed
1360 * @return an integer value representing the outcome of the request.
1361 * The interpretation of this value is specific to each networking
1362 * implementation+feature combination, except that the value {@code -1}
1363 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001364 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001365 * @deprecated Deprecated in favor of the cleaner
1366 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001367 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001368 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001369 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001371 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001373 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001374 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1375 if (netCap == null) {
1376 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1377 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 return -1;
1379 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001380
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001381 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001382 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001383 }
1384 return 1;
1385 }
1386
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001387 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001388 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1389 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001390 switch (feature) {
1391 case "enableCBS":
1392 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1393 case "enableDUN":
1394 case "enableDUNAlways":
1395 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1396 case "enableFOTA":
1397 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1398 case "enableHIPRI":
1399 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1400 case "enableIMS":
1401 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1402 case "enableMMS":
1403 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1404 case "enableSUPL":
1405 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1406 default:
1407 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001408 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001409 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1410 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001411 }
1412 return null;
1413 }
1414
Robert Greenwalt06314e42014-10-29 14:04:06 -07001415 /**
1416 * Guess what the network request was trying to say so that the resulting
1417 * network is accessible via the legacy (deprecated) API such as
1418 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001419 *
1420 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001421 * capability but ignore things such as networkSpecifier.
1422 * If the request has more than one transport or capability it doesn't
1423 * match the old legacy requests (they selected only single transport/capability)
1424 * so this function cannot map the request to a single legacy type and
1425 * the resulting network will not be available to the legacy APIs.
1426 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001427 * This code is only called from the requestNetwork API (L and above).
1428 *
1429 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1430 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1431 * do this for SUPL requests, which are the only ones that we know need it. If
1432 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1433 * compatibility we can send them:
1434 *
1435 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1436 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1437 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001438 * TODO - This should be removed when the legacy APIs are removed.
1439 */
Ye Wenb87875e2014-07-21 14:19:01 -07001440 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1441 if (netCap == null) {
1442 return TYPE_NONE;
1443 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001444
Ye Wenb87875e2014-07-21 14:19:01 -07001445 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1446 return TYPE_NONE;
1447 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001448
Lifu Tang30f95a72016-01-07 23:20:38 -08001449 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001450 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1451 // NOTE: if this causes app breakage, we should not just comment out this early return;
1452 // instead, we should make this early return conditional on the requesting app's target
1453 // SDK version, as described in the comment above.
1454 return TYPE_NONE;
1455 }
1456
Robert Greenwalt06314e42014-10-29 14:04:06 -07001457 String type = null;
1458 int result = TYPE_NONE;
1459
Ye Wenb87875e2014-07-21 14:19:01 -07001460 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001461 type = "enableCBS";
1462 result = TYPE_MOBILE_CBS;
1463 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1464 type = "enableIMS";
1465 result = TYPE_MOBILE_IMS;
1466 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1467 type = "enableFOTA";
1468 result = TYPE_MOBILE_FOTA;
1469 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1470 type = "enableDUN";
1471 result = TYPE_MOBILE_DUN;
1472 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001473 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001474 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001475 // back out this hack for mms as they no longer need this and it's causing
1476 // device slowdowns - b/23350688 (note, supl still needs this)
1477 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1478 // type = "enableMMS";
1479 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001480 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1481 type = "enableHIPRI";
1482 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001483 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001484 if (type != null) {
1485 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1486 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1487 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001488 }
1489 }
1490 return TYPE_NONE;
1491 }
1492
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001493 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001494 if (netCap == null) return TYPE_NONE;
1495 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1496 return TYPE_MOBILE_CBS;
1497 }
1498 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1499 return TYPE_MOBILE_IMS;
1500 }
1501 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1502 return TYPE_MOBILE_FOTA;
1503 }
1504 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1505 return TYPE_MOBILE_DUN;
1506 }
1507 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1508 return TYPE_MOBILE_SUPL;
1509 }
1510 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1511 return TYPE_MOBILE_MMS;
1512 }
1513 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1514 return TYPE_MOBILE_HIPRI;
1515 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001516 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1517 return TYPE_WIFI_P2P;
1518 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001519 return TYPE_NONE;
1520 }
1521
1522 private static class LegacyRequest {
1523 NetworkCapabilities networkCapabilities;
1524 NetworkRequest networkRequest;
1525 int expireSequenceNumber;
1526 Network currentNetwork;
1527 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001528
1529 private void clearDnsBinding() {
1530 if (currentNetwork != null) {
1531 currentNetwork = null;
1532 setProcessDefaultNetworkForHostResolution(null);
1533 }
1534 }
1535
Robert Greenwalt6078b502014-06-11 16:05:07 -07001536 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001537 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001538 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001539 currentNetwork = network;
1540 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001541 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001542 }
1543 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001544 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001545 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001546 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1547 }
1548 };
1549 }
1550
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001551 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001552 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1553 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001554
1555 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1556 synchronized (sLegacyRequests) {
1557 LegacyRequest l = sLegacyRequests.get(netCap);
1558 if (l != null) return l.networkRequest;
1559 }
1560 return null;
1561 }
1562
1563 private void renewRequestLocked(LegacyRequest l) {
1564 l.expireSequenceNumber++;
1565 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1566 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1567 }
1568
1569 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1570 int ourSeqNum = -1;
1571 synchronized (sLegacyRequests) {
1572 LegacyRequest l = sLegacyRequests.get(netCap);
1573 if (l == null) return;
1574 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001575 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001576 }
1577 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1578 }
1579
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001580 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001581 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1582 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001583 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001584 try {
1585 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001586 } catch (RemoteException e) {
1587 throw e.rethrowFromSystemServer();
1588 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001589 LegacyRequest l = new LegacyRequest();
1590 l.networkCapabilities = netCap;
1591 l.delay = delay;
1592 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001593 l.networkRequest = sendRequestForNetwork(
1594 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001595 if (l.networkRequest == null) return null;
1596 sLegacyRequests.put(netCap, l);
1597 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1598 return l.networkRequest;
1599 }
1600
1601 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1602 if (delay >= 0) {
1603 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001604 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001605 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1606 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001607 }
1608 }
1609
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001610 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001611 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1612 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001613 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001614 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001615 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001616 if (l == null) return false;
1617 unregisterNetworkCallback(l.networkCallback);
1618 l.clearDnsBinding();
1619 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 }
1621
Erik Kline35bf06c2017-01-26 18:08:28 +09001622 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1623 static {
1624 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1625 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1626 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1627 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1628 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1629 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1630 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1631 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1632 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1633 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1634 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1635 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1636 }
1637
1638 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1639 static {
1640 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1641 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1642 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1643 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1644 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1645 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1646 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1647 }
1648
1649 /**
1650 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1651 * instance suitable for registering a request or callback. Throws an
1652 * IllegalArgumentException if no mapping from the legacy type to
1653 * NetworkCapabilities is known.
1654 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001655 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1656 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001657 * @hide
1658 */
1659 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1660 final NetworkCapabilities nc = new NetworkCapabilities();
1661
1662 // Map from type to transports.
1663 final int NOT_FOUND = -1;
1664 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001665 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001666 nc.addTransportType(transport);
1667
1668 // Map from type to capabilities.
1669 nc.addCapability(sLegacyTypeToCapability.get(
1670 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1671 nc.maybeMarkCapabilitiesRestricted();
1672 return nc;
1673 }
1674
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001675 /** @hide */
1676 public static class PacketKeepaliveCallback {
1677 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001678 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001679 public void onStarted() {}
1680 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001681 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001682 public void onStopped() {}
1683 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001684 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001685 public void onError(int error) {}
1686 }
1687
1688 /**
1689 * Allows applications to request that the system periodically send specific packets on their
1690 * behalf, using hardware offload to save battery power.
1691 *
1692 * To request that the system send keepalives, call one of the methods that return a
1693 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1694 * passing in a non-null callback. If the callback is successfully started, the callback's
1695 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1696 * specifying one of the {@code ERROR_*} constants in this class.
1697 *
Chalard Jean4d660112018-06-04 16:52:49 +09001698 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1699 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1700 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001701 *
1702 * @hide
1703 */
1704 public class PacketKeepalive {
1705
1706 private static final String TAG = "PacketKeepalive";
1707
1708 /** @hide */
1709 public static final int SUCCESS = 0;
1710
1711 /** @hide */
1712 public static final int NO_KEEPALIVE = -1;
1713
1714 /** @hide */
1715 public static final int BINDER_DIED = -10;
1716
1717 /** The specified {@code Network} is not connected. */
1718 public static final int ERROR_INVALID_NETWORK = -20;
1719 /** The specified IP addresses are invalid. For example, the specified source IP address is
1720 * not configured on the specified {@code Network}. */
1721 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1722 /** The requested port is invalid. */
1723 public static final int ERROR_INVALID_PORT = -22;
1724 /** The packet length is invalid (e.g., too long). */
1725 public static final int ERROR_INVALID_LENGTH = -23;
1726 /** The packet transmission interval is invalid (e.g., too short). */
1727 public static final int ERROR_INVALID_INTERVAL = -24;
1728
1729 /** The hardware does not support this request. */
1730 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001731 /** The hardware returned an error. */
1732 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001733
Nathan Harold63dd8132018-02-14 13:09:45 -08001734 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001735 public static final int NATT_PORT = 4500;
1736
Nathan Harold63dd8132018-02-14 13:09:45 -08001737 /** The minimum interval in seconds between keepalive packet transmissions */
1738 public static final int MIN_INTERVAL = 10;
1739
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001740 private final Network mNetwork;
1741 private final PacketKeepaliveCallback mCallback;
1742 private final Looper mLooper;
1743 private final Messenger mMessenger;
1744
1745 private volatile Integer mSlot;
1746
1747 void stopLooper() {
1748 mLooper.quit();
1749 }
1750
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001751 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001752 public void stop() {
1753 try {
1754 mService.stopKeepalive(mNetwork, mSlot);
1755 } catch (RemoteException e) {
1756 Log.e(TAG, "Error stopping packet keepalive: ", e);
1757 stopLooper();
1758 }
1759 }
1760
1761 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001762 Preconditions.checkNotNull(network, "network cannot be null");
1763 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001764 mNetwork = network;
1765 mCallback = callback;
1766 HandlerThread thread = new HandlerThread(TAG);
1767 thread.start();
1768 mLooper = thread.getLooper();
1769 mMessenger = new Messenger(new Handler(mLooper) {
1770 @Override
1771 public void handleMessage(Message message) {
1772 switch (message.what) {
1773 case NetworkAgent.EVENT_PACKET_KEEPALIVE:
1774 int error = message.arg2;
1775 try {
1776 if (error == SUCCESS) {
1777 if (mSlot == null) {
1778 mSlot = message.arg1;
1779 mCallback.onStarted();
1780 } else {
1781 mSlot = null;
1782 stopLooper();
1783 mCallback.onStopped();
1784 }
1785 } else {
1786 stopLooper();
1787 mCallback.onError(error);
1788 }
1789 } catch (Exception e) {
1790 Log.e(TAG, "Exception in keepalive callback(" + error + ")", e);
1791 }
1792 break;
1793 default:
1794 Log.e(TAG, "Unhandled message " + Integer.toHexString(message.what));
1795 break;
1796 }
1797 }
1798 });
1799 }
1800 }
1801
1802 /**
1803 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1804 *
1805 * @hide
1806 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001807 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001808 public PacketKeepalive startNattKeepalive(
1809 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1810 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1811 final PacketKeepalive k = new PacketKeepalive(network, callback);
1812 try {
1813 mService.startNattKeepalive(network, intervalSeconds, k.mMessenger, new Binder(),
1814 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1815 } catch (RemoteException e) {
1816 Log.e(TAG, "Error starting packet keepalive: ", e);
1817 k.stopLooper();
1818 return null;
1819 }
1820 return k;
1821 }
1822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 /**
1824 * Ensure that a network route exists to deliver traffic to the specified
1825 * host via the specified network interface. An attempt to add a route that
1826 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001827 *
1828 * <p>This method requires the caller to hold either the
1829 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1830 * or the ability to modify system settings as determined by
1831 * {@link android.provider.Settings.System#canWrite}.</p>
1832 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 * @param networkType the type of the network over which traffic to the specified
1834 * host is to be routed
1835 * @param hostAddress the IP address of the host to which the route is desired
1836 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001837 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001838 * @deprecated Deprecated in favor of the
1839 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
1840 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001841 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001842 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001843 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001845 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001847 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001848 }
1849
1850 /**
1851 * Ensure that a network route exists to deliver traffic to the specified
1852 * host via the specified network interface. An attempt to add a route that
1853 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001854 *
1855 * <p>This method requires the caller to hold either the
1856 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1857 * or the ability to modify system settings as determined by
1858 * {@link android.provider.Settings.System#canWrite}.</p>
1859 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001860 * @param networkType the type of the network over which traffic to the specified
1861 * host is to be routed
1862 * @param hostAddress the IP address of the host to which the route is desired
1863 * @return {@code true} on success, {@code false} on failure
1864 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001865 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001866 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001867 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001868 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001869 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001870 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001871 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001873 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001875 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 }
1877 }
1878
1879 /**
1880 * Returns the value of the setting for background data usage. If false,
1881 * applications should not use the network if the application is not in the
1882 * foreground. Developers should respect this setting, and check the value
1883 * of this before performing any background data operations.
1884 * <p>
1885 * All applications that have background services that use the network
1886 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001887 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07001888 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001889 * background data depends on several combined factors, and this method will
1890 * always return {@code true}. Instead, when background data is unavailable,
1891 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07001892 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 * @return Whether background data usage is allowed.
1894 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001895 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001897 // assume that background data is allowed; final authority is
1898 // NetworkInfo which may be blocked.
1899 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
1901
1902 /**
1903 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001904 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 * @param allowBackgroundData Whether an application should use data while
1906 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001907 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
1909 * @see #getBackgroundDataSetting()
1910 * @hide
1911 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001912 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001913 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001915 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001917
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001918 /** {@hide} */
1919 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001920 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001921 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1922 try {
1923 return mService.getActiveNetworkQuotaInfo();
1924 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001925 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001926 }
1927 }
1928
1929 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001930 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001931 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001932 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001933 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001934 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001935 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001936 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
1937 if (b != null) {
1938 try {
1939 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08001940 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08001941 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
Malcolm Chenb455e722017-11-28 15:57:14 -08001942 boolean retVal = it.isUserDataEnabled(subId);
Wink Saville36ffb042014-12-05 11:10:30 -08001943 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
1944 + " retVal=" + retVal);
1945 return retVal;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001946 } catch (RemoteException e) {
1947 throw e.rethrowFromSystemServer();
1948 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001949 }
Wink Saville36ffb042014-12-05 11:10:30 -08001950 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001951 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001952 }
1953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07001955 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07001956 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001957 */
1958 public interface OnNetworkActiveListener {
1959 /**
1960 * Called on the main thread of the process to report that the current data network
1961 * has become active, and it is now a good time to perform any pending network
1962 * operations. Note that this listener only tells you when the network becomes
1963 * active; if at any other time you want to know whether it is active (and thus okay
1964 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07001965 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001966 */
Chalard Jean4d660112018-06-04 16:52:49 +09001967 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001968 }
1969
1970 private INetworkManagementService getNetworkManagementService() {
1971 synchronized (this) {
1972 if (mNMService != null) {
1973 return mNMService;
1974 }
1975 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1976 mNMService = INetworkManagementService.Stub.asInterface(b);
1977 return mNMService;
1978 }
1979 }
1980
1981 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09001982 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001983
1984 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07001985 * Start listening to reports when the system's default data network is active, meaning it is
1986 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
1987 * to determine the current state of the system's default network after registering the
1988 * listener.
1989 * <p>
1990 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04001991 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07001992 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001993 *
1994 * @param l The listener to be told when the network is active.
1995 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07001996 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001997 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
1998 @Override
1999 public void onNetworkActive() throws RemoteException {
2000 l.onNetworkActive();
2001 }
2002 };
2003
2004 try {
2005 getNetworkManagementService().registerNetworkActivityListener(rl);
2006 mNetworkActivityListeners.put(l, rl);
2007 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002008 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002009 }
2010 }
2011
2012 /**
2013 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002014 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002015 *
2016 * @param l Previously registered listener.
2017 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002018 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002019 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002020 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002021 try {
2022 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2023 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002024 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002025 }
2026 }
2027
2028 /**
2029 * Return whether the data network is currently active. An active network means that
2030 * it is currently in a high power state for performing data transmission. On some
2031 * types of networks, it may be expensive to move and stay in such a state, so it is
2032 * more power efficient to batch network traffic together when the radio is already in
2033 * this state. This method tells you whether right now is currently a good time to
2034 * initiate network traffic, as the network is already active.
2035 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002036 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002037 try {
2038 return getNetworkManagementService().isNetworkActive();
2039 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002040 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002041 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002042 }
2043
2044 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 * {@hide}
2046 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002047 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002048 mContext = Preconditions.checkNotNull(context, "missing context");
2049 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05002050 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002052
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002053 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002054 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002055 public static ConnectivityManager from(Context context) {
2056 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2057 }
2058
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002059 /** @hide */
2060 public NetworkRequest getDefaultRequest() {
2061 try {
2062 // This is not racy as the default request is final in ConnectivityService.
2063 return mService.getDefaultRequest();
2064 } catch (RemoteException e) {
2065 throw e.rethrowFromSystemServer();
2066 }
2067 }
2068
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002069 /* TODO: These permissions checks don't belong in client-side code. Move them to
2070 * services.jar, possibly in com.android.server.net. */
2071
2072 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002073 public static final void enforceChangePermission(Context context) {
2074 int uid = Binder.getCallingUid();
2075 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2076 .getPackageNameForUid(context, uid), true /* throwException */);
2077 }
2078
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002079 /** {@hide} */
2080 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002081 Preconditions.checkNotNull(context, "Context cannot be null");
2082 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002083
Robert Greenwaltedb47662014-09-16 17:54:19 -07002084 if (context.getResources().getStringArray(
2085 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2086 // Have a provisioning app - must only let system apps (which check this app)
2087 // turn on tethering
2088 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002089 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002090 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002091 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002092 // If callingPkg's uid is not same as Binder.getCallingUid(),
2093 // AppOpsService throws SecurityException.
2094 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2095 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002096 }
2097 }
2098
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002099 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002100 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2101 * situations where a Context pointer is unavailable.
2102 * @hide
2103 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002104 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002105 static ConnectivityManager getInstanceOrNull() {
2106 return sInstance;
2107 }
2108
2109 /**
2110 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2111 * situations where a Context pointer is unavailable.
2112 * @hide
2113 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002114 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002115 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002116 private static ConnectivityManager getInstance() {
2117 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002118 throw new IllegalStateException("No ConnectivityManager yet constructed");
2119 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002120 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002121 }
2122
2123 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002124 * Get the set of tetherable, available interfaces. This list is limited by
2125 * device configuration and current interface existence.
2126 *
2127 * @return an array of 0 or more Strings of tetherable interface names.
2128 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002129 * {@hide}
2130 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002131 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002132 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002133 public String[] getTetherableIfaces() {
2134 try {
2135 return mService.getTetherableIfaces();
2136 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002137 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002138 }
2139 }
2140
2141 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002142 * Get the set of tethered interfaces.
2143 *
2144 * @return an array of 0 or more String of currently tethered interface names.
2145 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002146 * {@hide}
2147 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002148 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002149 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002150 public String[] getTetheredIfaces() {
2151 try {
2152 return mService.getTetheredIfaces();
2153 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002154 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002155 }
2156 }
2157
2158 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002159 * Get the set of interface names which attempted to tether but
2160 * failed. Re-attempting to tether may cause them to reset to the Tethered
2161 * state. Alternatively, causing the interface to be destroyed and recreated
2162 * may cause them to reset to the available state.
2163 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2164 * information on the cause of the errors.
2165 *
2166 * @return an array of 0 or more String indicating the interface names
2167 * which failed to tether.
2168 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002169 * {@hide}
2170 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002171 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002172 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002173 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002174 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08002175 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002176 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002177 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002178 }
2179 }
2180
2181 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002182 * Get the set of tethered dhcp ranges.
2183 *
2184 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
2185 * {@hide}
2186 */
2187 public String[] getTetheredDhcpRanges() {
2188 try {
2189 return mService.getTetheredDhcpRanges();
2190 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002191 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002192 }
2193 }
2194
2195 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002196 * Attempt to tether the named interface. This will setup a dhcp server
2197 * on the interface, forward and NAT IP packets and forward DNS requests
2198 * to the best active upstream network interface. Note that if no upstream
2199 * IP network interface is available, dhcp will still run and traffic will be
2200 * allowed between the tethered devices and this device, though upstream net
2201 * access will of course fail until an upstream network interface becomes
2202 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002203 *
2204 * <p>This method requires the caller to hold either the
2205 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2206 * or the ability to modify system settings as determined by
2207 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002208 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002209 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2210 * and WifiStateMachine which need direct access. All other clients should use
2211 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2212 * logic.</p>
2213 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002214 * @param iface the interface name to tether.
2215 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2216 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002217 * {@hide}
2218 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002219 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002220 public int tether(String iface) {
2221 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002222 String pkgName = mContext.getOpPackageName();
2223 Log.i(TAG, "tether caller:" + pkgName);
2224 return mService.tether(iface, pkgName);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002225 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002226 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002227 }
2228 }
2229
2230 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002231 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002232 *
2233 * <p>This method requires the caller to hold either the
2234 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2235 * or the ability to modify system settings as determined by
2236 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002237 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002238 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2239 * and WifiStateMachine which need direct access. All other clients should use
2240 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2241 * logic.</p>
2242 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002243 * @param iface the interface name to untether.
2244 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2245 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002246 * {@hide}
2247 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002248 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002249 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002250 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002251 String pkgName = mContext.getOpPackageName();
2252 Log.i(TAG, "untether caller:" + pkgName);
2253 return mService.untether(iface, pkgName);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002254 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002255 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002256 }
2257 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002258
2259 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002260 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002261 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002262 * due to device configuration.
2263 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002264 * <p>If this app does not have permission to use this API, it will always
2265 * return false rather than throw an exception.</p>
2266 *
2267 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2268 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2269 *
2270 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2271 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2272 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002273 * @return a boolean - {@code true} indicating Tethering is supported.
2274 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002275 * {@hide}
2276 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002277 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002278 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2279 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002280 public boolean isTetheringSupported() {
Chalard Jean8f76fc32017-09-26 15:45:18 +09002281 String pkgName = mContext.getOpPackageName();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002282 try {
Udam Saini0e94c362017-06-07 12:06:28 -07002283 return mService.isTetheringSupported(pkgName);
Chalard Jean8f76fc32017-09-26 15:45:18 +09002284 } catch (SecurityException e) {
2285 // This API is not available to this caller, but for backward-compatibility
2286 // this will just return false instead of throwing.
2287 return false;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002288 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002289 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002290 }
2291 }
2292
2293 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002294 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2295 * @hide
2296 */
2297 @SystemApi
2298 public static abstract class OnStartTetheringCallback {
2299 /**
2300 * Called when tethering has been successfully started.
2301 */
Chalard Jean4d660112018-06-04 16:52:49 +09002302 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002303
2304 /**
2305 * Called when starting tethering failed.
2306 */
Chalard Jean4d660112018-06-04 16:52:49 +09002307 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002308 }
2309
2310 /**
2311 * Convenient overload for
2312 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2313 * handler to run on the current thread's {@link Looper}.
2314 * @hide
2315 */
2316 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07002317 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002318 public void startTethering(int type, boolean showProvisioningUi,
2319 final OnStartTetheringCallback callback) {
2320 startTethering(type, showProvisioningUi, callback, null);
2321 }
2322
2323 /**
2324 * Runs tether provisioning for the given type if needed and then starts tethering if
2325 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2326 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2327 * schedules tether provisioning re-checks if appropriate.
2328 *
2329 * @param type The type of tethering to start. Must be one of
2330 * {@link ConnectivityManager.TETHERING_WIFI},
2331 * {@link ConnectivityManager.TETHERING_USB}, or
2332 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2333 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2334 * is one. This should be true the first time this function is called and also any time
2335 * the user can see this UI. It gives users information from their carrier about the
2336 * check failing and how they can sign up for tethering if possible.
2337 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2338 * of the result of trying to tether.
2339 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2340 * @hide
2341 */
2342 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002343 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002344 public void startTethering(int type, boolean showProvisioningUi,
2345 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002346 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002347
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002348 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2349 @Override
2350 protected void onReceiveResult(int resultCode, Bundle resultData) {
2351 if (resultCode == TETHER_ERROR_NO_ERROR) {
2352 callback.onTetheringStarted();
2353 } else {
2354 callback.onTetheringFailed();
2355 }
2356 }
2357 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002358
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002359 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002360 String pkgName = mContext.getOpPackageName();
2361 Log.i(TAG, "startTethering caller:" + pkgName);
2362 mService.startTethering(type, wrappedCallback, showProvisioningUi, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002363 } catch (RemoteException e) {
2364 Log.e(TAG, "Exception trying to start tethering.", e);
2365 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2366 }
2367 }
2368
2369 /**
2370 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2371 * applicable.
2372 *
2373 * @param type The type of tethering to stop. Must be one of
2374 * {@link ConnectivityManager.TETHERING_WIFI},
2375 * {@link ConnectivityManager.TETHERING_USB}, or
2376 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2377 * @hide
2378 */
2379 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002380 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002381 public void stopTethering(int type) {
2382 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002383 String pkgName = mContext.getOpPackageName();
2384 Log.i(TAG, "stopTethering caller:" + pkgName);
2385 mService.stopTethering(type, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002386 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002387 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002388 }
2389 }
2390
2391 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002392 * Get the list of regular expressions that define any tetherable
2393 * USB network interfaces. If USB tethering is not supported by the
2394 * device, this list should be empty.
2395 *
2396 * @return an array of 0 or more regular expression Strings defining
2397 * what interfaces are considered tetherable usb interfaces.
2398 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002399 * {@hide}
2400 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002401 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002402 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002403 public String[] getTetherableUsbRegexs() {
2404 try {
2405 return mService.getTetherableUsbRegexs();
2406 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002407 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002408 }
2409 }
2410
2411 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002412 * Get the list of regular expressions that define any tetherable
2413 * Wifi network interfaces. If Wifi tethering is not supported by the
2414 * device, this list should be empty.
2415 *
2416 * @return an array of 0 or more regular expression Strings defining
2417 * what interfaces are considered tetherable wifi interfaces.
2418 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002419 * {@hide}
2420 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002421 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002422 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002423 public String[] getTetherableWifiRegexs() {
2424 try {
2425 return mService.getTetherableWifiRegexs();
2426 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002427 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002428 }
2429 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002430
Danica Chang6fdd0c62010-08-11 14:54:43 -07002431 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002432 * Get the list of regular expressions that define any tetherable
2433 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2434 * device, this list should be empty.
2435 *
2436 * @return an array of 0 or more regular expression Strings defining
2437 * what interfaces are considered tetherable bluetooth interfaces.
2438 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002439 * {@hide}
2440 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002441 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002442 @UnsupportedAppUsage
Danica Chang6fdd0c62010-08-11 14:54:43 -07002443 public String[] getTetherableBluetoothRegexs() {
2444 try {
2445 return mService.getTetherableBluetoothRegexs();
2446 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002447 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002448 }
2449 }
2450
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002451 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002452 * Attempt to both alter the mode of USB and Tethering of USB. A
2453 * utility method to deal with some of the complexity of USB - will
2454 * attempt to switch to Rndis and subsequently tether the resulting
2455 * interface on {@code true} or turn off tethering and switch off
2456 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002457 *
2458 * <p>This method requires the caller to hold either the
2459 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2460 * or the ability to modify system settings as determined by
2461 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002462 *
2463 * @param enable a boolean - {@code true} to enable tethering
2464 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2465 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002466 * {@hide}
2467 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002468 @UnsupportedAppUsage
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002469 public int setUsbTethering(boolean enable) {
2470 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002471 String pkgName = mContext.getOpPackageName();
2472 Log.i(TAG, "setUsbTethering caller:" + pkgName);
2473 return mService.setUsbTethering(enable, pkgName);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002474 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002475 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002476 }
2477 }
2478
Robert Greenwalt5a735062010-03-02 17:25:02 -08002479 /** {@hide} */
2480 public static final int TETHER_ERROR_NO_ERROR = 0;
2481 /** {@hide} */
2482 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2483 /** {@hide} */
2484 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2485 /** {@hide} */
2486 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2487 /** {@hide} */
2488 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2489 /** {@hide} */
2490 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2491 /** {@hide} */
2492 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2493 /** {@hide} */
2494 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2495 /** {@hide} */
2496 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2497 /** {@hide} */
2498 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2499 /** {@hide} */
2500 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002501 /** {@hide} */
2502 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +09002503 /** {@hide} */
2504 public static final int TETHER_ERROR_DHCPSERVER_ERROR = 12;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002505
2506 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002507 * Get a more detailed error code after a Tethering or Untethering
2508 * request asynchronously failed.
2509 *
2510 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002511 * @return error The error code of the last error tethering or untethering the named
2512 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002513 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002514 * {@hide}
2515 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002516 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002517 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002518 public int getLastTetherError(String iface) {
2519 try {
2520 return mService.getLastTetherError(iface);
2521 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002522 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002523 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002524 }
2525
2526 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002527 * Report network connectivity status. This is currently used only
2528 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002529 * <p>This method requires the caller to hold the permission
2530 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002531 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002532 * @param networkType The type of network you want to report on
2533 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002534 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002535 * {@hide}
2536 */
2537 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002538 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002539 try {
2540 mService.reportInetCondition(networkType, percentage);
2541 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002542 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002543 }
2544 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002545
2546 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002547 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002548 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002549 * the framework to re-evaluate network connectivity and/or switch to another
2550 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002551 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002552 * @param network The {@link Network} the application was attempting to use
2553 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002554 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2555 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002556 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002557 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002558 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002559 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002560 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002561 // One of these will be ignored because it matches system's current state.
2562 // The other will trigger the necessary reevaluation.
2563 mService.reportNetworkConnectivity(network, true);
2564 mService.reportNetworkConnectivity(network, false);
2565 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002566 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002567 }
2568 }
2569
2570 /**
2571 * Report to the framework whether a network has working connectivity.
2572 * This provides a hint to the system that a particular network is providing
2573 * working connectivity or not. In response the framework may re-evaluate
2574 * the network's connectivity and might take further action thereafter.
2575 *
2576 * @param network The {@link Network} the application was attempting to use
2577 * or {@code null} to indicate the current default network.
2578 * @param hasConnectivity {@code true} if the application was able to successfully access the
2579 * Internet using {@code network} or {@code false} if not.
2580 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002581 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002582 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002583 try {
2584 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002585 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002586 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002587 }
2588 }
2589
2590 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002591 * Set a network-independent global http proxy. This is not normally what you want
2592 * for typical HTTP proxies - they are general network dependent. However if you're
2593 * doing something unusual like general internal filtering this may be useful. On
2594 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002595 *
2596 * @param p A {@link ProxyInfo} object defining the new global
2597 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002598 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002599 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002600 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Jason Monk207900c2014-04-25 15:00:09 -04002601 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002602 try {
2603 mService.setGlobalProxy(p);
2604 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002605 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002606 }
2607 }
2608
2609 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002610 * Retrieve any network-independent global HTTP proxy.
2611 *
Jason Monk207900c2014-04-25 15:00:09 -04002612 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002613 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002614 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002615 */
Jason Monk207900c2014-04-25 15:00:09 -04002616 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002617 try {
2618 return mService.getGlobalProxy();
2619 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002620 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002621 }
2622 }
2623
2624 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002625 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2626 * network-specific HTTP proxy. If {@code network} is null, the
2627 * network-specific proxy returned is the proxy of the default active
2628 * network.
2629 *
2630 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2631 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2632 * or when {@code network} is {@code null},
2633 * the {@code ProxyInfo} for the default active network. Returns
2634 * {@code null} when no proxy applies or the caller doesn't have
2635 * permission to use {@code network}.
2636 * @hide
2637 */
2638 public ProxyInfo getProxyForNetwork(Network network) {
2639 try {
2640 return mService.getProxyForNetwork(network);
2641 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002642 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04002643 }
2644 }
2645
2646 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002647 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
2648 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04002649 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05002650 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002651 *
Jason Monk207900c2014-04-25 15:00:09 -04002652 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002653 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07002654 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002655 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05002656 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04002657 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07002658 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002659
2660 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002661 * Returns true if the hardware supports the given network type
2662 * else it returns false. This doesn't indicate we have coverage
2663 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002664 * hardware supports it. For example a GSM phone without a SIM
2665 * should still return {@code true} for mobile data, but a wifi only
2666 * tablet would return {@code false}.
2667 *
2668 * @param networkType The network type we'd like to check
2669 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002670 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002671 * @hide
2672 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002673 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002674 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002675 @UnsupportedAppUsage
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002676 public boolean isNetworkSupported(int networkType) {
2677 try {
2678 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002679 } catch (RemoteException e) {
2680 throw e.rethrowFromSystemServer();
2681 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002682 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002683
2684 /**
2685 * Returns if the currently active data network is metered. A network is
2686 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002687 * that connection due to monetary costs, data limitations or
2688 * battery/performance issues. You should check this before doing large
2689 * data transfers, and warn the user or delay the operation until another
2690 * network is available.
2691 *
2692 * @return {@code true} if large transfers should be avoided, otherwise
2693 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002694 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002695 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002696 public boolean isActiveNetworkMetered() {
2697 try {
2698 return mService.isActiveNetworkMetered();
2699 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002700 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002701 }
2702 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002703
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002704 /**
2705 * If the LockdownVpn mechanism is enabled, updates the vpn
2706 * with a reload of its profile.
2707 *
2708 * @return a boolean with {@code} indicating success
2709 *
2710 * <p>This method can only be called by the system UID
2711 * {@hide}
2712 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002713 public boolean updateLockdownVpn() {
2714 try {
2715 return mService.updateLockdownVpn();
2716 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002717 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002718 }
2719 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002720
2721 /**
Wink Saville948282b2013-08-29 08:55:16 -07002722 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07002723 *
Wink Savilleab9321d2013-06-29 21:10:57 -07002724 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07002725 *
2726 * @return time out that will be used, maybe less that suggestedTimeOutMs
2727 * -1 if an error.
2728 *
2729 * {@hide}
2730 */
Wink Saville948282b2013-08-29 08:55:16 -07002731 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07002732 int timeOutMs = -1;
2733 try {
Wink Saville948282b2013-08-29 08:55:16 -07002734 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07002735 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002736 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07002737 }
2738 return timeOutMs;
2739 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002740
2741 /**
Wink Saville42d4f082013-07-20 20:31:59 -07002742 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002743 * {@hide}
2744 */
2745 public String getMobileProvisioningUrl() {
2746 try {
2747 return mService.getMobileProvisioningUrl();
2748 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002749 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002750 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002751 }
Wink Saville42d4f082013-07-20 20:31:59 -07002752
2753 /**
Wink Saville948282b2013-08-29 08:55:16 -07002754 * Set sign in error notification to visible or in visible
2755 *
Wink Saville948282b2013-08-29 08:55:16 -07002756 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04002757 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07002758 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002759 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07002760 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04002761 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07002762 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04002763 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07002764 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002765 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07002766 }
2767 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002768
2769 /**
2770 * Set the value for enabling/disabling airplane mode
2771 *
2772 * @param enable whether to enable airplane mode or not
2773 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002774 * @hide
2775 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09002776 @RequiresPermission(anyOf = {
2777 android.Manifest.permission.NETWORK_SETTINGS,
2778 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2779 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09002780 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002781 public void setAirplaneMode(boolean enable) {
2782 try {
2783 mService.setAirplaneMode(enable);
2784 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002785 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002786 }
2787 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002788
2789 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002790 @UnsupportedAppUsage
Robert Greenwalta67be032014-05-16 15:49:14 -07002791 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07002792 try {
Robert Greenwalta67be032014-05-16 15:49:14 -07002793 mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002794 } catch (RemoteException e) {
2795 throw e.rethrowFromSystemServer();
2796 }
Robert Greenwalta67be032014-05-16 15:49:14 -07002797 }
2798
2799 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00002800 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Robert Greenwalta67be032014-05-16 15:49:14 -07002801 public void unregisterNetworkFactory(Messenger messenger) {
2802 try {
2803 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002804 } catch (RemoteException e) {
2805 throw e.rethrowFromSystemServer();
2806 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002807 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002808
Paul Jensen31a94f42015-02-13 14:18:39 -05002809 /**
2810 * @hide
2811 * Register a NetworkAgent with ConnectivityService.
2812 * @return NetID corresponding to NetworkAgent.
2813 */
2814 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002815 NetworkCapabilities nc, int score, NetworkMisc misc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002816 try {
Paul Jensen31a94f42015-02-13 14:18:39 -05002817 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc);
2818 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002819 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05002820 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002821 }
2822
Robert Greenwalt9258c642014-03-26 16:47:06 -07002823 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09002824 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
2825 * changes. Should be extended by applications wanting notifications.
2826 *
2827 * A {@code NetworkCallback} is registered by calling
2828 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2829 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09002830 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09002831 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
2832 * A {@code NetworkCallback} should be registered at most once at any time.
2833 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002834 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002835 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002836 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002837 * Called when the framework connects to a new network to evaluate whether it satisfies this
2838 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
2839 * callback. There is no guarantee that this new network will satisfy any requests, or that
2840 * the network will stay connected for longer than the time necessary to evaluate it.
2841 * <p>
2842 * Most applications <b>should not</b> act on this callback, and should instead use
2843 * {@link #onAvailable}. This callback is intended for use by applications that can assist
2844 * the framework in properly evaluating the network &mdash; for example, an application that
2845 * can automatically log in to a captive portal without user intervention.
2846 *
2847 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09002848 *
2849 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07002850 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002851 public void onPreCheck(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002852
2853 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002854 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07002855 * This callback may be called more than once if the {@link Network} that is
2856 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002857 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002858 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09002859 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
2860 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08002861 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09002862 * @hide
2863 */
2864 public void onAvailable(Network network, NetworkCapabilities networkCapabilities,
junyulai05986c62018-08-07 19:50:45 +08002865 LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09002866 // Internally only this method is called when a new network is available, and
2867 // it calls the callback in the same way and order that older versions used
2868 // to call so as not to change the behavior.
2869 onAvailable(network);
2870 if (!networkCapabilities.hasCapability(
2871 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
2872 onNetworkSuspended(network);
2873 }
2874 onCapabilitiesChanged(network, networkCapabilities);
2875 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08002876 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09002877 }
2878
2879 /**
2880 * Called when the framework connects and has declared a new network ready for use.
2881 * This callback may be called more than once if the {@link Network} that is
2882 * satisfying the request changes. This will always immediately be followed by a
2883 * call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} then by a
junyulai05986c62018-08-07 19:50:45 +08002884 * call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call to
2885 * {@link #onBlockedStatusChanged(Network, boolean)}.
Chalard Jean804b8fb2018-01-30 22:41:41 +09002886 *
2887 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002888 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002889 public void onAvailable(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002890
2891 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002892 * Called when the network is about to be disconnected. Often paired with an
Robert Greenwalt6078b502014-06-11 16:05:07 -07002893 * {@link NetworkCallback#onAvailable} call with the new replacement network
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002894 * for graceful handover. This may not be called if we have a hard loss
2895 * (loss without warning). This may be followed by either a
Robert Greenwalt6078b502014-06-11 16:05:07 -07002896 * {@link NetworkCallback#onLost} call or a
2897 * {@link NetworkCallback#onAvailable} call for this network depending
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002898 * on whether we lose or regain it.
2899 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002900 * @param network The {@link Network} that is about to be disconnected.
2901 * @param maxMsToLive The time in ms the framework will attempt to keep the
2902 * network connected. Note that the network may suffer a
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002903 * hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002904 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002905 public void onLosing(Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002906
2907 /**
2908 * Called when the framework has a hard loss of the network or when the
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002909 * graceful failure ends.
2910 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002911 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002912 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002913 public void onLost(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002914
2915 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08002916 * Called if no network is found in the timeout time specified in
Hugo Benichi0eec03f2017-05-15 15:15:33 +09002917 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call. This callback is not
Etan Cohenaebf17e2017-03-01 12:47:28 -08002918 * called for the version of {@link #requestNetwork(NetworkRequest, NetworkCallback)}
2919 * without timeout. When this callback is invoked the associated
2920 * {@link NetworkRequest} will have already been removed and released, as if
2921 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002922 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002923 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002924
2925 /**
2926 * Called when the network the framework connected to for this request
2927 * changes capabilities but still satisfies the stated need.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002928 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002929 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09002930 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
2931 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002932 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002933 public void onCapabilitiesChanged(Network network,
Robert Greenwalt7b816022014-04-18 15:25:25 -07002934 NetworkCapabilities networkCapabilities) {}
2935
2936 /**
2937 * Called when the network the framework connected to for this request
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002938 * changes {@link LinkProperties}.
2939 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002940 * @param network The {@link Network} whose link properties have changed.
2941 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002942 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002943 public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002944
Robert Greenwalt8d482522015-06-24 13:23:42 -07002945 /**
2946 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09002947 * goes into {@link NetworkInfo.State#SUSPENDED}.
Robert Greenwalt8d482522015-06-24 13:23:42 -07002948 * This generally means that while the TCP connections are still live,
2949 * temporarily network data fails to transfer. Specifically this is used
2950 * on cellular networks to mask temporary outages when driving through
2951 * a tunnel, etc.
2952 * @hide
2953 */
2954 public void onNetworkSuspended(Network network) {}
2955
2956 /**
2957 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09002958 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
2959 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Robert Greenwalt8d482522015-06-24 13:23:42 -07002960 * @hide
2961 */
2962 public void onNetworkResumed(Network network) {}
2963
junyulai05986c62018-08-07 19:50:45 +08002964 /**
2965 * Called when access to the specified network is blocked or unblocked.
2966 *
2967 * @param network The {@link Network} whose blocked status has changed.
2968 * @param blocked The blocked status of this {@link Network}.
2969 */
2970 public void onBlockedStatusChanged(Network network, boolean blocked) {}
2971
Robert Greenwalt6078b502014-06-11 16:05:07 -07002972 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002973 }
2974
Hugo Benichicb883232017-05-11 13:16:17 +09002975 /**
2976 * Constant error codes used by ConnectivityService to communicate about failures and errors
2977 * across a Binder boundary.
2978 * @hide
2979 */
2980 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09002981 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09002982 }
2983
2984 /** @hide */
2985 public static class TooManyRequestsException extends RuntimeException {}
2986
2987 private static RuntimeException convertServiceException(ServiceSpecificException e) {
2988 switch (e.errorCode) {
2989 case Errors.TOO_MANY_REQUESTS:
2990 return new TooManyRequestsException();
2991 default:
2992 Log.w(TAG, "Unknown service error code " + e.errorCode);
2993 return new RuntimeException(e);
2994 }
2995 }
2996
Robert Greenwalt9258c642014-03-26 16:47:06 -07002997 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002998 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07002999 public static final int CALLBACK_PRECHECK = BASE + 1;
3000 /** @hide */
3001 public static final int CALLBACK_AVAILABLE = BASE + 2;
3002 /** @hide arg1 = TTL */
3003 public static final int CALLBACK_LOSING = BASE + 3;
3004 /** @hide */
3005 public static final int CALLBACK_LOST = BASE + 4;
3006 /** @hide */
3007 public static final int CALLBACK_UNAVAIL = BASE + 5;
3008 /** @hide */
3009 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3010 /** @hide */
3011 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003012 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003013 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003014 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003015 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003016 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003017 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003018 /** @hide */
3019 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003020
Erik Kline57faba92015-11-25 12:49:38 +09003021 /** @hide */
3022 public static String getCallbackName(int whichCallback) {
3023 switch (whichCallback) {
3024 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3025 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3026 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3027 case CALLBACK_LOST: return "CALLBACK_LOST";
3028 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3029 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3030 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003031 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3032 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3033 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003034 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003035 default:
3036 return Integer.toString(whichCallback);
3037 }
3038 }
3039
Robert Greenwalt562cc542014-05-15 18:07:26 -07003040 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003041 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003042 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003043
Hugo Benichid42650f2016-07-06 22:53:17 +09003044 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003045 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003046 }
3047
Hugo Benichi2583ef02017-02-02 17:02:36 +09003048 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003049 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003050 }
3051
Robert Greenwalt9258c642014-03-26 16:47:06 -07003052 @Override
3053 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003054 if (message.what == EXPIRE_LEGACY_REQUEST) {
3055 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3056 return;
3057 }
3058
3059 final NetworkRequest request = getObject(message, NetworkRequest.class);
3060 final Network network = getObject(message, Network.class);
3061 final NetworkCallback callback;
3062 synchronized (sCallbacks) {
3063 callback = sCallbacks.get(request);
3064 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003065 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003066 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003067 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003068 if (callback == null) {
3069 Log.w(TAG, "callback not found for " + getCallbackName(message.what) + " message");
3070 return;
3071 }
3072
Robert Greenwalt9258c642014-03-26 16:47:06 -07003073 switch (message.what) {
3074 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003075 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003076 break;
3077 }
3078 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003079 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3080 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003081 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003082 break;
3083 }
3084 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003085 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003086 break;
3087 }
3088 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003089 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003090 break;
3091 }
3092 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003093 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003094 break;
3095 }
3096 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003097 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3098 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003099 break;
3100 }
3101 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003102 LinkProperties lp = getObject(message, LinkProperties.class);
3103 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003104 break;
3105 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003106 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003107 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003108 break;
3109 }
3110 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003111 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003112 break;
3113 }
junyulai05986c62018-08-07 19:50:45 +08003114 case CALLBACK_BLK_CHANGED: {
3115 boolean blocked = message.arg1 != 0;
3116 callback.onBlockedStatusChanged(network, blocked);
3117 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003118 }
3119 }
3120
Hugo Benichid42650f2016-07-06 22:53:17 +09003121 private <T> T getObject(Message msg, Class<T> c) {
3122 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003123 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003124 }
3125
Hugo Benichi2583ef02017-02-02 17:02:36 +09003126 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003127 synchronized (sCallbacks) {
3128 if (sCallbackHandler == null) {
3129 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003130 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003131 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003132 }
3133 }
3134
Hugo Benichi6f260f32017-02-03 14:18:44 +09003135 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3136 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003137
Hugo Benichi6f260f32017-02-03 14:18:44 +09003138 private static final int LISTEN = 1;
3139 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003140
Hugo Benichi6f260f32017-02-03 14:18:44 +09003141 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3142 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003143 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003144 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003145 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003146 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003147 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003148 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003149 if (callback.networkRequest != null
3150 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003151 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3152 // and requests (http://b/20701525).
3153 Log.e(TAG, "NetworkCallback was already registered");
3154 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003155 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003156 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003157 if (action == LISTEN) {
Hugo Benichid42650f2016-07-06 22:53:17 +09003158 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04003159 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003160 request = mService.requestNetwork(
3161 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04003162 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003163 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003164 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003165 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003166 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003167 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003168 } catch (RemoteException e) {
3169 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003170 } catch (ServiceSpecificException e) {
3171 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003172 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003173 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003174 }
3175
3176 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003177 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003178 *
3179 * This is temporarily public @hide so it can be called by system code that uses the
3180 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
3181 * instead network notifications.
3182 *
3183 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
3184 *
3185 * @hide
3186 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003187 public void requestNetwork(@NonNull NetworkRequest request,
3188 @NonNull NetworkCallback networkCallback, int timeoutMs, int legacyType,
3189 @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003190 CallbackHandler cbHandler = new CallbackHandler(handler);
3191 NetworkCapabilities nc = request.networkCapabilities;
3192 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003193 }
3194
3195 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003196 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003197 *
3198 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003199 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3200 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003201 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003202 * Status of the request can be followed by listening to the various
Robert Greenwalt6078b502014-06-11 16:05:07 -07003203 * callbacks described in {@link NetworkCallback}. The {@link Network}
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003204 * can be used to direct traffic to the network.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003205 * <p>It is presently unsupported to request a network with mutable
3206 * {@link NetworkCapabilities} such as
3207 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3208 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3209 * as these {@code NetworkCapabilities} represent states that a particular
3210 * network may never attain, and whether a network will attain these states
3211 * is unknown prior to bringing up the network so the framework does not
3212 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003213 *
3214 * <p>This method requires the caller to hold either the
3215 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3216 * or the ability to modify system settings as determined by
3217 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003218 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003219 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003220 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3221 * the callback must not be shared - it uniquely specifies this request.
3222 * The callback is invoked on the default internal Handler.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003223 * @throws IllegalArgumentException if {@code request} specifies any mutable
3224 * {@code NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003225 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003226 public void requestNetwork(@NonNull NetworkRequest request,
3227 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003228 requestNetwork(request, networkCallback, getDefaultHandler());
3229 }
3230
3231 /**
3232 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3233 *
3234 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003235 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3236 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003237 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003238 * Status of the request can be followed by listening to the various
3239 * callbacks described in {@link NetworkCallback}. The {@link Network}
3240 * can be used to direct traffic to the network.
3241 * <p>It is presently unsupported to request a network with mutable
3242 * {@link NetworkCapabilities} such as
3243 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3244 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3245 * as these {@code NetworkCapabilities} represent states that a particular
3246 * network may never attain, and whether a network will attain these states
3247 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003248 * know how to go about satisfying a request with these capabilities.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003249 *
3250 * <p>This method requires the caller to hold either the
3251 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3252 * or the ability to modify system settings as determined by
3253 * {@link android.provider.Settings.System#canWrite}.</p>
3254 *
3255 * @param request {@link NetworkRequest} describing this request.
3256 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3257 * the callback must not be shared - it uniquely specifies this request.
3258 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3259 * @throws IllegalArgumentException if {@code request} specifies any mutable
3260 * {@code NetworkCapabilities}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003261 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003262 public void requestNetwork(@NonNull NetworkRequest request,
3263 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003264 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3265 CallbackHandler cbHandler = new CallbackHandler(handler);
3266 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003267 }
3268
3269 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003270 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3271 * by a timeout.
3272 *
3273 * This function behaves identically to the non-timed-out version
3274 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3275 * is not found within the given time (in milliseconds) the
3276 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3277 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3278 * not have to be released if timed-out (it is automatically released). Unregistering a
3279 * request that timed out is not an error.
3280 *
3281 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3282 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3283 * for that purpose. Calling this method will attempt to bring up the requested network.
3284 *
3285 * <p>This method requires the caller to hold either the
3286 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3287 * or the ability to modify system settings as determined by
3288 * {@link android.provider.Settings.System#canWrite}.</p>
3289 *
3290 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003291 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3292 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003293 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3294 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3295 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003296 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003297 public void requestNetwork(@NonNull NetworkRequest request,
3298 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003299 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003300 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003301 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003302 }
3303
Hugo Benichi2583ef02017-02-02 17:02:36 +09003304 /**
3305 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3306 * by a timeout.
3307 *
Chalard Jean4d660112018-06-04 16:52:49 +09003308 * This function behaves identically to the version without timeout, but if a suitable
Hugo Benichi2583ef02017-02-02 17:02:36 +09003309 * network is not found within the given time (in milliseconds) the
Etan Cohenaebf17e2017-03-01 12:47:28 -08003310 * {@link NetworkCallback#onUnavailable} callback is called. The request can still be
3311 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3312 * not have to be released if timed-out (it is automatically released). Unregistering a
3313 * request that timed out is not an error.
3314 *
3315 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3316 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3317 * for that purpose. Calling this method will attempt to bring up the requested network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003318 *
3319 * <p>This method requires the caller to hold either the
3320 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3321 * or the ability to modify system settings as determined by
3322 * {@link android.provider.Settings.System#canWrite}.</p>
3323 *
3324 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003325 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3326 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003327 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003328 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3329 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003330 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003331 public void requestNetwork(@NonNull NetworkRequest request,
3332 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003333 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003334 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3335 CallbackHandler cbHandler = new CallbackHandler(handler);
3336 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003337 }
3338
3339 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003340 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003341 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003342 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003343 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003344 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3345 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003346 */
Erik Kline90e93072014-11-19 12:12:24 +09003347 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003348
3349 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003350 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003351 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003352 * {@link android.content.Intent#getParcelableExtra(String)}.
3353 */
Erik Kline90e93072014-11-19 12:12:24 +09003354 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003355
3356
3357 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003358 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003359 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003360 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003361 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003362 * the request may outlive the calling application and get called back when a suitable
3363 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003364 * <p>
3365 * The operation is an Intent broadcast that goes to a broadcast receiver that
3366 * you registered with {@link Context#registerReceiver} or through the
3367 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3368 * <p>
3369 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003370 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3371 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003372 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003373 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003374 * Intent to reserve the network or it will be released shortly after the Intent
3375 * is processed.
3376 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003377 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003378 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003379 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003380 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003381 * The request may be released normally by calling
3382 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003383 * <p>It is presently unsupported to request a network with either
3384 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3385 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3386 * as these {@code NetworkCapabilities} represent states that a particular
3387 * network may never attain, and whether a network will attain these states
3388 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003389 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003390 *
3391 * <p>This method requires the caller to hold either the
3392 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3393 * or the ability to modify system settings as determined by
3394 * {@link android.provider.Settings.System#canWrite}.</p>
3395 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003396 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003397 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003398 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003399 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003400 * @throws IllegalArgumentException if {@code request} contains either
3401 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3402 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003403 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003404 public void requestNetwork(@NonNull NetworkRequest request,
3405 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003406 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003407 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003408 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003409 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003410 } catch (RemoteException e) {
3411 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003412 } catch (ServiceSpecificException e) {
3413 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003414 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003415 }
3416
3417 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003418 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3419 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003420 * This method has the same behavior as
3421 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003422 * releasing network resources and disconnecting.
3423 *
3424 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3425 * PendingIntent passed to
3426 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3427 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3428 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003429 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003430 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003431 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003432 try {
3433 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003434 } catch (RemoteException e) {
3435 throw e.rethrowFromSystemServer();
3436 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003437 }
3438
Hugo Benichie7678512017-05-09 15:19:01 +09003439 private static void checkPendingIntentNotNull(PendingIntent intent) {
3440 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3441 }
3442
3443 private static void checkCallbackNotNull(NetworkCallback callback) {
3444 Preconditions.checkNotNull(callback, "null NetworkCallback");
3445 }
3446
3447 private static void checkTimeout(int timeoutMs) {
3448 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003449 }
3450
3451 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003452 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003453 * {@link NetworkRequest}. The callbacks will continue to be called until
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003454 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003455 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003456 * @param request {@link NetworkRequest} describing this request.
3457 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3458 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003459 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003460 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003461 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003462 public void registerNetworkCallback(@NonNull NetworkRequest request,
3463 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003464 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3465 }
3466
3467 /**
3468 * Registers to receive notifications about all networks which satisfy the given
3469 * {@link NetworkRequest}. The callbacks will continue to be called until
3470 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003471 *
3472 * @param request {@link NetworkRequest} describing this request.
3473 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3474 * networks change state.
3475 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003476 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003477 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003478 public void registerNetworkCallback(@NonNull NetworkRequest request,
3479 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003480 CallbackHandler cbHandler = new CallbackHandler(handler);
3481 NetworkCapabilities nc = request.networkCapabilities;
3482 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003483 }
3484
3485 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003486 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3487 * {@link NetworkRequest}.
3488 *
3489 * This function behaves identically to the version that takes a NetworkCallback, but instead
3490 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3491 * the request may outlive the calling application and get called back when a suitable
3492 * network is found.
3493 * <p>
3494 * The operation is an Intent broadcast that goes to a broadcast receiver that
3495 * you registered with {@link Context#registerReceiver} or through the
3496 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3497 * <p>
3498 * The operation Intent is delivered with two extras, a {@link Network} typed
3499 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3500 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3501 * the original requests parameters.
3502 * <p>
3503 * If there is already a request for this Intent registered (with the equality of
3504 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3505 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3506 * <p>
3507 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003508 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003509 * @param request {@link NetworkRequest} describing this request.
3510 * @param operation Action to perform when the network is available (corresponds
3511 * to the {@link NetworkCallback#onAvailable} call. Typically
3512 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3513 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003514 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003515 public void registerNetworkCallback(@NonNull NetworkRequest request,
3516 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003517 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003518 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04003519 try {
3520 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003521 } catch (RemoteException e) {
3522 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003523 } catch (ServiceSpecificException e) {
3524 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003525 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003526 }
3527
3528 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003529 * Registers to receive notifications about changes in the system default network. The callbacks
3530 * will continue to be called until either the application exits or
3531 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09003532 *
3533 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3534 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003535 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09003536 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003537 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003538 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003539 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
3540 }
3541
3542 /**
3543 * Registers to receive notifications about changes in the system default network. The callbacks
3544 * will continue to be called until either the application exits or
3545 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003546 *
3547 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3548 * system default network changes.
3549 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003550 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003551 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003552 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
3553 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09003554 // This works because if the NetworkCapabilities are null,
3555 // ConnectivityService takes them from the default request.
3556 //
3557 // Since the capabilities are exactly the same as the default request's
3558 // capabilities, this request is guaranteed, at all times, to be
3559 // satisfied by the same network, if any, that satisfies the default
3560 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003561 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09003562 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
3563 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09003564 }
3565
3566 /**
fengludb571472015-04-21 17:12:05 -07003567 * Requests bandwidth update for a given {@link Network} and returns whether the update request
3568 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
3569 * network connection for updated bandwidth information. The caller will be notified via
3570 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003571 * method assumes that the caller has previously called
3572 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
3573 * changes.
fenglub15e72b2015-03-20 11:29:56 -07003574 *
fengluae519192015-04-27 14:28:04 -07003575 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07003576 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07003577 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003578 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003579 try {
fengludb571472015-04-21 17:12:05 -07003580 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07003581 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003582 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07003583 }
3584 }
3585
3586 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003587 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003588 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
3589 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
3590 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09003591 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
3592 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003593 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09003594 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
3595 * triggering it as soon as this call returns.
3596 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003597 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003598 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003599 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003600 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003601 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003602 final List<NetworkRequest> reqs = new ArrayList<>();
3603 // Find all requests associated to this callback and stop callback triggers immediately.
3604 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
3605 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003606 Preconditions.checkArgument(networkCallback.networkRequest != null,
3607 "NetworkCallback was not registered");
3608 Preconditions.checkArgument(networkCallback.networkRequest != ALREADY_UNREGISTERED,
3609 "NetworkCallback was already unregistered");
Hugo Benichidafed3d2017-03-06 09:17:06 +09003610 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
3611 if (e.getValue() == networkCallback) {
3612 reqs.add(e.getKey());
3613 }
3614 }
3615 // TODO: throw exception if callback was registered more than once (http://b/20701525).
3616 for (NetworkRequest r : reqs) {
3617 try {
3618 mService.releaseNetworkRequest(r);
3619 } catch (RemoteException e) {
3620 throw e.rethrowFromSystemServer();
3621 }
3622 // Only remove mapping if rpc was successful.
3623 sCallbacks.remove(r);
3624 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09003625 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003626 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003627 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003628
3629 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003630 * Unregisters a callback previously registered via
3631 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3632 *
3633 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3634 * PendingIntent passed to
3635 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3636 * Cannot be null.
3637 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003638 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003639 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003640 releaseNetworkRequest(operation);
3641 }
3642
3643 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003644 * Informs the system whether it should switch to {@code network} regardless of whether it is
3645 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
3646 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
3647 * the system default network regardless of any other network that's currently connected. If
3648 * {@code always} is true, then the choice is remembered, so that the next time the user
3649 * connects to this network, the system will switch to it.
3650 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003651 * @param network The network to accept.
3652 * @param accept Whether to accept the network even if unvalidated.
3653 * @param always Whether to remember this choice in the future.
3654 *
3655 * @hide
3656 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003657 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003658 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3659 try {
3660 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003661 } catch (RemoteException e) {
3662 throw e.rethrowFromSystemServer();
3663 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003664 }
3665
3666 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003667 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
3668 * only meaningful if the system is configured not to penalize such networks, e.g., if the
3669 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
3670 * NETWORK_AVOID_BAD_WIFI setting is unset}.
3671 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003672 * @param network The network to accept.
3673 *
3674 * @hide
3675 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003676 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003677 public void setAvoidUnvalidated(Network network) {
3678 try {
3679 mService.setAvoidUnvalidated(network);
3680 } catch (RemoteException e) {
3681 throw e.rethrowFromSystemServer();
3682 }
3683 }
3684
3685 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003686 * Requests that the system open the captive portal app on the specified network.
3687 *
3688 * @param network The network to log into.
3689 *
3690 * @hide
3691 */
3692 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
3693 public void startCaptivePortalApp(Network network) {
3694 try {
3695 mService.startCaptivePortalApp(network);
3696 } catch (RemoteException e) {
3697 throw e.rethrowFromSystemServer();
3698 }
3699 }
3700
3701 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003702 * Determine whether the device is configured to avoid bad wifi.
3703 * @hide
3704 */
3705 @SystemApi
3706 public boolean getAvoidBadWifi() {
3707 try {
3708 return mService.getAvoidBadWifi();
3709 } catch (RemoteException e) {
3710 throw e.rethrowFromSystemServer();
3711 }
3712 }
3713
3714 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003715 * It is acceptable to briefly use multipath data to provide seamless connectivity for
3716 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003717 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
3718 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003719 *
3720 * An example of such an operation might be a time-sensitive foreground activity, such as a
3721 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
3722 */
3723 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
3724
3725 /**
3726 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
3727 * a backup channel for traffic that is primarily going over another network.
3728 *
3729 * An example might be maintaining backup connections to peers or servers for the purpose of
3730 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
3731 * on backup paths should be negligible compared to the traffic on the main path.
3732 */
3733 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
3734
3735 /**
3736 * It is acceptable to use metered data to improve network latency and performance.
3737 */
3738 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
3739
3740 /**
3741 * Return value to use for unmetered networks. On such networks we currently set all the flags
3742 * to true.
3743 * @hide
3744 */
3745 public static final int MULTIPATH_PREFERENCE_UNMETERED =
3746 MULTIPATH_PREFERENCE_HANDOVER |
3747 MULTIPATH_PREFERENCE_RELIABILITY |
3748 MULTIPATH_PREFERENCE_PERFORMANCE;
3749
3750 /** @hide */
3751 @Retention(RetentionPolicy.SOURCE)
3752 @IntDef(flag = true, value = {
3753 MULTIPATH_PREFERENCE_HANDOVER,
3754 MULTIPATH_PREFERENCE_RELIABILITY,
3755 MULTIPATH_PREFERENCE_PERFORMANCE,
3756 })
3757 public @interface MultipathPreference {
3758 }
3759
3760 /**
3761 * Provides a hint to the calling application on whether it is desirable to use the
3762 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
3763 * for multipath data transfer on this network when it is not the system default network.
3764 * Applications desiring to use multipath network protocols should call this method before
3765 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003766 *
3767 * @param network The network on which the application desires to use multipath data.
3768 * If {@code null}, this method will return the a preference that will generally
3769 * apply to metered networks.
3770 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
3771 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003772 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003773 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003774 try {
3775 return mService.getMultipathPreference(network);
3776 } catch (RemoteException e) {
3777 throw e.rethrowFromSystemServer();
3778 }
3779 }
3780
3781 /**
Stuart Scott984dc852015-03-30 13:17:11 -07003782 * Resets all connectivity manager settings back to factory defaults.
3783 * @hide
3784 */
3785 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07003786 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07003787 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07003788 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003789 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07003790 }
3791 }
3792
3793 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003794 * Binds the current process to {@code network}. All Sockets created in the future
3795 * (and not explicitly bound via a bound SocketFactory from
3796 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3797 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3798 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3799 * work and all host name resolutions will fail. This is by design so an application doesn't
3800 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3801 * To clear binding pass {@code null} for {@code network}. Using individually bound
3802 * Sockets created by Network.getSocketFactory().createSocket() and
3803 * performing network-specific host name resolutions via
3804 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04003805 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003806 *
3807 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3808 * the current binding.
3809 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3810 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003811 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09003812 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04003813 // instantiated.
3814 return setProcessDefaultNetwork(network);
3815 }
3816
3817 /**
3818 * Binds the current process to {@code network}. All Sockets created in the future
3819 * (and not explicitly bound via a bound SocketFactory from
3820 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3821 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3822 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3823 * work and all host name resolutions will fail. This is by design so an application doesn't
3824 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3825 * To clear binding pass {@code null} for {@code network}. Using individually bound
3826 * Sockets created by Network.getSocketFactory().createSocket() and
3827 * performing network-specific host name resolutions via
3828 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
3829 * {@code setProcessDefaultNetwork}.
3830 *
3831 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3832 * the current binding.
3833 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3834 * @deprecated This function can throw {@link IllegalStateException}. Use
3835 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
3836 * is a direct replacement.
3837 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003838 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09003839 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003840 int netId = (network == null) ? NETID_UNSET : network.netId;
Paul Jensen72db88e2015-03-10 10:54:12 -04003841 if (netId == NetworkUtils.getBoundNetworkForProcess()) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003842 return true;
3843 }
3844 if (NetworkUtils.bindProcessToNetwork(netId)) {
Paul Jensene0bef712014-12-10 15:12:18 -05003845 // Set HTTP proxy system properties to match network.
3846 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09003847 try {
3848 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
3849 } catch (SecurityException e) {
3850 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
3851 Log.e(TAG, "Can't set proxy properties", e);
3852 }
Paul Jensenc91b5342014-08-27 12:38:45 -04003853 // Must flush DNS cache as new network may have different DNS resolutions.
3854 InetAddress.clearDnsCache();
3855 // Must flush socket pool as idle sockets will be bound to previous network and may
3856 // cause subsequent fetches to be performed on old network.
3857 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
3858 return true;
3859 } else {
3860 return false;
3861 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003862 }
3863
3864 /**
3865 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04003866 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003867 *
3868 * @return {@code Network} to which this process is bound, or {@code null}.
3869 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003870 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04003871 public Network getBoundNetworkForProcess() {
3872 // Forcing callers to call thru non-static function ensures ConnectivityManager
3873 // instantiated.
3874 return getProcessDefaultNetwork();
3875 }
3876
3877 /**
3878 * Returns the {@link Network} currently bound to this process via
3879 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
3880 *
3881 * @return {@code Network} to which this process is bound, or {@code null}.
3882 * @deprecated Using this function can lead to other functions throwing
3883 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
3884 * {@code getBoundNetworkForProcess} is a direct replacement.
3885 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003886 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09003887 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003888 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04003889 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04003890 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003891 return new Network(netId);
3892 }
3893
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003894 private void unsupportedStartingFrom(int version) {
3895 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09003896 // The getApplicationInfo() call we make below is not supported in system context. Let
3897 // the call through here, and rely on the fact that ConnectivityService will refuse to
3898 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003899 return;
3900 }
3901
3902 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
3903 throw new UnsupportedOperationException(
3904 "This method is not supported in target SDK version " + version + " and above");
3905 }
3906 }
3907
3908 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
3909 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08003910 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003911 // remove these exemptions. Note that this check is not secure, and apps can still access these
3912 // functions by accessing ConnectivityService directly. However, it should be clear that doing
3913 // so is unsupported and may break in the future. http://b/22728205
3914 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07003915 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003916 }
3917
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003918 /**
3919 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04003920 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003921 *
3922 * @param network The {@link Network} to bind host resolutions from the current process to, or
3923 * {@code null} to clear the current binding.
3924 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3925 * @hide
3926 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
3927 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003928 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003929 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003930 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04003931 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09003932 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003933 }
Felipe Leme1b103232016-01-22 09:44:57 -08003934
3935 /**
3936 * Device is not restricting metered network activity while application is running on
3937 * background.
3938 */
3939 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
3940
3941 /**
3942 * Device is restricting metered network activity while application is running on background,
3943 * but application is allowed to bypass it.
3944 * <p>
3945 * In this state, application should take action to mitigate metered network access.
3946 * For example, a music streaming application should switch to a low-bandwidth bitrate.
3947 */
3948 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
3949
3950 /**
3951 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08003952 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08003953 * In this state, application should not try to use the network while running on background,
3954 * because it would be denied.
3955 */
3956 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
3957
Felipe Leme9778f762016-01-27 14:46:39 -08003958 /**
3959 * A change in the background metered network activity restriction has occurred.
3960 * <p>
3961 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
3962 * applies to them.
3963 * <p>
3964 * This is only sent to registered receivers, not manifest receivers.
3965 */
3966 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3967 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
3968 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
3969
Felipe Lemeecfccea2016-01-25 11:48:04 -08003970 /** @hide */
3971 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08003972 @IntDef(flag = false, value = {
3973 RESTRICT_BACKGROUND_STATUS_DISABLED,
3974 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
3975 RESTRICT_BACKGROUND_STATUS_ENABLED,
3976 })
Felipe Leme1b103232016-01-22 09:44:57 -08003977 public @interface RestrictBackgroundStatus {
3978 }
3979
3980 private INetworkPolicyManager getNetworkPolicyManager() {
3981 synchronized (this) {
3982 if (mNPManager != null) {
3983 return mNPManager;
3984 }
3985 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
3986 .getService(Context.NETWORK_POLICY_SERVICE));
3987 return mNPManager;
3988 }
3989 }
3990
3991 /**
3992 * Determines if the calling application is subject to metered network restrictions while
3993 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07003994 *
3995 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
3996 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
3997 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08003998 */
3999 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4000 try {
4001 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4002 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004003 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004004 }
4005 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004006
4007 /**
4008 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004009 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4010 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004011 *
4012 * @return Hash of network watchlist config file. Null if config does not exist.
4013 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004014 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004015 public byte[] getNetworkWatchlistConfigHash() {
4016 try {
4017 return mService.getNetworkWatchlistConfigHash();
4018 } catch (RemoteException e) {
4019 Log.e(TAG, "Unable to get watchlist config hash");
4020 throw e.rethrowFromSystemServer();
4021 }
4022 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004023
4024 /**
4025 * Returns the {@code uid} of the owner of a network connection.
4026 *
4027 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and
4028 * {@code IPPROTO_UDP} currently supported.
4029 * @param local The local {@link InetSocketAddress} of a connection.
4030 * @param remote The remote {@link InetSocketAddress} of a connection.
4031 *
4032 * @return {@code uid} if the connection is found and the app has permission to observe it
4033 * (e.g., if it is associated with the calling VPN app's tunnel) or
4034 * {@link android.os.Process#INVALID_UID} if the connection is not found.
4035 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004036 public int getConnectionOwnerUid(int protocol, @NonNull InetSocketAddress local,
4037 @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004038 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4039 try {
4040 return mService.getConnectionOwnerUid(connectionInfo);
4041 } catch (RemoteException e) {
4042 throw e.rethrowFromSystemServer();
4043 }
4044 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004045
4046 private void printStackTrace() {
4047 if (DEBUG) {
4048 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4049 final StringBuffer sb = new StringBuffer();
4050 for (int i = 3; i < callStack.length; i++) {
4051 final String stackTrace = callStack[i].toString();
4052 if (stackTrace == null || stackTrace.contains("android.os")) {
4053 break;
4054 }
4055 sb.append(" [").append(stackTrace).append("]");
4056 }
4057 Log.d(TAG, "StackLog:" + sb.toString());
4058 }
4059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060}