blob: 160157771b181a4d4b8104c596cbe77d48810818 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080016package android.net;
17
junyulai215b8772019-01-15 11:32:44 +080018import static android.net.IpSecManager.INVALID_RESOURCE_ID;
19
junyulai48eac1d42018-12-27 17:25:29 +080020import android.annotation.CallbackExecutor;
Felipe Leme1b103232016-01-22 09:44:57 -080021import android.annotation.IntDef;
Chalard Jean50bea3d2019-01-07 19:26:34 +090022import android.annotation.NonNull;
Robin Lee244ce8e2016-01-05 18:03:46 +000023import android.annotation.Nullable;
Jeff Sharkey30e06bb2017-04-24 11:18:03 -060024import android.annotation.RequiresPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.annotation.SdkConstant;
26import android.annotation.SdkConstant.SdkConstantType;
Udam Sainib7c24872016-01-04 12:16:14 -080027import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060028import android.annotation.SystemService;
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +090029import android.annotation.TestApi;
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010030import android.annotation.UnsupportedAppUsage;
Robert Greenwalt9258c642014-03-26 16:47:06 -070031import android.app.PendingIntent;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070032import android.content.Context;
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070033import android.content.Intent;
junyulai48eac1d42018-12-27 17:25:29 +080034import android.net.IpSecManager.UdpEncapsulationSocket;
35import android.net.SocketKeepalive.Callback;
Robert Greenwalt42acef32009-08-12 16:08:25 -070036import android.os.Binder;
Mathew Inwood55418ea2018-12-20 15:30:45 +000037import android.os.Build;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070038import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080039import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070040import android.os.Handler;
41import android.os.HandlerThread;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080042import android.os.IBinder;
43import android.os.INetworkActivityListener;
44import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070045import android.os.Looper;
46import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070047import android.os.Messenger;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090048import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080050import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080051import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090052import android.os.ServiceSpecificException;
Jeff Sharkey961e3042011-08-29 16:02:57 -070053import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080054import android.telephony.SubscriptionManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080055import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070056import android.util.Log;
Erik Kline35bf06c2017-01-26 18:08:28 +090057import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058
Robert Greenwaltafa05c02014-05-21 20:04:36 -070059import com.android.internal.telephony.ITelephony;
Robert Greenwalt562cc542014-05-15 18:07:26 -070060import com.android.internal.telephony.PhoneConstants;
Hugo Benichidafed3d2017-03-06 09:17:06 +090061import com.android.internal.util.Preconditions;
62import com.android.internal.util.Protocol;
Robert Greenwaltafa05c02014-05-21 20:04:36 -070063
Paul Jensenc91b5342014-08-27 12:38:45 -040064import libcore.net.event.NetworkEventDispatcher;
65
junyulai215b8772019-01-15 11:32:44 +080066import java.io.FileDescriptor;
Felipe Leme1b103232016-01-22 09:44:57 -080067import java.lang.annotation.Retention;
68import java.lang.annotation.RetentionPolicy;
Jeremy Kleind42209d2015-12-28 15:11:58 -080069import java.net.InetAddress;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070070import java.net.InetSocketAddress;
Hugo Benichidafed3d2017-03-06 09:17:06 +090071import java.util.ArrayList;
Jeremy Kleind42209d2015-12-28 15:11:58 -080072import java.util.HashMap;
Hugo Benichidafed3d2017-03-06 09:17:06 +090073import java.util.List;
74import java.util.Map;
junyulai48eac1d42018-12-27 17:25:29 +080075import java.util.concurrent.Executor;
Jeremy Kleind42209d2015-12-28 15:11:58 -080076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077/**
78 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060079 * notifies applications when network connectivity changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 * <p>
81 * The primary responsibilities of this class are to:
82 * <ol>
83 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
84 * <li>Send broadcast intents when network connectivity changes</li>
85 * <li>Attempt to "fail over" to another network when connectivity to a network
86 * is lost</li>
87 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
88 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070089 * <li>Provide an API that allows applications to request and select networks for their data
90 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 * </ol>
92 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060093@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070094public class ConnectivityManager {
95 private static final String TAG = "ConnectivityManager";
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +090096 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070099 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 * been established or lost. The NetworkInfo for the affected network is
101 * sent as an extra; it should be consulted to see what kind of
102 * connectivity event occurred.
103 * <p/>
Mark Lu33ec1062016-12-05 10:57:55 -0800104 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
105 * broadcast if they declare the broadcast receiver in their manifest. Apps
106 * will still receive broadcasts if they register their
107 * {@link android.content.BroadcastReceiver} with
108 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
109 * and that context is still valid.
110 * <p/>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 * If this is a connection that was the result of failing over from a
112 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
113 * set to true.
114 * <p/>
115 * For a loss of connectivity, if the connectivity manager is attempting
116 * to connect (or has already connected) to another network, the
117 * NetworkInfo for the new network is also passed as an extra. This lets
118 * any receivers of the broadcast know that they should not necessarily
119 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800120 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * the failover attempt succeeded (and so there is still overall data
122 * connectivity), or that the failover attempt failed, meaning that all
123 * connectivity has been lost.
124 * <p/>
125 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
126 * is set to {@code true} if there are no connected networks at all.
Chalard Jean054cd162018-02-10 05:33:50 +0900127 *
128 * @deprecated apps should use the more versatile {@link #requestNetwork},
129 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
130 * functions instead for faster and more detailed updates about the network
131 * changes they care about.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800133 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean054cd162018-02-10 05:33:50 +0900134 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 /**
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700138 * A temporary hack until SUPL system can get off the legacy APIS.
139 * They do too many network requests and the long list of apps listening
Chalard Jean4d660112018-06-04 16:52:49 +0900140 * and waking due to the CONNECTIVITY_ACTION broadcast makes it expensive.
141 * Use this broadcast intent instead for SUPL requests.
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700142 * @hide
143 */
144 public static final String CONNECTIVITY_ACTION_SUPL =
145 "android.net.conn.CONNECTIVITY_CHANGE_SUPL";
146
147 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500148 * The device has connected to a network that has presented a captive
149 * portal, which is blocking Internet connectivity. The user was presented
150 * with a notification that network sign in is required,
151 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400152 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500153 * facilitate signing in to the network. This action includes a
154 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
155 * the network presenting the captive portal; all communication with the
156 * captive portal must be done using this {@code Network} object.
157 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400158 * This activity includes a {@link CaptivePortal} extra named
159 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
160 * outcomes of the captive portal sign in to the system:
161 * <ul>
162 * <li> When the app handling this action believes the user has signed in to
163 * the network and the captive portal has been dismissed, the app should
164 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
165 * reevaluate the network. If reevaluation finds the network no longer
166 * subject to a captive portal, the network may become the default active
Chalard Jean4d660112018-06-04 16:52:49 +0900167 * data network.</li>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400168 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500169 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400170 * {@link CaptivePortal#ignoreNetwork}. </li>
171 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500172 */
173 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
174 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
175
176 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 * The lookup key for a {@link NetworkInfo} object. Retrieve with
178 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700179 *
180 * @deprecated Since {@link NetworkInfo} can vary based on UID, applications
181 * should always obtain network information through
Paul Jensen3541e9f2015-03-18 12:23:02 -0400182 * {@link #getActiveNetworkInfo()}.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700183 * @see #EXTRA_NETWORK_TYPE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700185 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700189 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700190 *
191 * @see android.content.Intent#getIntExtra(String, int)
192 */
193 public static final String EXTRA_NETWORK_TYPE = "networkType";
194
195 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 * The lookup key for a boolean that indicates whether a connect event
197 * is for a network to which the connectivity manager was failing over
198 * following a disconnect on another network.
199 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai3822c8a2018-12-13 12:47:51 +0800200 *
201 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 */
junyulai3822c8a2018-12-13 12:47:51 +0800203 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 public static final String EXTRA_IS_FAILOVER = "isFailover";
205 /**
206 * The lookup key for a {@link NetworkInfo} object. This is supplied when
207 * there is another network that it may be possible to connect to. Retrieve with
208 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800209 *
210 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 */
junyulai3822c8a2018-12-13 12:47:51 +0800212 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
214 /**
215 * The lookup key for a boolean that indicates whether there is a
216 * complete lack of connectivity, i.e., no network is available.
217 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
218 */
219 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
220 /**
221 * The lookup key for a string that indicates why an attempt to connect
222 * to a network failed. The string has no particular structure. It is
223 * intended to be used in notifications presented to users. Retrieve
224 * it with {@link android.content.Intent#getStringExtra(String)}.
225 */
226 public static final String EXTRA_REASON = "reason";
227 /**
228 * The lookup key for a string that provides optionally supplied
229 * extra information about the network state. The information
230 * may be passed up from the lower networking layers, and its
231 * meaning may be specific to a particular network type. Retrieve
232 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800233 *
234 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 */
junyulai3822c8a2018-12-13 12:47:51 +0800236 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700238 /**
239 * The lookup key for an int that provides information about
240 * our connection to the internet at large. 0 indicates no connection,
241 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700242 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700243 * {@hide}
244 */
245 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400247 * The lookup key for a {@link CaptivePortal} object included with the
248 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
249 * object can be used to either indicate to the system that the captive
250 * portal has been dismissed or that the user does not want to pursue
251 * signing in to captive portal. Retrieve it with
252 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500253 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400254 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700255
256 /**
257 * Key for passing a URL to the captive portal login activity.
258 */
259 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
260
Paul Jensen25a217c2015-02-27 22:55:47 -0500261 /**
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900262 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
263 * portal login activity.
264 * {@hide}
265 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900266 @SystemApi
267 @TestApi
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900268 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
269 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
270
271 /**
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900272 * Key for passing a user agent string to the captive portal login activity.
273 * {@hide}
274 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900275 @SystemApi
276 @TestApi
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900277 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
278 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
279
280 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700281 * Broadcast action to indicate the change of data activity status
282 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800283 * The network becomes active when data transmission is started, or
284 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700285 * {@hide}
286 */
287 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean4d660112018-06-04 16:52:49 +0900288 public static final String ACTION_DATA_ACTIVITY_CHANGE =
289 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700290 /**
291 * The lookup key for an enum that indicates the network device type on which this data activity
292 * change happens.
293 * {@hide}
294 */
295 public static final String EXTRA_DEVICE_TYPE = "deviceType";
296 /**
297 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
298 * it is actively sending or receiving data and {@code false} means it is idle.
299 * {@hide}
300 */
301 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700302 /**
303 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
304 * {@hide}
305 */
306 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700307
308 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 * Broadcast Action: The setting for background data usage has changed
310 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
311 * <p>
312 * If an application uses the network in the background, it should listen
313 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700314 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800315 * <p>
316 *
317 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
318 * of background data depends on several combined factors, and
319 * this broadcast is no longer sent. Instead, when background
320 * data is unavailable, {@link #getActiveNetworkInfo()} will now
321 * appear disconnected. During first boot after a platform
322 * upgrade, this broadcast will be sent once if
323 * {@link #getBackgroundDataSetting()} was {@code false} before
324 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 */
326 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800327 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
329 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
330
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700331 /**
332 * Broadcast Action: The network connection may not be good
333 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
334 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
335 * the network and it's condition.
336 * @hide
337 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800338 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100339 @UnsupportedAppUsage
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700340 public static final String INET_CONDITION_ACTION =
341 "android.net.conn.INET_CONDITION_ACTION";
342
Robert Greenwalt42acef32009-08-12 16:08:25 -0700343 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800344 * Broadcast Action: A tetherable connection has come or gone.
345 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline8351faa2017-04-17 16:47:23 +0900346 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
347 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800348 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
349 * the current state of tethering. Each include a list of
350 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800351 * @hide
352 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800353 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100354 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800355 public static final String ACTION_TETHER_STATE_CHANGED =
356 "android.net.conn.TETHER_STATE_CHANGED";
357
358 /**
359 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800360 * gives a String[] listing all the interfaces configured for
361 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800362 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100363 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800364 public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800365
366 /**
367 * @hide
Erik Kline8351faa2017-04-17 16:47:23 +0900368 * gives a String[] listing all the interfaces currently in local-only
369 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800370 */
Erik Kline8351faa2017-04-17 16:47:23 +0900371 public static final String EXTRA_ACTIVE_LOCAL_ONLY = "localOnlyArray";
372
373 /**
374 * @hide
375 * gives a String[] listing all the interfaces currently tethered
376 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
377 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100378 @UnsupportedAppUsage
Erik Kline8351faa2017-04-17 16:47:23 +0900379 public static final String EXTRA_ACTIVE_TETHER = "tetherArray";
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800380
381 /**
382 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800383 * gives a String[] listing all the interfaces we tried to tether and
384 * failed. Use {@link #getLastTetherError} to find the error code
385 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800386 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100387 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800388 public static final String EXTRA_ERRORED_TETHER = "erroredArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800389
390 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800391 * Broadcast Action: The captive portal tracker has finished its test.
392 * Sent only while running Setup Wizard, in lieu of showing a user
393 * notification.
394 * @hide
395 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800396 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800397 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
398 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
399 /**
400 * The lookup key for a boolean that indicates whether a captive portal was detected.
401 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
402 * @hide
403 */
404 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
405
406 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900407 * Action used to display a dialog that asks the user whether to connect to a network that is
408 * not validated. This intent is used to start the dialog in settings via startActivity.
409 *
410 * @hide
411 */
412 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
413
414 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900415 * Action used to display a dialog that asks the user whether to avoid a network that is no
416 * longer validated. This intent is used to start the dialog in settings via startActivity.
417 *
418 * @hide
419 */
420 public static final String ACTION_PROMPT_LOST_VALIDATION =
421 "android.net.conn.PROMPT_LOST_VALIDATION";
422
423 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800424 * Invalid 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 public static final int TETHERING_INVALID = -1;
429
430 /**
431 * Wifi tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900432 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800433 * @hide
434 */
435 @SystemApi
436 public static final int TETHERING_WIFI = 0;
437
438 /**
439 * USB tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900440 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800441 * @hide
442 */
443 @SystemApi
444 public static final int TETHERING_USB = 1;
445
446 /**
447 * Bluetooth tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900448 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800449 * @hide
450 */
451 @SystemApi
452 public static final int TETHERING_BLUETOOTH = 2;
453
454 /**
455 * Extra used for communicating with the TetherService. Includes the type of tethering to
456 * enable if any.
457 * @hide
458 */
459 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
460
461 /**
462 * Extra used for communicating with the TetherService. Includes the type of tethering for
463 * which to cancel provisioning.
464 * @hide
465 */
466 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
467
468 /**
469 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
470 * provisioning.
471 * @hide
472 */
473 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
474
475 /**
476 * Tells the TetherService to run a provision check now.
477 * @hide
478 */
479 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
480
481 /**
482 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
483 * which will receive provisioning results. Can be left empty.
484 * @hide
485 */
486 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
487
488 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800489 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700490 * @hide
491 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100492 @UnsupportedAppUsage
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700493 public static final int TYPE_NONE = -1;
494
495 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900496 * A Mobile data connection. Devices may support more than one.
497 *
498 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
499 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
500 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700501 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900502 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700503 public static final int TYPE_MOBILE = 0;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900504
Robert Greenwalt42acef32009-08-12 16:08:25 -0700505 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900506 * A WIFI data connection. Devices may support more than one.
507 *
508 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
509 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
510 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700511 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900512 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700513 public static final int TYPE_WIFI = 1;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900514
Robert Greenwalt42acef32009-08-12 16:08:25 -0700515 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800516 * An MMS-specific Mobile data connection. This network type may use the
517 * same network interface as {@link #TYPE_MOBILE} or it may use a different
518 * one. This is used by applications needing to talk to the carrier's
519 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900520 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900521 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900522 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900523 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700524 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700525 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700526 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900527
Robert Greenwalt42acef32009-08-12 16:08:25 -0700528 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800529 * A SUPL-specific Mobile data connection. This network type may use the
530 * same network interface as {@link #TYPE_MOBILE} or it may use a different
531 * one. This is used by applications needing to talk to the carrier's
532 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900533 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900534 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900535 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900536 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700537 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700538 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700539 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900540
Robert Greenwalt42acef32009-08-12 16:08:25 -0700541 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800542 * A DUN-specific Mobile data connection. This network type may use the
543 * same network interface as {@link #TYPE_MOBILE} or it may use a different
544 * one. This is sometimes by the system when setting up an upstream connection
545 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900546 *
547 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
548 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
549 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700550 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900551 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700552 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900553
Robert Greenwalt42acef32009-08-12 16:08:25 -0700554 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800555 * A High Priority Mobile data connection. This network type uses the
556 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900557 * is different.
558 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900559 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
560 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
561 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700562 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700563 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700564 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900565
jsh8214deb2010-03-11 15:04:43 -0800566 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900567 * A WiMAX data connection.
568 *
569 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
570 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
571 * appropriate network. {@see NetworkCapabilities} for supported transports.
jsh8214deb2010-03-11 15:04:43 -0800572 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900573 @Deprecated
jsh8214deb2010-03-11 15:04:43 -0800574 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800575
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800576 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900577 * A Bluetooth data connection.
578 *
579 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
580 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
581 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800582 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900583 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800584 public static final int TYPE_BLUETOOTH = 7;
585
Robert Greenwalt60810842011-04-22 15:28:18 -0700586 /**
587 * Dummy data connection. This should not be used on shipping devices.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900588 * @deprecated This is not used any more.
Robert Greenwalt60810842011-04-22 15:28:18 -0700589 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900590 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800591 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800592
Robert Greenwalt60810842011-04-22 15:28:18 -0700593 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900594 * An Ethernet data connection.
595 *
596 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
597 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
598 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt60810842011-04-22 15:28:18 -0700599 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900600 @Deprecated
Robert Greenwalte12aec92011-01-28 14:48:37 -0800601 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700602
Wink Saville9d7d6282011-03-12 14:52:01 -0800603 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800604 * Over the air Administration.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900605 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800606 * {@hide}
607 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900608 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100609 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800610 public static final int TYPE_MOBILE_FOTA = 10;
611
612 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800613 * IP Multimedia Subsystem.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900614 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800615 * {@hide}
616 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900617 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100618 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800619 public static final int TYPE_MOBILE_IMS = 11;
620
621 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800622 * Carrier Branded Services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900623 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800624 * {@hide}
625 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900626 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100627 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800628 public static final int TYPE_MOBILE_CBS = 12;
629
repo syncaea743a2011-07-29 23:55:49 -0700630 /**
631 * A Wi-Fi p2p connection. Only requesting processes will have access to
632 * the peers connected.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900633 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncaea743a2011-07-29 23:55:49 -0700634 * {@hide}
635 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900636 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100637 @UnsupportedAppUsage
repo syncaea743a2011-07-29 23:55:49 -0700638 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800639
Wink Saville5e56bc52013-07-29 15:00:57 -0700640 /**
641 * The network to use for initially attaching to the network
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900642 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville5e56bc52013-07-29 15:00:57 -0700643 * {@hide}
644 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900645 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100646 @UnsupportedAppUsage
Wink Saville5e56bc52013-07-29 15:00:57 -0700647 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700648
Lorenzo Colittie285b432015-04-23 15:32:42 +0900649 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700650 * Emergency PDN connection for emergency services. This
651 * may include IMS and MMS in emergency situations.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900652 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram3e0e3bc2014-06-26 11:03:44 -0700653 * {@hide}
654 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900655 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100656 @UnsupportedAppUsage
Ram3e0e3bc2014-06-26 11:03:44 -0700657 public static final int TYPE_MOBILE_EMERGENCY = 15;
658
Hui Lu1c5624a2014-01-15 11:05:36 -0500659 /**
660 * The network that uses proxy to achieve connectivity.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900661 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu1c5624a2014-01-15 11:05:36 -0500662 * {@hide}
663 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900664 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100665 @UnsupportedAppUsage
Hui Lu1c5624a2014-01-15 11:05:36 -0500666 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700667
Robert Greenwalt8283f882014-07-07 17:09:01 -0700668 /**
669 * A virtual network using one or more native bearers.
670 * It may or may not be providing security services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900671 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700672 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900673 @Deprecated
Robert Greenwalt8283f882014-07-07 17:09:01 -0700674 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500675
676 /** {@hide} */
Robert Greenwalt8283f882014-07-07 17:09:01 -0700677 public static final int MAX_RADIO_TYPE = TYPE_VPN;
678
679 /** {@hide} */
680 public static final int MAX_NETWORK_TYPE = TYPE_VPN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681
Hugo Benichi16f0a942017-06-20 14:07:59 +0900682 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
683
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800684 /**
685 * If you want to set the default network preference,you can directly
686 * change the networkAttributes array in framework's config.xml.
687 *
688 * @deprecated Since we support so many more networks now, the single
689 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800690 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800691 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800692 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800693 * from an App.
694 */
695 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
697
Jeff Sharkey625239a2012-09-26 22:03:49 -0700698 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700699 * @hide
700 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900701 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700702
Paul Jensen5d59e782014-07-11 12:28:19 -0400703 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900704 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
705 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean4d660112018-06-04 16:52:49 +0900706 * registered from those that were already unregistered.
Hugo Benichi31c176d2017-06-17 13:14:12 +0900707 * @hide
708 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900709 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900710 new NetworkRequest.Builder().clearCapabilities().build();
711
712 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400713 * A NetID indicating no Network is selected.
714 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
715 * @hide
716 */
717 public static final int NETID_UNSET = 0;
718
Erik Kline4d092232017-10-30 15:29:44 +0900719 /**
720 * Private DNS Mode values.
721 *
722 * The "private_dns_mode" global setting stores a String value which is
723 * expected to be one of the following.
724 */
725
726 /**
727 * @hide
728 */
729 public static final String PRIVATE_DNS_MODE_OFF = "off";
730 /**
731 * @hide
732 */
733 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
734 /**
735 * @hide
736 */
737 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
738 /**
739 * The default Private DNS mode.
740 *
741 * This may change from release to release or may become dependent upon
742 * the capabilities of the underlying platform.
743 *
744 * @hide
745 */
Erik Kline19841792018-05-16 16:41:57 +0900746 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline4d092232017-10-30 15:29:44 +0900747
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100748 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700749 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500750 /**
751 * A kludge to facilitate static access where a Context pointer isn't available, like in the
752 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
753 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
754 * methods that take a Context argument.
755 */
756 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900758 private final Context mContext;
759
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800760 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800761 private INetworkPolicyManager mNPManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800762
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800763 /**
764 * Tests if a given integer represents a valid network type.
765 * @param networkType the type to be tested
766 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400767 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
768 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800769 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700770 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700771 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900772 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 }
774
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800775 /**
776 * Returns a non-localized string representing a given network type.
777 * ONLY used for debugging output.
778 * @param type the type needing naming
779 * @return a String for the given type, or a string version of the type ("87")
780 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900781 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800782 * {@hide}
783 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900784 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100785 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700786 public static String getNetworkTypeName(int type) {
787 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900788 case TYPE_NONE:
789 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700790 case TYPE_MOBILE:
791 return "MOBILE";
792 case TYPE_WIFI:
793 return "WIFI";
794 case TYPE_MOBILE_MMS:
795 return "MOBILE_MMS";
796 case TYPE_MOBILE_SUPL:
797 return "MOBILE_SUPL";
798 case TYPE_MOBILE_DUN:
799 return "MOBILE_DUN";
800 case TYPE_MOBILE_HIPRI:
801 return "MOBILE_HIPRI";
802 case TYPE_WIMAX:
803 return "WIMAX";
804 case TYPE_BLUETOOTH:
805 return "BLUETOOTH";
806 case TYPE_DUMMY:
807 return "DUMMY";
808 case TYPE_ETHERNET:
809 return "ETHERNET";
810 case TYPE_MOBILE_FOTA:
811 return "MOBILE_FOTA";
812 case TYPE_MOBILE_IMS:
813 return "MOBILE_IMS";
814 case TYPE_MOBILE_CBS:
815 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700816 case TYPE_WIFI_P2P:
817 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700818 case TYPE_MOBILE_IA:
819 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700820 case TYPE_MOBILE_EMERGENCY:
821 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500822 case TYPE_PROXY:
823 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900824 case TYPE_VPN:
825 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700826 default:
827 return Integer.toString(type);
828 }
829 }
830
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800831 /**
832 * Checks if a given type uses the cellular data connection.
833 * This should be replaced in the future by a network property.
834 * @param networkType the type to check
835 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900836 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800837 * {@hide}
838 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900839 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100840 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700841 public static boolean isNetworkTypeMobile(int networkType) {
842 switch (networkType) {
843 case TYPE_MOBILE:
844 case TYPE_MOBILE_MMS:
845 case TYPE_MOBILE_SUPL:
846 case TYPE_MOBILE_DUN:
847 case TYPE_MOBILE_HIPRI:
848 case TYPE_MOBILE_FOTA:
849 case TYPE_MOBILE_IMS:
850 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700851 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700852 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700853 return true;
854 default:
855 return false;
856 }
857 }
858
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800859 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700860 * Checks if the given network type is backed by a Wi-Fi radio.
861 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900862 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700863 * @hide
864 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900865 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700866 public static boolean isNetworkTypeWifi(int networkType) {
867 switch (networkType) {
868 case TYPE_WIFI:
869 case TYPE_WIFI_P2P:
870 return true;
871 default:
872 return false;
873 }
874 }
875
876 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800877 * Specifies the preferred network type. When the device has more
878 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800879 *
880 * @param preference the network type to prefer over all others. It is
881 * unspecified what happens to the old preferred network in the
882 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700883 * @deprecated Functionality has been removed as it no longer makes sense,
884 * with many more than two networks - we'd need an array to express
885 * preference. Instead we use dynamic network properties of
886 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800887 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700888 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
891
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800892 /**
893 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800894 *
895 * @return an integer representing the preferred network type
896 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700897 * @deprecated Functionality has been removed as it no longer makes sense,
898 * with many more than two networks - we'd need an array to express
899 * preference. Instead we use dynamic network properties of
900 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800901 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700902 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600903 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700905 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 }
907
Scott Main671644c2011-10-06 19:02:28 -0700908 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800909 * Returns details about the currently active default data network. When
910 * connected, this network is the default route for outgoing connections.
911 * You should always check {@link NetworkInfo#isConnected()} before initiating
912 * network traffic. This may return {@code null} when there is no default
913 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900914 * Note that if the default network is a VPN, this method will return the
915 * NetworkInfo for one of its underlying networks instead, or null if the
916 * VPN agent did not specify any. Apps interested in learning about VPNs
917 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800918 *
919 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500920 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800921 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700922 */
junyulai3822c8a2018-12-13 12:47:51 +0800923 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600924 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900925 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 public NetworkInfo getActiveNetworkInfo() {
927 try {
928 return mService.getActiveNetworkInfo();
929 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700930 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
932 }
933
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800934 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500935 * Returns a {@link Network} object corresponding to the currently active
936 * default data network. In the event that the current active default data
937 * network disconnects, the returned {@code Network} object will no longer
938 * be usable. This will return {@code null} when there is no default
939 * network.
940 *
941 * @return a {@link Network} object for the current default network or
942 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500943 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600944 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900945 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -0500946 public Network getActiveNetwork() {
947 try {
948 return mService.getActiveNetwork();
949 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700950 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500951 }
952 }
953
954 /**
Robin Leed2baf792016-03-24 12:07:00 +0000955 * Returns a {@link Network} object corresponding to the currently active
956 * default data network for a specific UID. In the event that the default data
957 * network disconnects, the returned {@code Network} object will no longer
958 * be usable. This will return {@code null} when there is no default
959 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +0000960 *
961 * @return a {@link Network} object for the current default network for the
962 * given UID or {@code null} if no default network is currently active
963 *
964 * @hide
965 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600966 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900967 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +0000968 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600969 return getActiveNetworkForUid(uid, false);
970 }
971
972 /** {@hide} */
973 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +0000974 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600975 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +0000976 } catch (RemoteException e) {
977 throw e.rethrowFromSystemServer();
978 }
979 }
980
981 /**
Charles He36738632017-05-15 17:07:18 +0100982 * Checks if a VPN app supports always-on mode.
983 *
984 * In order to support the always-on feature, an app has to
985 * <ul>
986 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +0100987 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
988 * meta-data field.
Charles He36738632017-05-15 17:07:18 +0100989 * </ul>
990 *
991 * @param userId The identifier of the user for whom the VPN app is installed.
992 * @param vpnPackage The canonical package name of the VPN app.
993 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
994 * @hide
995 */
996 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
997 try {
998 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
999 } catch (RemoteException e) {
1000 throw e.rethrowFromSystemServer();
1001 }
1002 }
1003
1004 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001005 * Configures an always-on VPN connection through a specific application.
1006 * This connection is automatically granted and persisted after a reboot.
1007 *
1008 * <p>The designated package should declare a {@link VpnService} in its
1009 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1010 * otherwise the call will fail.
1011 *
1012 * @param userId The identifier of the user to set an always-on VPN for.
1013 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1014 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001015 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1016 * {@code false} otherwise.
Pavel Grafova462bcb2019-01-25 08:50:06 +00001017 * @param lockdownWhitelist The list of packages that are allowed to access network directly
1018 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
1019 * this method must be called when a package that should be whitelisted is installed or
1020 * uninstalled.
Robin Lee244ce8e2016-01-05 18:03:46 +00001021 * @return {@code true} if the package is set as always-on VPN controller;
1022 * {@code false} otherwise.
1023 * @hide
1024 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001025 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leedc679712016-05-03 13:23:03 +01001026 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001027 boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001028 try {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001029 return mService.setAlwaysOnVpnPackage(
1030 userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
Robin Lee244ce8e2016-01-05 18:03:46 +00001031 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001032 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001033 }
1034 }
1035
1036 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001037 * Configures an always-on VPN connection through a specific application.
1038 * This connection is automatically granted and persisted after a reboot.
1039 *
1040 * <p>The designated package should declare a {@link VpnService} in its
1041 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1042 * otherwise the call will fail.
1043 *
1044 * @param userId The identifier of the user to set an always-on VPN for.
1045 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1046 * to remove an existing always-on VPN configuration.
1047 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1048 * {@code false} otherwise.
1049 * @return {@code true} if the package is set as always-on VPN controller;
1050 * {@code false} otherwise.
1051 * @hide
1052 */
1053 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1054 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
1055 boolean lockdownEnabled) {
1056 try {
1057 return mService.setAlwaysOnVpnPackage(
1058 userId, vpnPackage, lockdownEnabled, /* whitelist */ null);
1059 } catch (RemoteException e) {
1060 throw e.rethrowFromSystemServer();
1061 }
1062 }
1063
1064 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001065 * Returns the package name of the currently set always-on VPN application.
1066 * If there is no always-on VPN set, or the VPN is provided by the system instead
1067 * of by an app, {@code null} will be returned.
1068 *
1069 * @return Package name of VPN controller responsible for always-on VPN,
1070 * or {@code null} if none is set.
1071 * @hide
1072 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001073 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee244ce8e2016-01-05 18:03:46 +00001074 public String getAlwaysOnVpnPackageForUser(int userId) {
1075 try {
1076 return mService.getAlwaysOnVpnPackage(userId);
1077 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001078 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001079 }
1080 }
1081
1082 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001083 * @return whether always-on VPN is in lockdown mode.
1084 *
1085 * @hide
1086 **/
1087 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1088 public boolean isVpnLockdownEnabled(int userId) {
1089 try {
1090 return mService.isVpnLockdownEnabled(userId);
1091 } catch (RemoteException e) {
1092 throw e.rethrowFromSystemServer();
1093 }
1094
1095 }
1096
1097 /**
1098 * @return the list of packages that are allowed to access network when always-on VPN is in
1099 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1100 *
1101 * @hide
1102 **/
1103 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1104 public List<String> getVpnLockdownWhitelist(int userId) {
1105 try {
1106 return mService.getVpnLockdownWhitelist(userId);
1107 } catch (RemoteException e) {
1108 throw e.rethrowFromSystemServer();
1109 }
1110 }
1111
1112 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001113 * Returns details about the currently active default data network
1114 * for a given uid. This is for internal use only to avoid spying
1115 * other apps.
1116 *
1117 * @return a {@link NetworkInfo} object for the current default network
1118 * for the given uid or {@code null} if no default network is
1119 * available for the specified uid.
1120 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001121 * {@hide}
1122 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001123 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001124 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001125 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001126 return getActiveNetworkInfoForUid(uid, false);
1127 }
1128
1129 /** {@hide} */
1130 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001131 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001132 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001133 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001134 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001135 }
1136 }
1137
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001138 /**
1139 * Returns connection status information about a particular
1140 * network type.
1141 *
1142 * @param networkType integer specifying which networkType in
1143 * which you're interested.
1144 * @return a {@link NetworkInfo} object for the requested
1145 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001146 * supported by the device. If {@code networkType} is
1147 * TYPE_VPN and a VPN is active for the calling app,
1148 * then this method will try to return one of the
1149 * underlying networks for the VPN or null if the
1150 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001151 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001152 * @deprecated This method does not support multiple connected networks
1153 * of the same type. Use {@link #getAllNetworks} and
1154 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001155 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001156 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001157 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001158 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 public NetworkInfo getNetworkInfo(int networkType) {
1160 try {
1161 return mService.getNetworkInfo(networkType);
1162 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001163 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 }
1165 }
1166
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001167 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001168 * Returns connection status information about a particular
1169 * Network.
1170 *
1171 * @param network {@link Network} specifying which network
1172 * in which you're interested.
1173 * @return a {@link NetworkInfo} object for the requested
1174 * network or {@code null} if the {@code Network}
1175 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001176 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001177 */
junyulai3822c8a2018-12-13 12:47:51 +08001178 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001179 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001180 @Nullable
1181 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001182 return getNetworkInfoForUid(network, Process.myUid(), false);
1183 }
1184
1185 /** {@hide} */
1186 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001187 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001188 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001189 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001190 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001191 }
1192 }
1193
1194 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001195 * Returns connection status information about all network
1196 * types supported by the device.
1197 *
1198 * @return an array of {@link NetworkInfo} objects. Check each
1199 * {@link NetworkInfo#getType} for which type each applies.
1200 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001201 * @deprecated This method does not support multiple connected networks
1202 * of the same type. Use {@link #getAllNetworks} and
1203 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001204 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001205 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001206 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001207 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 public NetworkInfo[] getAllNetworkInfo() {
1209 try {
1210 return mService.getAllNetworkInfo();
1211 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001212 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 }
1214 }
1215
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001216 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001217 * Returns the {@link Network} object currently serving a given type, or
1218 * null if the given type is not connected.
1219 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001220 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001221 * @deprecated This method does not support multiple connected networks
1222 * of the same type. Use {@link #getAllNetworks} and
1223 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001224 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001225 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001226 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001227 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001228 public Network getNetworkForType(int networkType) {
1229 try {
1230 return mService.getNetworkForType(networkType);
1231 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001232 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001233 }
1234 }
1235
1236 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001237 * Returns an array of all {@link Network} currently tracked by the
1238 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001239 *
1240 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001241 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001242 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001243 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001244 public Network[] getAllNetworks() {
1245 try {
1246 return mService.getAllNetworks();
1247 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001248 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001249 }
1250 }
1251
1252 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001253 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001254 * the Networks that applications run by the given user will use by default.
1255 * @hide
1256 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001257 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001258 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1259 try {
1260 return mService.getDefaultNetworkCapabilitiesForUser(userId);
1261 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001262 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001263 }
1264 }
1265
1266 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001267 * Returns the IP information for the current default network.
1268 *
1269 * @return a {@link LinkProperties} object describing the IP info
1270 * for the current default network, or {@code null} if there
1271 * is no current default network.
1272 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001273 * {@hide}
1274 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001275 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001276 @UnsupportedAppUsage
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001277 public LinkProperties getActiveLinkProperties() {
1278 try {
1279 return mService.getActiveLinkProperties();
1280 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001281 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001282 }
1283 }
1284
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001285 /**
1286 * Returns the IP information for a given network type.
1287 *
1288 * @param networkType the network type of interest.
1289 * @return a {@link LinkProperties} object describing the IP info
1290 * for the given networkType, or {@code null} if there is
1291 * no current default network.
1292 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001293 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001294 * @deprecated This method does not support multiple connected networks
1295 * of the same type. Use {@link #getAllNetworks},
1296 * {@link #getNetworkInfo(android.net.Network)}, and
1297 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001298 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001299 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001300 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001301 @UnsupportedAppUsage
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001302 public LinkProperties getLinkProperties(int networkType) {
1303 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001304 return mService.getLinkPropertiesForType(networkType);
1305 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001306 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001307 }
1308 }
1309
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001310 /**
1311 * Get the {@link LinkProperties} for the given {@link Network}. This
1312 * will return {@code null} if the network is unknown.
1313 *
1314 * @param network The {@link Network} object identifying the network in question.
1315 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001316 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001317 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001318 @Nullable
1319 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001320 try {
1321 return mService.getLinkProperties(network);
1322 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001323 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001324 }
1325 }
1326
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001327 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001328 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001329 * will return {@code null} if the network is unknown.
1330 *
1331 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001332 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001333 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001334 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001335 @Nullable
1336 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001337 try {
1338 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001339 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001340 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001341 }
1342 }
1343
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001344 /**
Udam Sainib7c24872016-01-04 12:16:14 -08001345 * Gets the URL that should be used for resolving whether a captive portal is present.
1346 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1347 * portal is present.
1348 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1349 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1350 *
1351 * @hide
1352 */
1353 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07001354 @RequiresPermission(android.Manifest.permission.LOCAL_MAC_ADDRESS)
Udam Sainib7c24872016-01-04 12:16:14 -08001355 public String getCaptivePortalServerUrl() {
1356 try {
1357 return mService.getCaptivePortalServerUrl();
1358 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001359 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001360 }
1361 }
1362
1363 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 * Tells the underlying networking system that the caller wants to
1365 * begin using the named feature. The interpretation of {@code feature}
1366 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001367 *
1368 * <p>This method requires the caller to hold either the
1369 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1370 * or the ability to modify system settings as determined by
1371 * {@link android.provider.Settings.System#canWrite}.</p>
1372 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 * @param networkType specifies which network the request pertains to
1374 * @param feature the name of the feature to be used
1375 * @return an integer value representing the outcome of the request.
1376 * The interpretation of this value is specific to each networking
1377 * implementation+feature combination, except that the value {@code -1}
1378 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001379 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001380 * @deprecated Deprecated in favor of the cleaner
1381 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001382 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001383 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001384 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001386 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001388 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001389 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1390 if (netCap == null) {
1391 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1392 feature);
1393 return PhoneConstants.APN_REQUEST_FAILED;
1394 }
1395
1396 NetworkRequest request = null;
1397 synchronized (sLegacyRequests) {
1398 LegacyRequest l = sLegacyRequests.get(netCap);
1399 if (l != null) {
1400 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1401 renewRequestLocked(l);
1402 if (l.currentNetwork != null) {
1403 return PhoneConstants.APN_ALREADY_ACTIVE;
1404 } else {
1405 return PhoneConstants.APN_REQUEST_STARTED;
1406 }
1407 }
1408
1409 request = requestNetworkForFeatureLocked(netCap);
1410 }
1411 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001412 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001413 return PhoneConstants.APN_REQUEST_STARTED;
1414 } else {
1415 Log.d(TAG, " request Failed");
1416 return PhoneConstants.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 }
1419
1420 /**
1421 * Tells the underlying networking system that the caller is finished
1422 * using the named feature. The interpretation of {@code feature}
1423 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001424 *
1425 * <p>This method requires the caller to hold either the
1426 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1427 * or the ability to modify system settings as determined by
1428 * {@link android.provider.Settings.System#canWrite}.</p>
1429 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 * @param networkType specifies which network the request pertains to
1431 * @param feature the name of the feature that is no longer needed
1432 * @return an integer value representing the outcome of the request.
1433 * The interpretation of this value is specific to each networking
1434 * implementation+feature combination, except that the value {@code -1}
1435 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001436 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001437 * @deprecated Deprecated in favor of the cleaner
1438 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001439 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001440 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001441 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001443 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001445 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001446 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1447 if (netCap == null) {
1448 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1449 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 return -1;
1451 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001452
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001453 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001454 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001455 }
1456 return 1;
1457 }
1458
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001459 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001460 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1461 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001462 switch (feature) {
1463 case "enableCBS":
1464 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1465 case "enableDUN":
1466 case "enableDUNAlways":
1467 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1468 case "enableFOTA":
1469 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1470 case "enableHIPRI":
1471 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1472 case "enableIMS":
1473 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1474 case "enableMMS":
1475 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1476 case "enableSUPL":
1477 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1478 default:
1479 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001480 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001481 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1482 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001483 }
1484 return null;
1485 }
1486
Robert Greenwalt06314e42014-10-29 14:04:06 -07001487 /**
1488 * Guess what the network request was trying to say so that the resulting
1489 * network is accessible via the legacy (deprecated) API such as
1490 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001491 *
1492 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001493 * capability but ignore things such as networkSpecifier.
1494 * If the request has more than one transport or capability it doesn't
1495 * match the old legacy requests (they selected only single transport/capability)
1496 * so this function cannot map the request to a single legacy type and
1497 * the resulting network will not be available to the legacy APIs.
1498 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001499 * This code is only called from the requestNetwork API (L and above).
1500 *
1501 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1502 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1503 * do this for SUPL requests, which are the only ones that we know need it. If
1504 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1505 * compatibility we can send them:
1506 *
1507 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1508 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1509 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001510 * TODO - This should be removed when the legacy APIs are removed.
1511 */
Ye Wenb87875e2014-07-21 14:19:01 -07001512 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1513 if (netCap == null) {
1514 return TYPE_NONE;
1515 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001516
Ye Wenb87875e2014-07-21 14:19:01 -07001517 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1518 return TYPE_NONE;
1519 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001520
Lifu Tang30f95a72016-01-07 23:20:38 -08001521 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001522 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1523 // NOTE: if this causes app breakage, we should not just comment out this early return;
1524 // instead, we should make this early return conditional on the requesting app's target
1525 // SDK version, as described in the comment above.
1526 return TYPE_NONE;
1527 }
1528
Robert Greenwalt06314e42014-10-29 14:04:06 -07001529 String type = null;
1530 int result = TYPE_NONE;
1531
Ye Wenb87875e2014-07-21 14:19:01 -07001532 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001533 type = "enableCBS";
1534 result = TYPE_MOBILE_CBS;
1535 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1536 type = "enableIMS";
1537 result = TYPE_MOBILE_IMS;
1538 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1539 type = "enableFOTA";
1540 result = TYPE_MOBILE_FOTA;
1541 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1542 type = "enableDUN";
1543 result = TYPE_MOBILE_DUN;
1544 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001545 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001546 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001547 // back out this hack for mms as they no longer need this and it's causing
1548 // device slowdowns - b/23350688 (note, supl still needs this)
1549 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1550 // type = "enableMMS";
1551 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001552 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1553 type = "enableHIPRI";
1554 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001555 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001556 if (type != null) {
1557 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1558 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1559 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001560 }
1561 }
1562 return TYPE_NONE;
1563 }
1564
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001565 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001566 if (netCap == null) return TYPE_NONE;
1567 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1568 return TYPE_MOBILE_CBS;
1569 }
1570 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1571 return TYPE_MOBILE_IMS;
1572 }
1573 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1574 return TYPE_MOBILE_FOTA;
1575 }
1576 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1577 return TYPE_MOBILE_DUN;
1578 }
1579 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1580 return TYPE_MOBILE_SUPL;
1581 }
1582 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1583 return TYPE_MOBILE_MMS;
1584 }
1585 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1586 return TYPE_MOBILE_HIPRI;
1587 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001588 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1589 return TYPE_WIFI_P2P;
1590 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001591 return TYPE_NONE;
1592 }
1593
1594 private static class LegacyRequest {
1595 NetworkCapabilities networkCapabilities;
1596 NetworkRequest networkRequest;
1597 int expireSequenceNumber;
1598 Network currentNetwork;
1599 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001600
1601 private void clearDnsBinding() {
1602 if (currentNetwork != null) {
1603 currentNetwork = null;
1604 setProcessDefaultNetworkForHostResolution(null);
1605 }
1606 }
1607
Robert Greenwalt6078b502014-06-11 16:05:07 -07001608 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001609 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001610 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001611 currentNetwork = network;
1612 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001613 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001614 }
1615 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001616 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001617 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001618 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1619 }
1620 };
1621 }
1622
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001623 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001624 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1625 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001626
1627 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1628 synchronized (sLegacyRequests) {
1629 LegacyRequest l = sLegacyRequests.get(netCap);
1630 if (l != null) return l.networkRequest;
1631 }
1632 return null;
1633 }
1634
1635 private void renewRequestLocked(LegacyRequest l) {
1636 l.expireSequenceNumber++;
1637 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1638 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1639 }
1640
1641 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1642 int ourSeqNum = -1;
1643 synchronized (sLegacyRequests) {
1644 LegacyRequest l = sLegacyRequests.get(netCap);
1645 if (l == null) return;
1646 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001647 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001648 }
1649 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1650 }
1651
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001652 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001653 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1654 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001655 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001656 try {
1657 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001658 } catch (RemoteException e) {
1659 throw e.rethrowFromSystemServer();
1660 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001661 LegacyRequest l = new LegacyRequest();
1662 l.networkCapabilities = netCap;
1663 l.delay = delay;
1664 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001665 l.networkRequest = sendRequestForNetwork(
1666 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001667 if (l.networkRequest == null) return null;
1668 sLegacyRequests.put(netCap, l);
1669 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1670 return l.networkRequest;
1671 }
1672
1673 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1674 if (delay >= 0) {
1675 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001676 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001677 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1678 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001679 }
1680 }
1681
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001682 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001683 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1684 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001685 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001686 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001687 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001688 if (l == null) return false;
1689 unregisterNetworkCallback(l.networkCallback);
1690 l.clearDnsBinding();
1691 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693
Erik Kline35bf06c2017-01-26 18:08:28 +09001694 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1695 static {
1696 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1697 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1698 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1699 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1700 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1701 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1702 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1703 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1704 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1705 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1706 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1707 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1708 }
1709
1710 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1711 static {
1712 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1713 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1714 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1715 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1716 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1717 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1718 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1719 }
1720
1721 /**
1722 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1723 * instance suitable for registering a request or callback. Throws an
1724 * IllegalArgumentException if no mapping from the legacy type to
1725 * NetworkCapabilities is known.
1726 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001727 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1728 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001729 * @hide
1730 */
1731 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1732 final NetworkCapabilities nc = new NetworkCapabilities();
1733
1734 // Map from type to transports.
1735 final int NOT_FOUND = -1;
1736 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001737 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001738 nc.addTransportType(transport);
1739
1740 // Map from type to capabilities.
1741 nc.addCapability(sLegacyTypeToCapability.get(
1742 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1743 nc.maybeMarkCapabilitiesRestricted();
1744 return nc;
1745 }
1746
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001747 /** @hide */
1748 public static class PacketKeepaliveCallback {
1749 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001750 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001751 public void onStarted() {}
1752 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001753 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001754 public void onStopped() {}
1755 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001756 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001757 public void onError(int error) {}
1758 }
1759
1760 /**
1761 * Allows applications to request that the system periodically send specific packets on their
1762 * behalf, using hardware offload to save battery power.
1763 *
1764 * To request that the system send keepalives, call one of the methods that return a
1765 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1766 * passing in a non-null callback. If the callback is successfully started, the callback's
1767 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1768 * specifying one of the {@code ERROR_*} constants in this class.
1769 *
Chalard Jean4d660112018-06-04 16:52:49 +09001770 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1771 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1772 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001773 *
junyulai48eac1d42018-12-27 17:25:29 +08001774 * @deprecated Use {@link SocketKeepalive} instead.
1775 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001776 * @hide
1777 */
1778 public class PacketKeepalive {
1779
1780 private static final String TAG = "PacketKeepalive";
1781
1782 /** @hide */
1783 public static final int SUCCESS = 0;
1784
1785 /** @hide */
1786 public static final int NO_KEEPALIVE = -1;
1787
1788 /** @hide */
1789 public static final int BINDER_DIED = -10;
1790
1791 /** The specified {@code Network} is not connected. */
1792 public static final int ERROR_INVALID_NETWORK = -20;
1793 /** The specified IP addresses are invalid. For example, the specified source IP address is
1794 * not configured on the specified {@code Network}. */
1795 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1796 /** The requested port is invalid. */
1797 public static final int ERROR_INVALID_PORT = -22;
1798 /** The packet length is invalid (e.g., too long). */
1799 public static final int ERROR_INVALID_LENGTH = -23;
1800 /** The packet transmission interval is invalid (e.g., too short). */
1801 public static final int ERROR_INVALID_INTERVAL = -24;
1802
1803 /** The hardware does not support this request. */
1804 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001805 /** The hardware returned an error. */
1806 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001807
Nathan Harold63dd8132018-02-14 13:09:45 -08001808 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001809 public static final int NATT_PORT = 4500;
1810
Nathan Harold63dd8132018-02-14 13:09:45 -08001811 /** The minimum interval in seconds between keepalive packet transmissions */
1812 public static final int MIN_INTERVAL = 10;
1813
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001814 private final Network mNetwork;
1815 private final PacketKeepaliveCallback mCallback;
1816 private final Looper mLooper;
1817 private final Messenger mMessenger;
1818
1819 private volatile Integer mSlot;
1820
1821 void stopLooper() {
1822 mLooper.quit();
1823 }
1824
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001825 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001826 public void stop() {
1827 try {
1828 mService.stopKeepalive(mNetwork, mSlot);
1829 } catch (RemoteException e) {
1830 Log.e(TAG, "Error stopping packet keepalive: ", e);
1831 stopLooper();
1832 }
1833 }
1834
1835 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001836 Preconditions.checkNotNull(network, "network cannot be null");
1837 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001838 mNetwork = network;
1839 mCallback = callback;
1840 HandlerThread thread = new HandlerThread(TAG);
1841 thread.start();
1842 mLooper = thread.getLooper();
1843 mMessenger = new Messenger(new Handler(mLooper) {
1844 @Override
1845 public void handleMessage(Message message) {
1846 switch (message.what) {
1847 case NetworkAgent.EVENT_PACKET_KEEPALIVE:
1848 int error = message.arg2;
1849 try {
1850 if (error == SUCCESS) {
1851 if (mSlot == null) {
1852 mSlot = message.arg1;
1853 mCallback.onStarted();
1854 } else {
1855 mSlot = null;
1856 stopLooper();
1857 mCallback.onStopped();
1858 }
1859 } else {
1860 stopLooper();
1861 mCallback.onError(error);
1862 }
1863 } catch (Exception e) {
1864 Log.e(TAG, "Exception in keepalive callback(" + error + ")", e);
1865 }
1866 break;
1867 default:
1868 Log.e(TAG, "Unhandled message " + Integer.toHexString(message.what));
1869 break;
1870 }
1871 }
1872 });
1873 }
1874 }
1875
1876 /**
1877 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1878 *
junyulai48eac1d42018-12-27 17:25:29 +08001879 * @deprecated Use {@link #createSocketKeepalive} instead.
1880 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001881 * @hide
1882 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001883 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001884 public PacketKeepalive startNattKeepalive(
1885 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1886 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1887 final PacketKeepalive k = new PacketKeepalive(network, callback);
1888 try {
1889 mService.startNattKeepalive(network, intervalSeconds, k.mMessenger, new Binder(),
1890 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1891 } catch (RemoteException e) {
1892 Log.e(TAG, "Error starting packet keepalive: ", e);
1893 k.stopLooper();
1894 return null;
1895 }
1896 return k;
1897 }
1898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 /**
junyulai48eac1d42018-12-27 17:25:29 +08001900 * Request that keepalives be started on a IPsec NAT-T socket.
1901 *
1902 * @param network The {@link Network} the socket is on.
1903 * @param socket The socket that needs to be kept alive.
1904 * @param source The source address of the {@link UdpEncapsulationSocket}.
1905 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1906 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1907 * must run callback sequentially, otherwise the order of callbacks cannot be
1908 * guaranteed.
1909 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1910 * changes. Must be extended by applications that use this API.
1911 *
1912 * @return A {@link SocketKeepalive} object, which can be used to control this keepalive object.
1913 **/
1914 public SocketKeepalive createSocketKeepalive(@NonNull Network network,
1915 @NonNull UdpEncapsulationSocket socket,
1916 @NonNull InetAddress source,
1917 @NonNull InetAddress destination,
1918 @NonNull @CallbackExecutor Executor executor,
1919 @NonNull Callback callback) {
junyulai215b8772019-01-15 11:32:44 +08001920 return new NattSocketKeepalive(mService, network, socket.getFileDescriptor(),
1921 socket.getResourceId(), source, destination, executor, callback);
1922 }
1923
1924 /**
1925 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1926 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1927 *
1928 * @param network The {@link Network} the socket is on.
1929 * @param fd The {@link FileDescriptor} that needs to be kept alive. The provided
1930 * {@link FileDescriptor} must be bound to a port and the keepalives will be sent from
1931 * that port.
1932 * @param source The source address of the {@link UdpEncapsulationSocket}.
1933 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1934 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1935 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1936 * must run callback sequentially, otherwise the order of callbacks cannot be
1937 * guaranteed.
1938 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1939 * changes. Must be extended by applications that use this API.
1940 *
1941 * @hide
1942 */
1943 @SystemApi
1944 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
1945 public SocketKeepalive createNattKeepalive(@NonNull Network network,
1946 @NonNull FileDescriptor fd,
1947 @NonNull InetAddress source,
1948 @NonNull InetAddress destination,
1949 @NonNull @CallbackExecutor Executor executor,
1950 @NonNull Callback callback) {
1951 return new NattSocketKeepalive(mService, network, fd, INVALID_RESOURCE_ID /* Unused */,
1952 source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08001953 }
1954
1955 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 * Ensure that a network route exists to deliver traffic to the specified
1957 * host via the specified network interface. An attempt to add a route that
1958 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001959 *
1960 * <p>This method requires the caller to hold either the
1961 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1962 * or the ability to modify system settings as determined by
1963 * {@link android.provider.Settings.System#canWrite}.</p>
1964 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 * @param networkType the type of the network over which traffic to the specified
1966 * host is to be routed
1967 * @param hostAddress the IP address of the host to which the route is desired
1968 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001969 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001970 * @deprecated Deprecated in favor of the
1971 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
1972 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001973 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001974 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001975 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001977 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001979 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001980 }
1981
1982 /**
1983 * Ensure that a network route exists to deliver traffic to the specified
1984 * host via the specified network interface. An attempt to add a route that
1985 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001986 *
1987 * <p>This method requires the caller to hold either the
1988 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1989 * or the ability to modify system settings as determined by
1990 * {@link android.provider.Settings.System#canWrite}.</p>
1991 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001992 * @param networkType the type of the network over which traffic to the specified
1993 * host is to be routed
1994 * @param hostAddress the IP address of the host to which the route is desired
1995 * @return {@code true} on success, {@code false} on failure
1996 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001997 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001998 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001999 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002000 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002001 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002002 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002003 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002005 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002007 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009 }
2010
2011 /**
2012 * Returns the value of the setting for background data usage. If false,
2013 * applications should not use the network if the application is not in the
2014 * foreground. Developers should respect this setting, and check the value
2015 * of this before performing any background data operations.
2016 * <p>
2017 * All applications that have background services that use the network
2018 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002019 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002020 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002021 * background data depends on several combined factors, and this method will
2022 * always return {@code true}. Instead, when background data is unavailable,
2023 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002024 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 * @return Whether background data usage is allowed.
2026 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002027 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002029 // assume that background data is allowed; final authority is
2030 // NetworkInfo which may be blocked.
2031 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033
2034 /**
2035 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002036 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 * @param allowBackgroundData Whether an application should use data while
2038 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002039 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2041 * @see #getBackgroundDataSetting()
2042 * @hide
2043 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002044 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002045 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002047 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002049
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002050 /** {@hide} */
2051 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002052 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002053 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2054 try {
2055 return mService.getActiveNetworkQuotaInfo();
2056 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002057 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002058 }
2059 }
2060
2061 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002062 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002063 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002064 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002065 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002066 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002067 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002068 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
2069 if (b != null) {
2070 try {
2071 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08002072 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08002073 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
Malcolm Chenb455e722017-11-28 15:57:14 -08002074 boolean retVal = it.isUserDataEnabled(subId);
Wink Saville36ffb042014-12-05 11:10:30 -08002075 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2076 + " retVal=" + retVal);
2077 return retVal;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002078 } catch (RemoteException e) {
2079 throw e.rethrowFromSystemServer();
2080 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002081 }
Wink Saville36ffb042014-12-05 11:10:30 -08002082 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002083 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002084 }
2085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002087 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002088 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002089 */
2090 public interface OnNetworkActiveListener {
2091 /**
2092 * Called on the main thread of the process to report that the current data network
2093 * has become active, and it is now a good time to perform any pending network
2094 * operations. Note that this listener only tells you when the network becomes
2095 * active; if at any other time you want to know whether it is active (and thus okay
2096 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002097 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002098 */
Chalard Jean4d660112018-06-04 16:52:49 +09002099 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002100 }
2101
2102 private INetworkManagementService getNetworkManagementService() {
2103 synchronized (this) {
2104 if (mNMService != null) {
2105 return mNMService;
2106 }
2107 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2108 mNMService = INetworkManagementService.Stub.asInterface(b);
2109 return mNMService;
2110 }
2111 }
2112
2113 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002114 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002115
2116 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002117 * Start listening to reports when the system's default data network is active, meaning it is
2118 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2119 * to determine the current state of the system's default network after registering the
2120 * listener.
2121 * <p>
2122 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002123 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002124 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002125 *
2126 * @param l The listener to be told when the network is active.
2127 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002128 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002129 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2130 @Override
2131 public void onNetworkActive() throws RemoteException {
2132 l.onNetworkActive();
2133 }
2134 };
2135
2136 try {
2137 getNetworkManagementService().registerNetworkActivityListener(rl);
2138 mNetworkActivityListeners.put(l, rl);
2139 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002140 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002141 }
2142 }
2143
2144 /**
2145 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002146 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002147 *
2148 * @param l Previously registered listener.
2149 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002150 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002151 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002152 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002153 try {
2154 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2155 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002156 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002157 }
2158 }
2159
2160 /**
2161 * Return whether the data network is currently active. An active network means that
2162 * it is currently in a high power state for performing data transmission. On some
2163 * types of networks, it may be expensive to move and stay in such a state, so it is
2164 * more power efficient to batch network traffic together when the radio is already in
2165 * this state. This method tells you whether right now is currently a good time to
2166 * initiate network traffic, as the network is already active.
2167 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002168 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002169 try {
2170 return getNetworkManagementService().isNetworkActive();
2171 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002172 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002173 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002174 }
2175
2176 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 * {@hide}
2178 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002179 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002180 mContext = Preconditions.checkNotNull(context, "missing context");
2181 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05002182 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002184
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002185 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002186 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002187 public static ConnectivityManager from(Context context) {
2188 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2189 }
2190
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002191 /** @hide */
2192 public NetworkRequest getDefaultRequest() {
2193 try {
2194 // This is not racy as the default request is final in ConnectivityService.
2195 return mService.getDefaultRequest();
2196 } catch (RemoteException e) {
2197 throw e.rethrowFromSystemServer();
2198 }
2199 }
2200
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002201 /* TODO: These permissions checks don't belong in client-side code. Move them to
2202 * services.jar, possibly in com.android.server.net. */
2203
2204 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002205 public static final void enforceChangePermission(Context context) {
2206 int uid = Binder.getCallingUid();
2207 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2208 .getPackageNameForUid(context, uid), true /* throwException */);
2209 }
2210
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002211 /** {@hide} */
2212 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002213 Preconditions.checkNotNull(context, "Context cannot be null");
2214 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002215
Robert Greenwaltedb47662014-09-16 17:54:19 -07002216 if (context.getResources().getStringArray(
2217 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2218 // Have a provisioning app - must only let system apps (which check this app)
2219 // turn on tethering
2220 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002221 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002222 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002223 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002224 // If callingPkg's uid is not same as Binder.getCallingUid(),
2225 // AppOpsService throws SecurityException.
2226 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2227 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002228 }
2229 }
2230
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002231 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002232 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2233 * situations where a Context pointer is unavailable.
2234 * @hide
2235 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002236 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002237 static ConnectivityManager getInstanceOrNull() {
2238 return sInstance;
2239 }
2240
2241 /**
2242 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2243 * situations where a Context pointer is unavailable.
2244 * @hide
2245 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002246 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002247 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002248 private static ConnectivityManager getInstance() {
2249 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002250 throw new IllegalStateException("No ConnectivityManager yet constructed");
2251 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002252 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002253 }
2254
2255 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002256 * Get the set of tetherable, available interfaces. This list is limited by
2257 * device configuration and current interface existence.
2258 *
2259 * @return an array of 0 or more Strings of tetherable interface names.
2260 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002261 * {@hide}
2262 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002263 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002264 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002265 public String[] getTetherableIfaces() {
2266 try {
2267 return mService.getTetherableIfaces();
2268 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002269 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002270 }
2271 }
2272
2273 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002274 * Get the set of tethered interfaces.
2275 *
2276 * @return an array of 0 or more String of currently tethered interface names.
2277 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002278 * {@hide}
2279 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002280 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002281 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002282 public String[] getTetheredIfaces() {
2283 try {
2284 return mService.getTetheredIfaces();
2285 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002286 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002287 }
2288 }
2289
2290 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002291 * Get the set of interface names which attempted to tether but
2292 * failed. Re-attempting to tether may cause them to reset to the Tethered
2293 * state. Alternatively, causing the interface to be destroyed and recreated
2294 * may cause them to reset to the available state.
2295 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2296 * information on the cause of the errors.
2297 *
2298 * @return an array of 0 or more String indicating the interface names
2299 * which failed to tether.
2300 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002301 * {@hide}
2302 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002303 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002304 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002305 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002306 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08002307 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002308 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002309 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002310 }
2311 }
2312
2313 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002314 * Get the set of tethered dhcp ranges.
2315 *
2316 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
2317 * {@hide}
2318 */
2319 public String[] getTetheredDhcpRanges() {
2320 try {
2321 return mService.getTetheredDhcpRanges();
2322 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002323 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002324 }
2325 }
2326
2327 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002328 * Attempt to tether the named interface. This will setup a dhcp server
2329 * on the interface, forward and NAT IP packets and forward DNS requests
2330 * to the best active upstream network interface. Note that if no upstream
2331 * IP network interface is available, dhcp will still run and traffic will be
2332 * allowed between the tethered devices and this device, though upstream net
2333 * access will of course fail until an upstream network interface becomes
2334 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002335 *
2336 * <p>This method requires the caller to hold either the
2337 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2338 * or the ability to modify system settings as determined by
2339 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002340 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002341 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2342 * and WifiStateMachine which need direct access. All other clients should use
2343 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2344 * logic.</p>
2345 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002346 * @param iface the interface name to tether.
2347 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2348 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002349 * {@hide}
2350 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002351 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002352 public int tether(String iface) {
2353 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002354 String pkgName = mContext.getOpPackageName();
2355 Log.i(TAG, "tether caller:" + pkgName);
2356 return mService.tether(iface, pkgName);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002357 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002358 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002359 }
2360 }
2361
2362 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002363 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002364 *
2365 * <p>This method requires the caller to hold either the
2366 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2367 * or the ability to modify system settings as determined by
2368 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002369 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002370 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2371 * and WifiStateMachine which need direct access. All other clients should use
2372 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2373 * logic.</p>
2374 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002375 * @param iface the interface name to untether.
2376 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2377 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002378 * {@hide}
2379 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002380 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002381 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002382 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002383 String pkgName = mContext.getOpPackageName();
2384 Log.i(TAG, "untether caller:" + pkgName);
2385 return mService.untether(iface, pkgName);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002386 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002387 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002388 }
2389 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002390
2391 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002392 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002393 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002394 * due to device configuration.
2395 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002396 * <p>If this app does not have permission to use this API, it will always
2397 * return false rather than throw an exception.</p>
2398 *
2399 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2400 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2401 *
2402 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2403 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2404 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002405 * @return a boolean - {@code true} indicating Tethering is supported.
2406 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002407 * {@hide}
2408 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002409 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002410 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2411 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002412 public boolean isTetheringSupported() {
Chalard Jean8f76fc32017-09-26 15:45:18 +09002413 String pkgName = mContext.getOpPackageName();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002414 try {
Udam Saini0e94c362017-06-07 12:06:28 -07002415 return mService.isTetheringSupported(pkgName);
Chalard Jean8f76fc32017-09-26 15:45:18 +09002416 } catch (SecurityException e) {
2417 // This API is not available to this caller, but for backward-compatibility
2418 // this will just return false instead of throwing.
2419 return false;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002420 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002421 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002422 }
2423 }
2424
2425 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002426 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2427 * @hide
2428 */
2429 @SystemApi
2430 public static abstract class OnStartTetheringCallback {
2431 /**
2432 * Called when tethering has been successfully started.
2433 */
Chalard Jean4d660112018-06-04 16:52:49 +09002434 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002435
2436 /**
2437 * Called when starting tethering failed.
2438 */
Chalard Jean4d660112018-06-04 16:52:49 +09002439 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002440 }
2441
2442 /**
2443 * Convenient overload for
2444 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2445 * handler to run on the current thread's {@link Looper}.
2446 * @hide
2447 */
2448 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07002449 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002450 public void startTethering(int type, boolean showProvisioningUi,
2451 final OnStartTetheringCallback callback) {
2452 startTethering(type, showProvisioningUi, callback, null);
2453 }
2454
2455 /**
2456 * Runs tether provisioning for the given type if needed and then starts tethering if
2457 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2458 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2459 * schedules tether provisioning re-checks if appropriate.
2460 *
2461 * @param type The type of tethering to start. Must be one of
2462 * {@link ConnectivityManager.TETHERING_WIFI},
2463 * {@link ConnectivityManager.TETHERING_USB}, or
2464 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2465 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2466 * is one. This should be true the first time this function is called and also any time
2467 * the user can see this UI. It gives users information from their carrier about the
2468 * check failing and how they can sign up for tethering if possible.
2469 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2470 * of the result of trying to tether.
2471 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2472 * @hide
2473 */
2474 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002475 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002476 public void startTethering(int type, boolean showProvisioningUi,
2477 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002478 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002479
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002480 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2481 @Override
2482 protected void onReceiveResult(int resultCode, Bundle resultData) {
2483 if (resultCode == TETHER_ERROR_NO_ERROR) {
2484 callback.onTetheringStarted();
2485 } else {
2486 callback.onTetheringFailed();
2487 }
2488 }
2489 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002490
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002491 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002492 String pkgName = mContext.getOpPackageName();
2493 Log.i(TAG, "startTethering caller:" + pkgName);
2494 mService.startTethering(type, wrappedCallback, showProvisioningUi, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002495 } catch (RemoteException e) {
2496 Log.e(TAG, "Exception trying to start tethering.", e);
2497 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2498 }
2499 }
2500
2501 /**
2502 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2503 * applicable.
2504 *
2505 * @param type The type of tethering to stop. Must be one of
2506 * {@link ConnectivityManager.TETHERING_WIFI},
2507 * {@link ConnectivityManager.TETHERING_USB}, or
2508 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2509 * @hide
2510 */
2511 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002512 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002513 public void stopTethering(int type) {
2514 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002515 String pkgName = mContext.getOpPackageName();
2516 Log.i(TAG, "stopTethering caller:" + pkgName);
2517 mService.stopTethering(type, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002518 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002519 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002520 }
2521 }
2522
2523 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002524 * Get the list of regular expressions that define any tetherable
2525 * USB network interfaces. If USB tethering is not supported by the
2526 * device, this list should be empty.
2527 *
2528 * @return an array of 0 or more regular expression Strings defining
2529 * what interfaces are considered tetherable usb interfaces.
2530 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002531 * {@hide}
2532 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002533 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002534 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002535 public String[] getTetherableUsbRegexs() {
2536 try {
2537 return mService.getTetherableUsbRegexs();
2538 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002539 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002540 }
2541 }
2542
2543 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002544 * Get the list of regular expressions that define any tetherable
2545 * Wifi network interfaces. If Wifi tethering is not supported by the
2546 * device, this list should be empty.
2547 *
2548 * @return an array of 0 or more regular expression Strings defining
2549 * what interfaces are considered tetherable wifi interfaces.
2550 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002551 * {@hide}
2552 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002553 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002554 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002555 public String[] getTetherableWifiRegexs() {
2556 try {
2557 return mService.getTetherableWifiRegexs();
2558 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002559 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002560 }
2561 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002562
Danica Chang6fdd0c62010-08-11 14:54:43 -07002563 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002564 * Get the list of regular expressions that define any tetherable
2565 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2566 * device, this list should be empty.
2567 *
2568 * @return an array of 0 or more regular expression Strings defining
2569 * what interfaces are considered tetherable bluetooth interfaces.
2570 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002571 * {@hide}
2572 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002573 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002574 @UnsupportedAppUsage
Danica Chang6fdd0c62010-08-11 14:54:43 -07002575 public String[] getTetherableBluetoothRegexs() {
2576 try {
2577 return mService.getTetherableBluetoothRegexs();
2578 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002579 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002580 }
2581 }
2582
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002583 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002584 * Attempt to both alter the mode of USB and Tethering of USB. A
2585 * utility method to deal with some of the complexity of USB - will
2586 * attempt to switch to Rndis and subsequently tether the resulting
2587 * interface on {@code true} or turn off tethering and switch off
2588 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002589 *
2590 * <p>This method requires the caller to hold either the
2591 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2592 * or the ability to modify system settings as determined by
2593 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002594 *
2595 * @param enable a boolean - {@code true} to enable tethering
2596 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2597 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002598 * {@hide}
2599 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002600 @UnsupportedAppUsage
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002601 public int setUsbTethering(boolean enable) {
2602 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002603 String pkgName = mContext.getOpPackageName();
2604 Log.i(TAG, "setUsbTethering caller:" + pkgName);
2605 return mService.setUsbTethering(enable, pkgName);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002606 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002607 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002608 }
2609 }
2610
Robert Greenwalt5a735062010-03-02 17:25:02 -08002611 /** {@hide} */
2612 public static final int TETHER_ERROR_NO_ERROR = 0;
2613 /** {@hide} */
2614 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2615 /** {@hide} */
2616 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2617 /** {@hide} */
2618 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2619 /** {@hide} */
2620 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2621 /** {@hide} */
2622 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2623 /** {@hide} */
2624 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2625 /** {@hide} */
2626 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2627 /** {@hide} */
2628 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2629 /** {@hide} */
2630 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2631 /** {@hide} */
2632 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002633 /** {@hide} */
2634 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +09002635 /** {@hide} */
2636 public static final int TETHER_ERROR_DHCPSERVER_ERROR = 12;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002637
2638 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002639 * Get a more detailed error code after a Tethering or Untethering
2640 * request asynchronously failed.
2641 *
2642 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002643 * @return error The error code of the last error tethering or untethering the named
2644 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002645 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002646 * {@hide}
2647 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002648 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002649 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002650 public int getLastTetherError(String iface) {
2651 try {
2652 return mService.getLastTetherError(iface);
2653 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002654 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002655 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002656 }
2657
2658 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002659 * Report network connectivity status. This is currently used only
2660 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002661 * <p>This method requires the caller to hold the permission
2662 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002663 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002664 * @param networkType The type of network you want to report on
2665 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002666 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002667 * {@hide}
2668 */
2669 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002670 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002671 try {
2672 mService.reportInetCondition(networkType, percentage);
2673 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002674 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002675 }
2676 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002677
2678 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002679 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002680 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002681 * the framework to re-evaluate network connectivity and/or switch to another
2682 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002683 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002684 * @param network The {@link Network} the application was attempting to use
2685 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002686 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2687 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002688 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002689 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002690 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002691 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002692 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002693 // One of these will be ignored because it matches system's current state.
2694 // The other will trigger the necessary reevaluation.
2695 mService.reportNetworkConnectivity(network, true);
2696 mService.reportNetworkConnectivity(network, false);
2697 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002698 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002699 }
2700 }
2701
2702 /**
2703 * Report to the framework whether a network has working connectivity.
2704 * This provides a hint to the system that a particular network is providing
2705 * working connectivity or not. In response the framework may re-evaluate
2706 * the network's connectivity and might take further action thereafter.
2707 *
2708 * @param network The {@link Network} the application was attempting to use
2709 * or {@code null} to indicate the current default network.
2710 * @param hasConnectivity {@code true} if the application was able to successfully access the
2711 * Internet using {@code network} or {@code false} if not.
2712 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002713 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002714 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002715 try {
2716 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002717 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002718 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002719 }
2720 }
2721
2722 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002723 * Set a network-independent global http proxy. This is not normally what you want
2724 * for typical HTTP proxies - they are general network dependent. However if you're
2725 * doing something unusual like general internal filtering this may be useful. On
2726 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002727 *
2728 * @param p A {@link ProxyInfo} object defining the new global
2729 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002730 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002731 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002732 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Jason Monk207900c2014-04-25 15:00:09 -04002733 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002734 try {
2735 mService.setGlobalProxy(p);
2736 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002737 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002738 }
2739 }
2740
2741 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002742 * Retrieve any network-independent global HTTP proxy.
2743 *
Jason Monk207900c2014-04-25 15:00:09 -04002744 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002745 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002746 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002747 */
Jason Monk207900c2014-04-25 15:00:09 -04002748 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002749 try {
2750 return mService.getGlobalProxy();
2751 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002752 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002753 }
2754 }
2755
2756 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002757 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2758 * network-specific HTTP proxy. If {@code network} is null, the
2759 * network-specific proxy returned is the proxy of the default active
2760 * network.
2761 *
2762 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2763 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2764 * or when {@code network} is {@code null},
2765 * the {@code ProxyInfo} for the default active network. Returns
2766 * {@code null} when no proxy applies or the caller doesn't have
2767 * permission to use {@code network}.
2768 * @hide
2769 */
2770 public ProxyInfo getProxyForNetwork(Network network) {
2771 try {
2772 return mService.getProxyForNetwork(network);
2773 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002774 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04002775 }
2776 }
2777
2778 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002779 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
2780 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04002781 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05002782 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002783 *
Jason Monk207900c2014-04-25 15:00:09 -04002784 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002785 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07002786 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002787 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05002788 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04002789 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07002790 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002791
2792 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002793 * Returns true if the hardware supports the given network type
2794 * else it returns false. This doesn't indicate we have coverage
2795 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002796 * hardware supports it. For example a GSM phone without a SIM
2797 * should still return {@code true} for mobile data, but a wifi only
2798 * tablet would return {@code false}.
2799 *
2800 * @param networkType The network type we'd like to check
2801 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002802 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002803 * @hide
2804 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002805 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002806 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002807 @UnsupportedAppUsage
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002808 public boolean isNetworkSupported(int networkType) {
2809 try {
2810 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002811 } catch (RemoteException e) {
2812 throw e.rethrowFromSystemServer();
2813 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002814 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002815
2816 /**
2817 * Returns if the currently active data network is metered. A network is
2818 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002819 * that connection due to monetary costs, data limitations or
2820 * battery/performance issues. You should check this before doing large
2821 * data transfers, and warn the user or delay the operation until another
2822 * network is available.
2823 *
2824 * @return {@code true} if large transfers should be avoided, otherwise
2825 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002826 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002827 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002828 public boolean isActiveNetworkMetered() {
2829 try {
2830 return mService.isActiveNetworkMetered();
2831 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002832 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002833 }
2834 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002835
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002836 /**
2837 * If the LockdownVpn mechanism is enabled, updates the vpn
2838 * with a reload of its profile.
2839 *
2840 * @return a boolean with {@code} indicating success
2841 *
2842 * <p>This method can only be called by the system UID
2843 * {@hide}
2844 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002845 public boolean updateLockdownVpn() {
2846 try {
2847 return mService.updateLockdownVpn();
2848 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002849 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002850 }
2851 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002852
2853 /**
Wink Saville948282b2013-08-29 08:55:16 -07002854 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07002855 *
Wink Savilleab9321d2013-06-29 21:10:57 -07002856 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07002857 *
2858 * @return time out that will be used, maybe less that suggestedTimeOutMs
2859 * -1 if an error.
2860 *
2861 * {@hide}
2862 */
Wink Saville948282b2013-08-29 08:55:16 -07002863 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07002864 int timeOutMs = -1;
2865 try {
Wink Saville948282b2013-08-29 08:55:16 -07002866 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07002867 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002868 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07002869 }
2870 return timeOutMs;
2871 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002872
2873 /**
Wink Saville42d4f082013-07-20 20:31:59 -07002874 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002875 * {@hide}
2876 */
2877 public String getMobileProvisioningUrl() {
2878 try {
2879 return mService.getMobileProvisioningUrl();
2880 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002881 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002882 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002883 }
Wink Saville42d4f082013-07-20 20:31:59 -07002884
2885 /**
Wink Saville948282b2013-08-29 08:55:16 -07002886 * Set sign in error notification to visible or in visible
2887 *
Wink Saville948282b2013-08-29 08:55:16 -07002888 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04002889 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07002890 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002891 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07002892 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04002893 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07002894 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04002895 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07002896 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002897 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07002898 }
2899 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002900
2901 /**
2902 * Set the value for enabling/disabling airplane mode
2903 *
2904 * @param enable whether to enable airplane mode or not
2905 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002906 * @hide
2907 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09002908 @RequiresPermission(anyOf = {
2909 android.Manifest.permission.NETWORK_SETTINGS,
2910 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2911 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09002912 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002913 public void setAirplaneMode(boolean enable) {
2914 try {
2915 mService.setAirplaneMode(enable);
2916 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002917 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002918 }
2919 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002920
2921 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002922 @UnsupportedAppUsage
Robert Greenwalta67be032014-05-16 15:49:14 -07002923 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07002924 try {
Robert Greenwalta67be032014-05-16 15:49:14 -07002925 mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002926 } catch (RemoteException e) {
2927 throw e.rethrowFromSystemServer();
2928 }
Robert Greenwalta67be032014-05-16 15:49:14 -07002929 }
2930
2931 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00002932 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Robert Greenwalta67be032014-05-16 15:49:14 -07002933 public void unregisterNetworkFactory(Messenger messenger) {
2934 try {
2935 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002936 } catch (RemoteException e) {
2937 throw e.rethrowFromSystemServer();
2938 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002939 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002940
Paul Jensen31a94f42015-02-13 14:18:39 -05002941 /**
2942 * @hide
2943 * Register a NetworkAgent with ConnectivityService.
2944 * @return NetID corresponding to NetworkAgent.
2945 */
2946 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002947 NetworkCapabilities nc, int score, NetworkMisc misc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002948 try {
Paul Jensen31a94f42015-02-13 14:18:39 -05002949 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc);
2950 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002951 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05002952 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002953 }
2954
Robert Greenwalt9258c642014-03-26 16:47:06 -07002955 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09002956 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
2957 * changes. Should be extended by applications wanting notifications.
2958 *
2959 * A {@code NetworkCallback} is registered by calling
2960 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2961 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09002962 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09002963 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
2964 * A {@code NetworkCallback} should be registered at most once at any time.
2965 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002966 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002967 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002968 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002969 * Called when the framework connects to a new network to evaluate whether it satisfies this
2970 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
2971 * callback. There is no guarantee that this new network will satisfy any requests, or that
2972 * the network will stay connected for longer than the time necessary to evaluate it.
2973 * <p>
2974 * Most applications <b>should not</b> act on this callback, and should instead use
2975 * {@link #onAvailable}. This callback is intended for use by applications that can assist
2976 * the framework in properly evaluating the network &mdash; for example, an application that
2977 * can automatically log in to a captive portal without user intervention.
2978 *
2979 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09002980 *
2981 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07002982 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002983 public void onPreCheck(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002984
2985 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002986 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07002987 * This callback may be called more than once if the {@link Network} that is
2988 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002989 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002990 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09002991 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
2992 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08002993 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09002994 * @hide
2995 */
2996 public void onAvailable(Network network, NetworkCapabilities networkCapabilities,
junyulai05986c62018-08-07 19:50:45 +08002997 LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09002998 // Internally only this method is called when a new network is available, and
2999 // it calls the callback in the same way and order that older versions used
3000 // to call so as not to change the behavior.
3001 onAvailable(network);
3002 if (!networkCapabilities.hasCapability(
3003 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3004 onNetworkSuspended(network);
3005 }
3006 onCapabilitiesChanged(network, networkCapabilities);
3007 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003008 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003009 }
3010
3011 /**
3012 * Called when the framework connects and has declared a new network ready for use.
3013 * This callback may be called more than once if the {@link Network} that is
3014 * satisfying the request changes. This will always immediately be followed by a
3015 * call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} then by a
junyulai05986c62018-08-07 19:50:45 +08003016 * call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call to
3017 * {@link #onBlockedStatusChanged(Network, boolean)}.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003018 *
3019 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003020 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003021 public void onAvailable(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003022
3023 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003024 * Called when the network is about to be disconnected. Often paired with an
Robert Greenwalt6078b502014-06-11 16:05:07 -07003025 * {@link NetworkCallback#onAvailable} call with the new replacement network
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003026 * for graceful handover. This may not be called if we have a hard loss
3027 * (loss without warning). This may be followed by either a
Robert Greenwalt6078b502014-06-11 16:05:07 -07003028 * {@link NetworkCallback#onLost} call or a
3029 * {@link NetworkCallback#onAvailable} call for this network depending
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003030 * on whether we lose or regain it.
3031 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003032 * @param network The {@link Network} that is about to be disconnected.
3033 * @param maxMsToLive The time in ms the framework will attempt to keep the
3034 * network connected. Note that the network may suffer a
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003035 * hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003036 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003037 public void onLosing(Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003038
3039 /**
3040 * Called when the framework has a hard loss of the network or when the
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003041 * graceful failure ends.
3042 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003043 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003044 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003045 public void onLost(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003046
3047 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003048 * Called if no network is found in the timeout time specified in
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003049 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call. This callback is not
Etan Cohenaebf17e2017-03-01 12:47:28 -08003050 * called for the version of {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3051 * without timeout. When this callback is invoked the associated
3052 * {@link NetworkRequest} will have already been removed and released, as if
3053 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003054 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003055 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003056
3057 /**
3058 * Called when the network the framework connected to for this request
3059 * changes capabilities but still satisfies the stated need.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003060 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003061 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003062 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3063 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003064 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003065 public void onCapabilitiesChanged(Network network,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003066 NetworkCapabilities networkCapabilities) {}
3067
3068 /**
3069 * Called when the network the framework connected to for this request
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003070 * changes {@link LinkProperties}.
3071 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003072 * @param network The {@link Network} whose link properties have changed.
3073 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003074 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003075 public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003076
Robert Greenwalt8d482522015-06-24 13:23:42 -07003077 /**
3078 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003079 * goes into {@link NetworkInfo.State#SUSPENDED}.
Robert Greenwalt8d482522015-06-24 13:23:42 -07003080 * This generally means that while the TCP connections are still live,
3081 * temporarily network data fails to transfer. Specifically this is used
3082 * on cellular networks to mask temporary outages when driving through
3083 * a tunnel, etc.
3084 * @hide
3085 */
3086 public void onNetworkSuspended(Network network) {}
3087
3088 /**
3089 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003090 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3091 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Robert Greenwalt8d482522015-06-24 13:23:42 -07003092 * @hide
3093 */
3094 public void onNetworkResumed(Network network) {}
3095
junyulai05986c62018-08-07 19:50:45 +08003096 /**
3097 * Called when access to the specified network is blocked or unblocked.
3098 *
3099 * @param network The {@link Network} whose blocked status has changed.
3100 * @param blocked The blocked status of this {@link Network}.
3101 */
3102 public void onBlockedStatusChanged(Network network, boolean blocked) {}
3103
Robert Greenwalt6078b502014-06-11 16:05:07 -07003104 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003105 }
3106
Hugo Benichicb883232017-05-11 13:16:17 +09003107 /**
3108 * Constant error codes used by ConnectivityService to communicate about failures and errors
3109 * across a Binder boundary.
3110 * @hide
3111 */
3112 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003113 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003114 }
3115
3116 /** @hide */
3117 public static class TooManyRequestsException extends RuntimeException {}
3118
3119 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3120 switch (e.errorCode) {
3121 case Errors.TOO_MANY_REQUESTS:
3122 return new TooManyRequestsException();
3123 default:
3124 Log.w(TAG, "Unknown service error code " + e.errorCode);
3125 return new RuntimeException(e);
3126 }
3127 }
3128
Robert Greenwalt9258c642014-03-26 16:47:06 -07003129 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003130 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003131 public static final int CALLBACK_PRECHECK = BASE + 1;
3132 /** @hide */
3133 public static final int CALLBACK_AVAILABLE = BASE + 2;
3134 /** @hide arg1 = TTL */
3135 public static final int CALLBACK_LOSING = BASE + 3;
3136 /** @hide */
3137 public static final int CALLBACK_LOST = BASE + 4;
3138 /** @hide */
3139 public static final int CALLBACK_UNAVAIL = BASE + 5;
3140 /** @hide */
3141 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3142 /** @hide */
3143 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003144 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003145 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003146 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003147 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003148 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003149 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003150 /** @hide */
3151 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003152
Erik Kline57faba92015-11-25 12:49:38 +09003153 /** @hide */
3154 public static String getCallbackName(int whichCallback) {
3155 switch (whichCallback) {
3156 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3157 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3158 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3159 case CALLBACK_LOST: return "CALLBACK_LOST";
3160 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3161 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3162 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003163 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3164 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3165 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003166 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003167 default:
3168 return Integer.toString(whichCallback);
3169 }
3170 }
3171
Robert Greenwalt562cc542014-05-15 18:07:26 -07003172 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003173 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003174 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003175
Hugo Benichid42650f2016-07-06 22:53:17 +09003176 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003177 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003178 }
3179
Hugo Benichi2583ef02017-02-02 17:02:36 +09003180 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003181 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003182 }
3183
Robert Greenwalt9258c642014-03-26 16:47:06 -07003184 @Override
3185 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003186 if (message.what == EXPIRE_LEGACY_REQUEST) {
3187 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3188 return;
3189 }
3190
3191 final NetworkRequest request = getObject(message, NetworkRequest.class);
3192 final Network network = getObject(message, Network.class);
3193 final NetworkCallback callback;
3194 synchronized (sCallbacks) {
3195 callback = sCallbacks.get(request);
3196 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003197 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003198 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003199 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003200 if (callback == null) {
3201 Log.w(TAG, "callback not found for " + getCallbackName(message.what) + " message");
3202 return;
3203 }
3204
Robert Greenwalt9258c642014-03-26 16:47:06 -07003205 switch (message.what) {
3206 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003207 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003208 break;
3209 }
3210 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003211 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3212 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003213 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003214 break;
3215 }
3216 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003217 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003218 break;
3219 }
3220 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003221 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003222 break;
3223 }
3224 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003225 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003226 break;
3227 }
3228 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003229 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3230 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003231 break;
3232 }
3233 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003234 LinkProperties lp = getObject(message, LinkProperties.class);
3235 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003236 break;
3237 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003238 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003239 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003240 break;
3241 }
3242 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003243 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003244 break;
3245 }
junyulai05986c62018-08-07 19:50:45 +08003246 case CALLBACK_BLK_CHANGED: {
3247 boolean blocked = message.arg1 != 0;
3248 callback.onBlockedStatusChanged(network, blocked);
3249 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003250 }
3251 }
3252
Hugo Benichid42650f2016-07-06 22:53:17 +09003253 private <T> T getObject(Message msg, Class<T> c) {
3254 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003255 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003256 }
3257
Hugo Benichi2583ef02017-02-02 17:02:36 +09003258 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003259 synchronized (sCallbacks) {
3260 if (sCallbackHandler == null) {
3261 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003262 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003263 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003264 }
3265 }
3266
Hugo Benichi6f260f32017-02-03 14:18:44 +09003267 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3268 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003269
Hugo Benichi6f260f32017-02-03 14:18:44 +09003270 private static final int LISTEN = 1;
3271 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003272
Hugo Benichi6f260f32017-02-03 14:18:44 +09003273 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3274 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003275 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003276 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003277 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003278 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003279 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003280 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003281 if (callback.networkRequest != null
3282 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003283 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3284 // and requests (http://b/20701525).
3285 Log.e(TAG, "NetworkCallback was already registered");
3286 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003287 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003288 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003289 if (action == LISTEN) {
Hugo Benichid42650f2016-07-06 22:53:17 +09003290 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04003291 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003292 request = mService.requestNetwork(
3293 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04003294 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003295 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003296 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003297 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003298 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003299 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003300 } catch (RemoteException e) {
3301 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003302 } catch (ServiceSpecificException e) {
3303 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003304 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003305 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003306 }
3307
3308 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003309 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003310 *
3311 * This is temporarily public @hide so it can be called by system code that uses the
3312 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
3313 * instead network notifications.
3314 *
3315 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
3316 *
3317 * @hide
3318 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003319 public void requestNetwork(@NonNull NetworkRequest request,
3320 @NonNull NetworkCallback networkCallback, int timeoutMs, int legacyType,
3321 @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003322 CallbackHandler cbHandler = new CallbackHandler(handler);
3323 NetworkCapabilities nc = request.networkCapabilities;
3324 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003325 }
3326
3327 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003328 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003329 *
3330 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003331 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3332 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003333 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003334 * Status of the request can be followed by listening to the various
Robert Greenwalt6078b502014-06-11 16:05:07 -07003335 * callbacks described in {@link NetworkCallback}. The {@link Network}
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003336 * can be used to direct traffic to the network.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003337 * <p>It is presently unsupported to request a network with mutable
3338 * {@link NetworkCapabilities} such as
3339 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3340 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3341 * as these {@code NetworkCapabilities} represent states that a particular
3342 * network may never attain, and whether a network will attain these states
3343 * is unknown prior to bringing up the network so the framework does not
3344 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003345 *
3346 * <p>This method requires the caller to hold either the
3347 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3348 * or the ability to modify system settings as determined by
3349 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003350 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003351 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003352 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3353 * the callback must not be shared - it uniquely specifies this request.
3354 * The callback is invoked on the default internal Handler.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003355 * @throws IllegalArgumentException if {@code request} specifies any mutable
3356 * {@code NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003357 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003358 public void requestNetwork(@NonNull NetworkRequest request,
3359 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003360 requestNetwork(request, networkCallback, getDefaultHandler());
3361 }
3362
3363 /**
3364 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3365 *
3366 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003367 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3368 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003369 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003370 * Status of the request can be followed by listening to the various
3371 * callbacks described in {@link NetworkCallback}. The {@link Network}
3372 * can be used to direct traffic to the network.
3373 * <p>It is presently unsupported to request a network with mutable
3374 * {@link NetworkCapabilities} such as
3375 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3376 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3377 * as these {@code NetworkCapabilities} represent states that a particular
3378 * network may never attain, and whether a network will attain these states
3379 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003380 * know how to go about satisfying a request with these capabilities.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003381 *
3382 * <p>This method requires the caller to hold either the
3383 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3384 * or the ability to modify system settings as determined by
3385 * {@link android.provider.Settings.System#canWrite}.</p>
3386 *
3387 * @param request {@link NetworkRequest} describing this request.
3388 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3389 * the callback must not be shared - it uniquely specifies this request.
3390 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3391 * @throws IllegalArgumentException if {@code request} specifies any mutable
3392 * {@code NetworkCapabilities}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003393 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003394 public void requestNetwork(@NonNull NetworkRequest request,
3395 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003396 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3397 CallbackHandler cbHandler = new CallbackHandler(handler);
3398 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003399 }
3400
3401 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003402 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3403 * by a timeout.
3404 *
3405 * This function behaves identically to the non-timed-out version
3406 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3407 * is not found within the given time (in milliseconds) the
3408 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3409 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3410 * not have to be released if timed-out (it is automatically released). Unregistering a
3411 * request that timed out is not an error.
3412 *
3413 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3414 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3415 * for that purpose. Calling this method will attempt to bring up the requested network.
3416 *
3417 * <p>This method requires the caller to hold either the
3418 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3419 * or the ability to modify system settings as determined by
3420 * {@link android.provider.Settings.System#canWrite}.</p>
3421 *
3422 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003423 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3424 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003425 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3426 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3427 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003428 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003429 public void requestNetwork(@NonNull NetworkRequest request,
3430 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003431 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003432 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003433 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003434 }
3435
Hugo Benichi2583ef02017-02-02 17:02:36 +09003436 /**
3437 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3438 * by a timeout.
3439 *
Chalard Jean4d660112018-06-04 16:52:49 +09003440 * This function behaves identically to the version without timeout, but if a suitable
Hugo Benichi2583ef02017-02-02 17:02:36 +09003441 * network is not found within the given time (in milliseconds) the
Etan Cohenaebf17e2017-03-01 12:47:28 -08003442 * {@link NetworkCallback#onUnavailable} callback is called. The request can still be
3443 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3444 * not have to be released if timed-out (it is automatically released). Unregistering a
3445 * request that timed out is not an error.
3446 *
3447 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3448 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3449 * for that purpose. Calling this method will attempt to bring up the requested network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003450 *
3451 * <p>This method requires the caller to hold either the
3452 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3453 * or the ability to modify system settings as determined by
3454 * {@link android.provider.Settings.System#canWrite}.</p>
3455 *
3456 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003457 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3458 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003459 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003460 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3461 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003462 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003463 public void requestNetwork(@NonNull NetworkRequest request,
3464 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003465 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003466 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3467 CallbackHandler cbHandler = new CallbackHandler(handler);
3468 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003469 }
3470
3471 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003472 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003473 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003474 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003475 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003476 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3477 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003478 */
Erik Kline90e93072014-11-19 12:12:24 +09003479 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003480
3481 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003482 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003483 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003484 * {@link android.content.Intent#getParcelableExtra(String)}.
3485 */
Erik Kline90e93072014-11-19 12:12:24 +09003486 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003487
3488
3489 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003490 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003491 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003492 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003493 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003494 * the request may outlive the calling application and get called back when a suitable
3495 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003496 * <p>
3497 * The operation is an Intent broadcast that goes to a broadcast receiver that
3498 * you registered with {@link Context#registerReceiver} or through the
3499 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3500 * <p>
3501 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003502 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3503 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003504 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003505 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003506 * Intent to reserve the network or it will be released shortly after the Intent
3507 * is processed.
3508 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003509 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003510 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003511 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003512 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003513 * The request may be released normally by calling
3514 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003515 * <p>It is presently unsupported to request a network with either
3516 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3517 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3518 * as these {@code NetworkCapabilities} represent states that a particular
3519 * network may never attain, and whether a network will attain these states
3520 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003521 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003522 *
3523 * <p>This method requires the caller to hold either the
3524 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3525 * or the ability to modify system settings as determined by
3526 * {@link android.provider.Settings.System#canWrite}.</p>
3527 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003528 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003529 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003530 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003531 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003532 * @throws IllegalArgumentException if {@code request} contains either
3533 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3534 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003535 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003536 public void requestNetwork(@NonNull NetworkRequest request,
3537 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003538 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003539 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003540 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003541 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003542 } catch (RemoteException e) {
3543 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003544 } catch (ServiceSpecificException e) {
3545 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003546 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003547 }
3548
3549 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003550 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3551 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003552 * This method has the same behavior as
3553 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003554 * releasing network resources and disconnecting.
3555 *
3556 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3557 * PendingIntent passed to
3558 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3559 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3560 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003561 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003562 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003563 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003564 try {
3565 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003566 } catch (RemoteException e) {
3567 throw e.rethrowFromSystemServer();
3568 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003569 }
3570
Hugo Benichie7678512017-05-09 15:19:01 +09003571 private static void checkPendingIntentNotNull(PendingIntent intent) {
3572 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3573 }
3574
3575 private static void checkCallbackNotNull(NetworkCallback callback) {
3576 Preconditions.checkNotNull(callback, "null NetworkCallback");
3577 }
3578
3579 private static void checkTimeout(int timeoutMs) {
3580 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003581 }
3582
3583 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003584 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003585 * {@link NetworkRequest}. The callbacks will continue to be called until
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003586 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003587 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003588 * @param request {@link NetworkRequest} describing this request.
3589 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3590 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003591 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003592 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003593 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003594 public void registerNetworkCallback(@NonNull NetworkRequest request,
3595 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003596 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3597 }
3598
3599 /**
3600 * Registers to receive notifications about all networks which satisfy the given
3601 * {@link NetworkRequest}. The callbacks will continue to be called until
3602 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003603 *
3604 * @param request {@link NetworkRequest} describing this request.
3605 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3606 * networks change state.
3607 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003608 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003609 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003610 public void registerNetworkCallback(@NonNull NetworkRequest request,
3611 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003612 CallbackHandler cbHandler = new CallbackHandler(handler);
3613 NetworkCapabilities nc = request.networkCapabilities;
3614 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003615 }
3616
3617 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003618 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3619 * {@link NetworkRequest}.
3620 *
3621 * This function behaves identically to the version that takes a NetworkCallback, but instead
3622 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3623 * the request may outlive the calling application and get called back when a suitable
3624 * network is found.
3625 * <p>
3626 * The operation is an Intent broadcast that goes to a broadcast receiver that
3627 * you registered with {@link Context#registerReceiver} or through the
3628 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3629 * <p>
3630 * The operation Intent is delivered with two extras, a {@link Network} typed
3631 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3632 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3633 * the original requests parameters.
3634 * <p>
3635 * If there is already a request for this Intent registered (with the equality of
3636 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3637 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3638 * <p>
3639 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003640 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003641 * @param request {@link NetworkRequest} describing this request.
3642 * @param operation Action to perform when the network is available (corresponds
3643 * to the {@link NetworkCallback#onAvailable} call. Typically
3644 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3645 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003646 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003647 public void registerNetworkCallback(@NonNull NetworkRequest request,
3648 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003649 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003650 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04003651 try {
3652 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003653 } catch (RemoteException e) {
3654 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003655 } catch (ServiceSpecificException e) {
3656 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003657 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003658 }
3659
3660 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003661 * Registers to receive notifications about changes in the system default network. The callbacks
3662 * will continue to be called until either the application exits or
3663 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09003664 *
3665 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3666 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003667 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09003668 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003669 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003670 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003671 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
3672 }
3673
3674 /**
3675 * Registers to receive notifications about changes in the system default network. The callbacks
3676 * will continue to be called until either the application exits or
3677 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003678 *
3679 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3680 * system default network changes.
3681 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003682 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003683 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003684 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
3685 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09003686 // This works because if the NetworkCapabilities are null,
3687 // ConnectivityService takes them from the default request.
3688 //
3689 // Since the capabilities are exactly the same as the default request's
3690 // capabilities, this request is guaranteed, at all times, to be
3691 // satisfied by the same network, if any, that satisfies the default
3692 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003693 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09003694 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
3695 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09003696 }
3697
3698 /**
fengludb571472015-04-21 17:12:05 -07003699 * Requests bandwidth update for a given {@link Network} and returns whether the update request
3700 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
3701 * network connection for updated bandwidth information. The caller will be notified via
3702 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003703 * method assumes that the caller has previously called
3704 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
3705 * changes.
fenglub15e72b2015-03-20 11:29:56 -07003706 *
fengluae519192015-04-27 14:28:04 -07003707 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07003708 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07003709 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003710 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003711 try {
fengludb571472015-04-21 17:12:05 -07003712 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07003713 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003714 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07003715 }
3716 }
3717
3718 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003719 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003720 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
3721 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
3722 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09003723 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
3724 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003725 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09003726 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
3727 * triggering it as soon as this call returns.
3728 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003729 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003730 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003731 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003732 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003733 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003734 final List<NetworkRequest> reqs = new ArrayList<>();
3735 // Find all requests associated to this callback and stop callback triggers immediately.
3736 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
3737 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003738 Preconditions.checkArgument(networkCallback.networkRequest != null,
3739 "NetworkCallback was not registered");
3740 Preconditions.checkArgument(networkCallback.networkRequest != ALREADY_UNREGISTERED,
3741 "NetworkCallback was already unregistered");
Hugo Benichidafed3d2017-03-06 09:17:06 +09003742 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
3743 if (e.getValue() == networkCallback) {
3744 reqs.add(e.getKey());
3745 }
3746 }
3747 // TODO: throw exception if callback was registered more than once (http://b/20701525).
3748 for (NetworkRequest r : reqs) {
3749 try {
3750 mService.releaseNetworkRequest(r);
3751 } catch (RemoteException e) {
3752 throw e.rethrowFromSystemServer();
3753 }
3754 // Only remove mapping if rpc was successful.
3755 sCallbacks.remove(r);
3756 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09003757 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003758 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003759 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003760
3761 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003762 * Unregisters a callback previously registered via
3763 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3764 *
3765 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3766 * PendingIntent passed to
3767 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3768 * Cannot be null.
3769 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003770 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003771 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003772 releaseNetworkRequest(operation);
3773 }
3774
3775 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003776 * Informs the system whether it should switch to {@code network} regardless of whether it is
3777 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
3778 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
3779 * the system default network regardless of any other network that's currently connected. If
3780 * {@code always} is true, then the choice is remembered, so that the next time the user
3781 * connects to this network, the system will switch to it.
3782 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003783 * @param network The network to accept.
3784 * @param accept Whether to accept the network even if unvalidated.
3785 * @param always Whether to remember this choice in the future.
3786 *
3787 * @hide
3788 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003789 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003790 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3791 try {
3792 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003793 } catch (RemoteException e) {
3794 throw e.rethrowFromSystemServer();
3795 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003796 }
3797
3798 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003799 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
3800 * only meaningful if the system is configured not to penalize such networks, e.g., if the
3801 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
3802 * NETWORK_AVOID_BAD_WIFI setting is unset}.
3803 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003804 * @param network The network to accept.
3805 *
3806 * @hide
3807 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003808 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003809 public void setAvoidUnvalidated(Network network) {
3810 try {
3811 mService.setAvoidUnvalidated(network);
3812 } catch (RemoteException e) {
3813 throw e.rethrowFromSystemServer();
3814 }
3815 }
3816
3817 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003818 * Requests that the system open the captive portal app on the specified network.
3819 *
3820 * @param network The network to log into.
3821 *
3822 * @hide
3823 */
3824 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
3825 public void startCaptivePortalApp(Network network) {
3826 try {
3827 mService.startCaptivePortalApp(network);
3828 } catch (RemoteException e) {
3829 throw e.rethrowFromSystemServer();
3830 }
3831 }
3832
3833 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003834 * Determine whether the device is configured to avoid bad wifi.
3835 * @hide
3836 */
3837 @SystemApi
3838 public boolean getAvoidBadWifi() {
3839 try {
3840 return mService.getAvoidBadWifi();
3841 } catch (RemoteException e) {
3842 throw e.rethrowFromSystemServer();
3843 }
3844 }
3845
3846 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003847 * It is acceptable to briefly use multipath data to provide seamless connectivity for
3848 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003849 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
3850 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003851 *
3852 * An example of such an operation might be a time-sensitive foreground activity, such as a
3853 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
3854 */
3855 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
3856
3857 /**
3858 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
3859 * a backup channel for traffic that is primarily going over another network.
3860 *
3861 * An example might be maintaining backup connections to peers or servers for the purpose of
3862 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
3863 * on backup paths should be negligible compared to the traffic on the main path.
3864 */
3865 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
3866
3867 /**
3868 * It is acceptable to use metered data to improve network latency and performance.
3869 */
3870 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
3871
3872 /**
3873 * Return value to use for unmetered networks. On such networks we currently set all the flags
3874 * to true.
3875 * @hide
3876 */
3877 public static final int MULTIPATH_PREFERENCE_UNMETERED =
3878 MULTIPATH_PREFERENCE_HANDOVER |
3879 MULTIPATH_PREFERENCE_RELIABILITY |
3880 MULTIPATH_PREFERENCE_PERFORMANCE;
3881
3882 /** @hide */
3883 @Retention(RetentionPolicy.SOURCE)
3884 @IntDef(flag = true, value = {
3885 MULTIPATH_PREFERENCE_HANDOVER,
3886 MULTIPATH_PREFERENCE_RELIABILITY,
3887 MULTIPATH_PREFERENCE_PERFORMANCE,
3888 })
3889 public @interface MultipathPreference {
3890 }
3891
3892 /**
3893 * Provides a hint to the calling application on whether it is desirable to use the
3894 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
3895 * for multipath data transfer on this network when it is not the system default network.
3896 * Applications desiring to use multipath network protocols should call this method before
3897 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003898 *
3899 * @param network The network on which the application desires to use multipath data.
3900 * If {@code null}, this method will return the a preference that will generally
3901 * apply to metered networks.
3902 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
3903 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003904 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003905 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003906 try {
3907 return mService.getMultipathPreference(network);
3908 } catch (RemoteException e) {
3909 throw e.rethrowFromSystemServer();
3910 }
3911 }
3912
3913 /**
Stuart Scott984dc852015-03-30 13:17:11 -07003914 * Resets all connectivity manager settings back to factory defaults.
3915 * @hide
3916 */
3917 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07003918 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07003919 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07003920 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003921 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07003922 }
3923 }
3924
3925 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003926 * Binds the current process to {@code network}. All Sockets created in the future
3927 * (and not explicitly bound via a bound SocketFactory from
3928 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3929 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3930 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3931 * work and all host name resolutions will fail. This is by design so an application doesn't
3932 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3933 * To clear binding pass {@code null} for {@code network}. Using individually bound
3934 * Sockets created by Network.getSocketFactory().createSocket() and
3935 * performing network-specific host name resolutions via
3936 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04003937 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003938 *
3939 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3940 * the current binding.
3941 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3942 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003943 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09003944 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04003945 // instantiated.
3946 return setProcessDefaultNetwork(network);
3947 }
3948
3949 /**
3950 * Binds the current process to {@code network}. All Sockets created in the future
3951 * (and not explicitly bound via a bound SocketFactory from
3952 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3953 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3954 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3955 * work and all host name resolutions will fail. This is by design so an application doesn't
3956 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3957 * To clear binding pass {@code null} for {@code network}. Using individually bound
3958 * Sockets created by Network.getSocketFactory().createSocket() and
3959 * performing network-specific host name resolutions via
3960 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
3961 * {@code setProcessDefaultNetwork}.
3962 *
3963 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3964 * the current binding.
3965 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3966 * @deprecated This function can throw {@link IllegalStateException}. Use
3967 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
3968 * is a direct replacement.
3969 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003970 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09003971 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003972 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09003973 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
3974
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09003975 if (netId != NETID_UNSET) {
3976 netId = network.getNetIdForResolv();
3977 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09003978
3979 if (!NetworkUtils.bindProcessToNetwork(netId)) {
3980 return false;
3981 }
3982
3983 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05003984 // Set HTTP proxy system properties to match network.
3985 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09003986 try {
3987 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
3988 } catch (SecurityException e) {
3989 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
3990 Log.e(TAG, "Can't set proxy properties", e);
3991 }
Paul Jensenc91b5342014-08-27 12:38:45 -04003992 // Must flush DNS cache as new network may have different DNS resolutions.
3993 InetAddress.clearDnsCache();
3994 // Must flush socket pool as idle sockets will be bound to previous network and may
3995 // cause subsequent fetches to be performed on old network.
3996 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04003997 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09003998
3999 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004000 }
4001
4002 /**
4003 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004004 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004005 *
4006 * @return {@code Network} to which this process is bound, or {@code null}.
4007 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004008 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004009 public Network getBoundNetworkForProcess() {
4010 // Forcing callers to call thru non-static function ensures ConnectivityManager
4011 // instantiated.
4012 return getProcessDefaultNetwork();
4013 }
4014
4015 /**
4016 * Returns the {@link Network} currently bound to this process via
4017 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4018 *
4019 * @return {@code Network} to which this process is bound, or {@code null}.
4020 * @deprecated Using this function can lead to other functions throwing
4021 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4022 * {@code getBoundNetworkForProcess} is a direct replacement.
4023 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004024 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004025 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004026 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004027 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004028 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004029 return new Network(netId);
4030 }
4031
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004032 private void unsupportedStartingFrom(int version) {
4033 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004034 // The getApplicationInfo() call we make below is not supported in system context. Let
4035 // the call through here, and rely on the fact that ConnectivityService will refuse to
4036 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004037 return;
4038 }
4039
4040 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4041 throw new UnsupportedOperationException(
4042 "This method is not supported in target SDK version " + version + " and above");
4043 }
4044 }
4045
4046 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4047 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004048 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004049 // remove these exemptions. Note that this check is not secure, and apps can still access these
4050 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4051 // so is unsupported and may break in the future. http://b/22728205
4052 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004053 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004054 }
4055
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004056 /**
4057 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004058 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004059 *
4060 * @param network The {@link Network} to bind host resolutions from the current process to, or
4061 * {@code null} to clear the current binding.
4062 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4063 * @hide
4064 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4065 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004066 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004067 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004068 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004069 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004070 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004071 }
Felipe Leme1b103232016-01-22 09:44:57 -08004072
4073 /**
4074 * Device is not restricting metered network activity while application is running on
4075 * background.
4076 */
4077 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4078
4079 /**
4080 * Device is restricting metered network activity while application is running on background,
4081 * but application is allowed to bypass it.
4082 * <p>
4083 * In this state, application should take action to mitigate metered network access.
4084 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4085 */
4086 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4087
4088 /**
4089 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004090 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004091 * In this state, application should not try to use the network while running on background,
4092 * because it would be denied.
4093 */
4094 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4095
Felipe Leme9778f762016-01-27 14:46:39 -08004096 /**
4097 * A change in the background metered network activity restriction has occurred.
4098 * <p>
4099 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4100 * applies to them.
4101 * <p>
4102 * This is only sent to registered receivers, not manifest receivers.
4103 */
4104 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4105 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4106 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4107
Felipe Lemeecfccea2016-01-25 11:48:04 -08004108 /** @hide */
4109 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004110 @IntDef(flag = false, value = {
4111 RESTRICT_BACKGROUND_STATUS_DISABLED,
4112 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4113 RESTRICT_BACKGROUND_STATUS_ENABLED,
4114 })
Felipe Leme1b103232016-01-22 09:44:57 -08004115 public @interface RestrictBackgroundStatus {
4116 }
4117
4118 private INetworkPolicyManager getNetworkPolicyManager() {
4119 synchronized (this) {
4120 if (mNPManager != null) {
4121 return mNPManager;
4122 }
4123 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4124 .getService(Context.NETWORK_POLICY_SERVICE));
4125 return mNPManager;
4126 }
4127 }
4128
4129 /**
4130 * Determines if the calling application is subject to metered network restrictions while
4131 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004132 *
4133 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4134 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4135 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004136 */
4137 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4138 try {
4139 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4140 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004141 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004142 }
4143 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004144
4145 /**
4146 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004147 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4148 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004149 *
4150 * @return Hash of network watchlist config file. Null if config does not exist.
4151 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004152 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004153 public byte[] getNetworkWatchlistConfigHash() {
4154 try {
4155 return mService.getNetworkWatchlistConfigHash();
4156 } catch (RemoteException e) {
4157 Log.e(TAG, "Unable to get watchlist config hash");
4158 throw e.rethrowFromSystemServer();
4159 }
4160 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004161
4162 /**
4163 * Returns the {@code uid} of the owner of a network connection.
4164 *
4165 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and
4166 * {@code IPPROTO_UDP} currently supported.
4167 * @param local The local {@link InetSocketAddress} of a connection.
4168 * @param remote The remote {@link InetSocketAddress} of a connection.
4169 *
4170 * @return {@code uid} if the connection is found and the app has permission to observe it
4171 * (e.g., if it is associated with the calling VPN app's tunnel) or
4172 * {@link android.os.Process#INVALID_UID} if the connection is not found.
4173 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004174 public int getConnectionOwnerUid(int protocol, @NonNull InetSocketAddress local,
4175 @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004176 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4177 try {
4178 return mService.getConnectionOwnerUid(connectionInfo);
4179 } catch (RemoteException e) {
4180 throw e.rethrowFromSystemServer();
4181 }
4182 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004183
4184 private void printStackTrace() {
4185 if (DEBUG) {
4186 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4187 final StringBuffer sb = new StringBuffer();
4188 for (int i = 3; i < callStack.length; i++) {
4189 final String stackTrace = callStack[i].toString();
4190 if (stackTrace == null || stackTrace.contains("android.os")) {
4191 break;
4192 }
4193 sb.append(" [").append(stackTrace).append("]");
4194 }
4195 Log.d(TAG, "StackLog:" + sb.toString());
4196 }
4197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198}