blob: 2a323e5ec97db5d8bf676b9fec4c263dee06a575 [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;
Robert Greenwalt9258c642014-03-26 16:47:06 -070030import android.app.PendingIntent;
Artur Satayev26958002019-12-10 17:47:52 +000031import android.compat.annotation.UnsupportedAppUsage;
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;
markchiene8b9d752020-01-20 19:31:56 +080036import android.net.TetheringManager.StartTetheringCallback;
markchien40898ca2020-01-21 13:11:06 +080037import android.net.TetheringManager.TetheringEventCallback;
markchiene8b9d752020-01-20 19:31:56 +080038import android.net.TetheringManager.TetheringRequest;
Robert Greenwalt42acef32009-08-12 16:08:25 -070039import android.os.Binder;
Mathew Inwood55418ea2018-12-20 15:30:45 +000040import android.os.Build;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070041import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080042import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070043import android.os.Handler;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080044import android.os.IBinder;
45import android.os.INetworkActivityListener;
46import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070047import android.os.Looper;
48import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070049import android.os.Messenger;
junyulai0c666972019-03-04 22:45:36 +080050import android.os.ParcelFileDescriptor;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090051import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080053import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080054import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090055import android.os.ServiceSpecificException;
Jeff Sharkey961e3042011-08-29 16:02:57 -070056import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080057import android.telephony.SubscriptionManager;
Meng Wanga73bed82019-11-18 17:10:00 -080058import android.telephony.TelephonyManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080059import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070060import android.util.Log;
Erik Kline35bf06c2017-01-26 18:08:28 +090061import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062
markchien40898ca2020-01-21 13:11:06 +080063import com.android.internal.annotations.GuardedBy;
Hugo Benichidafed3d2017-03-06 09:17:06 +090064import com.android.internal.util.Preconditions;
65import com.android.internal.util.Protocol;
Robert Greenwaltafa05c02014-05-21 20:04:36 -070066
Paul Jensenc91b5342014-08-27 12:38:45 -040067import libcore.net.event.NetworkEventDispatcher;
68
junyulai215b8772019-01-15 11:32:44 +080069import java.io.FileDescriptor;
junyulai0c666972019-03-04 22:45:36 +080070import java.io.IOException;
71import java.io.UncheckedIOException;
Felipe Leme1b103232016-01-22 09:44:57 -080072import java.lang.annotation.Retention;
73import java.lang.annotation.RetentionPolicy;
Jeremy Kleind42209d2015-12-28 15:11:58 -080074import java.net.InetAddress;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070075import java.net.InetSocketAddress;
junyulai352dc2f2019-01-08 20:04:33 +080076import java.net.Socket;
Hugo Benichidafed3d2017-03-06 09:17:06 +090077import java.util.ArrayList;
Jeremy Kleind42209d2015-12-28 15:11:58 -080078import java.util.HashMap;
Hugo Benichidafed3d2017-03-06 09:17:06 +090079import java.util.List;
80import java.util.Map;
markchien40898ca2020-01-21 13:11:06 +080081import java.util.Objects;
junyulai48eac1d42018-12-27 17:25:29 +080082import java.util.concurrent.Executor;
junyulai7c469172019-01-16 20:23:34 +080083import java.util.concurrent.ExecutorService;
84import java.util.concurrent.Executors;
85import java.util.concurrent.RejectedExecutionException;
Jeremy Kleind42209d2015-12-28 15:11:58 -080086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087/**
88 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060089 * notifies applications when network connectivity changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 * <p>
91 * The primary responsibilities of this class are to:
92 * <ol>
93 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
94 * <li>Send broadcast intents when network connectivity changes</li>
95 * <li>Attempt to "fail over" to another network when connectivity to a network
96 * is lost</li>
97 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
98 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070099 * <li>Provide an API that allows applications to request and select networks for their data
100 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 * </ol>
102 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -0600103@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700104public class ConnectivityManager {
105 private static final String TAG = "ConnectivityManager";
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +0900106 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700109 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 * been established or lost. The NetworkInfo for the affected network is
111 * sent as an extra; it should be consulted to see what kind of
112 * connectivity event occurred.
113 * <p/>
Mark Lu33ec1062016-12-05 10:57:55 -0800114 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
115 * broadcast if they declare the broadcast receiver in their manifest. Apps
116 * will still receive broadcasts if they register their
117 * {@link android.content.BroadcastReceiver} with
118 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
119 * and that context is still valid.
120 * <p/>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * If this is a connection that was the result of failing over from a
122 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
123 * set to true.
124 * <p/>
125 * For a loss of connectivity, if the connectivity manager is attempting
126 * to connect (or has already connected) to another network, the
127 * NetworkInfo for the new network is also passed as an extra. This lets
128 * any receivers of the broadcast know that they should not necessarily
129 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800130 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 * the failover attempt succeeded (and so there is still overall data
132 * connectivity), or that the failover attempt failed, meaning that all
133 * connectivity has been lost.
134 * <p/>
135 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
136 * is set to {@code true} if there are no connected networks at all.
Chalard Jean054cd162018-02-10 05:33:50 +0900137 *
138 * @deprecated apps should use the more versatile {@link #requestNetwork},
139 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
140 * functions instead for faster and more detailed updates about the network
141 * changes they care about.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800143 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean054cd162018-02-10 05:33:50 +0900144 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500148 * The device has connected to a network that has presented a captive
149 * portal, which is blocking Internet connectivity. The user was presented
150 * with a notification that network sign in is required,
151 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400152 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500153 * facilitate signing in to the network. This action includes a
154 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
155 * the network presenting the captive portal; all communication with the
156 * captive portal must be done using this {@code Network} object.
157 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400158 * This activity includes a {@link CaptivePortal} extra named
159 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
160 * outcomes of the captive portal sign in to the system:
161 * <ul>
162 * <li> When the app handling this action believes the user has signed in to
163 * the network and the captive portal has been dismissed, the app should
164 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
165 * reevaluate the network. If reevaluation finds the network no longer
166 * subject to a captive portal, the network may become the default active
Chalard Jean4d660112018-06-04 16:52:49 +0900167 * data network.</li>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400168 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500169 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400170 * {@link CaptivePortal#ignoreNetwork}. </li>
171 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500172 */
173 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
174 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
175
176 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 * The lookup key for a {@link NetworkInfo} object. Retrieve with
178 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700179 *
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900180 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
181 * can't accurately represent modern network characteristics.
182 * Please obtain information about networks from the {@link NetworkCapabilities}
183 * or {@link LinkProperties} objects instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700185 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700189 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700190 *
191 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900192 * @deprecated The network type is not rich enough to represent the characteristics
193 * of modern networks. Please use {@link NetworkCapabilities} instead,
194 * in particular the transports.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700195 */
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900196 @Deprecated
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700197 public static final String EXTRA_NETWORK_TYPE = "networkType";
198
199 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 * The lookup key for a boolean that indicates whether a connect event
201 * is for a network to which the connectivity manager was failing over
202 * following a disconnect on another network.
203 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai3822c8a2018-12-13 12:47:51 +0800204 *
205 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 */
junyulai3822c8a2018-12-13 12:47:51 +0800207 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 public static final String EXTRA_IS_FAILOVER = "isFailover";
209 /**
210 * The lookup key for a {@link NetworkInfo} object. This is supplied when
211 * there is another network that it may be possible to connect to. Retrieve with
212 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800213 *
214 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 */
junyulai3822c8a2018-12-13 12:47:51 +0800216 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
218 /**
219 * The lookup key for a boolean that indicates whether there is a
220 * complete lack of connectivity, i.e., no network is available.
221 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
222 */
223 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
224 /**
225 * The lookup key for a string that indicates why an attempt to connect
226 * to a network failed. The string has no particular structure. It is
227 * intended to be used in notifications presented to users. Retrieve
228 * it with {@link android.content.Intent#getStringExtra(String)}.
229 */
230 public static final String EXTRA_REASON = "reason";
231 /**
232 * The lookup key for a string that provides optionally supplied
233 * extra information about the network state. The information
234 * may be passed up from the lower networking layers, and its
235 * meaning may be specific to a particular network type. Retrieve
236 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800237 *
238 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 */
junyulai3822c8a2018-12-13 12:47:51 +0800240 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700242 /**
243 * The lookup key for an int that provides information about
244 * our connection to the internet at large. 0 indicates no connection,
245 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700246 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700247 * {@hide}
248 */
249 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400251 * The lookup key for a {@link CaptivePortal} object included with the
252 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
253 * object can be used to either indicate to the system that the captive
254 * portal has been dismissed or that the user does not want to pursue
255 * signing in to captive portal. Retrieve it with
256 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500257 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400258 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700259
260 /**
261 * Key for passing a URL to the captive portal login activity.
262 */
263 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
264
Paul Jensen25a217c2015-02-27 22:55:47 -0500265 /**
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900266 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
267 * portal login activity.
268 * {@hide}
269 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900270 @SystemApi
271 @TestApi
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900272 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
273 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
274
275 /**
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900276 * Key for passing a user agent string to the captive portal login activity.
277 * {@hide}
278 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900279 @SystemApi
280 @TestApi
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900281 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
282 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
283
284 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700285 * Broadcast action to indicate the change of data activity status
286 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800287 * The network becomes active when data transmission is started, or
288 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700289 * {@hide}
290 */
291 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean4d660112018-06-04 16:52:49 +0900292 public static final String ACTION_DATA_ACTIVITY_CHANGE =
293 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700294 /**
295 * The lookup key for an enum that indicates the network device type on which this data activity
296 * change happens.
297 * {@hide}
298 */
299 public static final String EXTRA_DEVICE_TYPE = "deviceType";
300 /**
301 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
302 * it is actively sending or receiving data and {@code false} means it is idle.
303 * {@hide}
304 */
305 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700306 /**
307 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
308 * {@hide}
309 */
310 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700311
312 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 * Broadcast Action: The setting for background data usage has changed
314 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
315 * <p>
316 * If an application uses the network in the background, it should listen
317 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700318 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800319 * <p>
320 *
321 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
322 * of background data depends on several combined factors, and
323 * this broadcast is no longer sent. Instead, when background
324 * data is unavailable, {@link #getActiveNetworkInfo()} will now
325 * appear disconnected. During first boot after a platform
326 * upgrade, this broadcast will be sent once if
327 * {@link #getBackgroundDataSetting()} was {@code false} before
328 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 */
330 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800331 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
333 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
334
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700335 /**
336 * Broadcast Action: The network connection may not be good
337 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
338 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
339 * the network and it's condition.
340 * @hide
341 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800342 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100343 @UnsupportedAppUsage
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700344 public static final String INET_CONDITION_ACTION =
345 "android.net.conn.INET_CONDITION_ACTION";
346
Robert Greenwalt42acef32009-08-12 16:08:25 -0700347 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800348 * Broadcast Action: A tetherable connection has come or gone.
349 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline8351faa2017-04-17 16:47:23 +0900350 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
351 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800352 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
353 * the current state of tethering. Each include a list of
354 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800355 * @hide
356 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800357 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100358 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800359 public static final String ACTION_TETHER_STATE_CHANGED =
markchien9e44cde2019-12-25 19:40:32 +0800360 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800361
362 /**
363 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800364 * gives a String[] listing all the interfaces configured for
365 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800366 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100367 @UnsupportedAppUsage
markchien9e44cde2019-12-25 19:40:32 +0800368 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800369
370 /**
371 * @hide
Erik Kline8351faa2017-04-17 16:47:23 +0900372 * gives a String[] listing all the interfaces currently in local-only
373 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800374 */
markchien9e44cde2019-12-25 19:40:32 +0800375 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline8351faa2017-04-17 16:47:23 +0900376
377 /**
378 * @hide
379 * gives a String[] listing all the interfaces currently tethered
380 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
381 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100382 @UnsupportedAppUsage
markchien9e44cde2019-12-25 19:40:32 +0800383 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800384
385 /**
386 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800387 * gives a String[] listing all the interfaces we tried to tether and
388 * failed. Use {@link #getLastTetherError} to find the error code
389 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800390 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100391 @UnsupportedAppUsage
markchien9e44cde2019-12-25 19:40:32 +0800392 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800393
394 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800395 * Broadcast Action: The captive portal tracker has finished its test.
396 * Sent only while running Setup Wizard, in lieu of showing a user
397 * notification.
398 * @hide
399 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800400 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800401 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
402 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
403 /**
404 * The lookup key for a boolean that indicates whether a captive portal was detected.
405 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
406 * @hide
407 */
408 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
409
410 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900411 * Action used to display a dialog that asks the user whether to connect to a network that is
412 * not validated. This intent is used to start the dialog in settings via startActivity.
413 *
414 * @hide
415 */
416 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
417
418 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900419 * Action used to display a dialog that asks the user whether to avoid a network that is no
420 * longer validated. This intent is used to start the dialog in settings via startActivity.
421 *
422 * @hide
423 */
424 public static final String ACTION_PROMPT_LOST_VALIDATION =
425 "android.net.conn.PROMPT_LOST_VALIDATION";
426
427 /**
lucasline252a742019-03-12 13:08:03 +0800428 * Action used to display a dialog that asks the user whether to stay connected to a network
429 * that has not validated. This intent is used to start the dialog in settings via
430 * startActivity.
431 *
432 * @hide
433 */
434 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
435 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
436
437 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800438 * Invalid tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900439 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800440 * @hide
441 */
markchien9e44cde2019-12-25 19:40:32 +0800442 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800443
444 /**
445 * Wifi tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900446 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800447 * @hide
448 */
449 @SystemApi
markchien9e44cde2019-12-25 19:40:32 +0800450 public static final int TETHERING_WIFI = TetheringManager.TETHERING_WIFI;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800451
452 /**
453 * USB tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900454 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800455 * @hide
456 */
457 @SystemApi
markchien9e44cde2019-12-25 19:40:32 +0800458 public static final int TETHERING_USB = TetheringManager.TETHERING_USB;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800459
460 /**
461 * Bluetooth tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900462 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800463 * @hide
464 */
465 @SystemApi
markchien9e44cde2019-12-25 19:40:32 +0800466 public static final int TETHERING_BLUETOOTH = TetheringManager.TETHERING_BLUETOOTH;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800467
468 /**
Jimmy Chenbcd86d02019-07-15 18:03:23 +0800469 * Wifi P2p tethering type.
470 * Wifi P2p tethering is set through events automatically, and don't
471 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
472 * @hide
473 */
markchien9e44cde2019-12-25 19:40:32 +0800474 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chenbcd86d02019-07-15 18:03:23 +0800475
476 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800477 * Extra used for communicating with the TetherService. Includes the type of tethering to
478 * enable if any.
479 * @hide
480 */
markchien40898ca2020-01-21 13:11:06 +0800481 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800482
483 /**
484 * Extra used for communicating with the TetherService. Includes the type of tethering for
485 * which to cancel provisioning.
486 * @hide
487 */
markchien40898ca2020-01-21 13:11:06 +0800488 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800489
490 /**
491 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
492 * provisioning.
493 * @hide
494 */
markchien40898ca2020-01-21 13:11:06 +0800495 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800496
497 /**
498 * Tells the TetherService to run a provision check now.
499 * @hide
500 */
markchien40898ca2020-01-21 13:11:06 +0800501 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800502
503 /**
504 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
505 * which will receive provisioning results. Can be left empty.
506 * @hide
507 */
markchien40898ca2020-01-21 13:11:06 +0800508 public static final String EXTRA_PROVISION_CALLBACK =
509 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800510
511 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800512 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700513 * @hide
514 */
paulhu4dc238b52020-01-13 16:46:45 +0800515 @SystemApi
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700516 public static final int TYPE_NONE = -1;
517
518 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900519 * A Mobile data connection. Devices may support more than one.
520 *
521 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
522 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
523 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700524 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900525 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700526 public static final int TYPE_MOBILE = 0;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900527
Robert Greenwalt42acef32009-08-12 16:08:25 -0700528 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900529 * A WIFI data connection. Devices may support more than one.
530 *
531 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
532 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
533 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700534 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900535 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700536 public static final int TYPE_WIFI = 1;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900537
Robert Greenwalt42acef32009-08-12 16:08:25 -0700538 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800539 * An MMS-specific Mobile data connection. This network type may use the
540 * same network interface as {@link #TYPE_MOBILE} or it may use a different
541 * one. This is used by applications needing to talk to the carrier's
542 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900543 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900544 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900545 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900546 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700547 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700548 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700549 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900550
Robert Greenwalt42acef32009-08-12 16:08:25 -0700551 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800552 * A SUPL-specific Mobile data connection. This network type may use the
553 * same network interface as {@link #TYPE_MOBILE} or it may use a different
554 * one. This is used by applications needing to talk to the carrier's
555 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900556 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900557 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900558 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900559 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700560 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700561 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700562 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900563
Robert Greenwalt42acef32009-08-12 16:08:25 -0700564 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800565 * A DUN-specific Mobile data connection. This network type may use the
566 * same network interface as {@link #TYPE_MOBILE} or it may use a different
567 * one. This is sometimes by the system when setting up an upstream connection
568 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900569 *
570 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
571 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
572 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700573 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900574 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700575 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900576
Robert Greenwalt42acef32009-08-12 16:08:25 -0700577 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800578 * A High Priority Mobile data connection. This network type uses the
579 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900580 * is different.
581 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900582 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
583 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
584 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700585 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700586 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700587 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900588
jsh8214deb2010-03-11 15:04:43 -0800589 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900590 * A WiMAX data connection.
591 *
592 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
593 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
594 * appropriate network. {@see NetworkCapabilities} for supported transports.
jsh8214deb2010-03-11 15:04:43 -0800595 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900596 @Deprecated
jsh8214deb2010-03-11 15:04:43 -0800597 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800598
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800599 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900600 * A Bluetooth data connection.
601 *
602 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
603 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
604 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800605 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900606 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800607 public static final int TYPE_BLUETOOTH = 7;
608
Robert Greenwalt60810842011-04-22 15:28:18 -0700609 /**
610 * Dummy data connection. This should not be used on shipping devices.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900611 * @deprecated This is not used any more.
Robert Greenwalt60810842011-04-22 15:28:18 -0700612 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900613 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800614 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800615
Robert Greenwalt60810842011-04-22 15:28:18 -0700616 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900617 * An Ethernet data connection.
618 *
619 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
620 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
621 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt60810842011-04-22 15:28:18 -0700622 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900623 @Deprecated
Robert Greenwalte12aec92011-01-28 14:48:37 -0800624 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700625
Wink Saville9d7d6282011-03-12 14:52:01 -0800626 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800627 * Over the air Administration.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900628 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800629 * {@hide}
630 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900631 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900632 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Saville9d7d6282011-03-12 14:52:01 -0800633 public static final int TYPE_MOBILE_FOTA = 10;
634
635 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800636 * IP Multimedia Subsystem.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900637 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800638 * {@hide}
639 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900640 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100641 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800642 public static final int TYPE_MOBILE_IMS = 11;
643
644 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800645 * Carrier Branded Services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900646 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800647 * {@hide}
648 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900649 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900650 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Saville9d7d6282011-03-12 14:52:01 -0800651 public static final int TYPE_MOBILE_CBS = 12;
652
repo syncaea743a2011-07-29 23:55:49 -0700653 /**
654 * A Wi-Fi p2p connection. Only requesting processes will have access to
655 * the peers connected.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900656 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncaea743a2011-07-29 23:55:49 -0700657 * {@hide}
658 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900659 @Deprecated
paulhu5ae1d2c2020-01-15 15:38:23 +0800660 @SystemApi
repo syncaea743a2011-07-29 23:55:49 -0700661 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800662
Wink Saville5e56bc52013-07-29 15:00:57 -0700663 /**
664 * The network to use for initially attaching to the network
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900665 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville5e56bc52013-07-29 15:00:57 -0700666 * {@hide}
667 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900668 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100669 @UnsupportedAppUsage
Wink Saville5e56bc52013-07-29 15:00:57 -0700670 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700671
Lorenzo Colittie285b432015-04-23 15:32:42 +0900672 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700673 * Emergency PDN connection for emergency services. This
674 * may include IMS and MMS in emergency situations.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900675 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram3e0e3bc2014-06-26 11:03:44 -0700676 * {@hide}
677 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900678 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900679 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram3e0e3bc2014-06-26 11:03:44 -0700680 public static final int TYPE_MOBILE_EMERGENCY = 15;
681
Hui Lu1c5624a2014-01-15 11:05:36 -0500682 /**
683 * The network that uses proxy to achieve connectivity.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900684 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu1c5624a2014-01-15 11:05:36 -0500685 * {@hide}
686 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900687 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100688 @UnsupportedAppUsage
Hui Lu1c5624a2014-01-15 11:05:36 -0500689 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700690
Robert Greenwalt8283f882014-07-07 17:09:01 -0700691 /**
692 * A virtual network using one or more native bearers.
693 * It may or may not be providing security services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900694 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700695 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900696 @Deprecated
Robert Greenwalt8283f882014-07-07 17:09:01 -0700697 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500698
Benedict Wong89ce5e32018-11-14 17:40:55 -0800699 /**
700 * A network that is exclusively meant to be used for testing
701 *
702 * @deprecated Use {@link NetworkCapabilities} instead.
703 * @hide
704 */
705 @Deprecated
706 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700707
Chalard Jeanc06d7882019-11-21 14:48:00 +0900708 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
709 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
710 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
711 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
712 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
713
Robert Greenwalt8283f882014-07-07 17:09:01 -0700714 /** {@hide} */
Benedict Wong89ce5e32018-11-14 17:40:55 -0800715 public static final int MAX_RADIO_TYPE = TYPE_TEST;
716
717 /** {@hide} */
718 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719
Hugo Benichi16f0a942017-06-20 14:07:59 +0900720 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
721
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800722 /**
723 * If you want to set the default network preference,you can directly
724 * change the networkAttributes array in framework's config.xml.
725 *
726 * @deprecated Since we support so many more networks now, the single
727 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800728 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800729 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800730 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800731 * from an App.
732 */
733 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
735
Jeff Sharkey625239a2012-09-26 22:03:49 -0700736 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700737 * @hide
738 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900739 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700740
Paul Jensen5d59e782014-07-11 12:28:19 -0400741 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900742 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
743 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean4d660112018-06-04 16:52:49 +0900744 * registered from those that were already unregistered.
Hugo Benichi31c176d2017-06-17 13:14:12 +0900745 * @hide
746 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900747 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900748 new NetworkRequest.Builder().clearCapabilities().build();
749
750 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400751 * A NetID indicating no Network is selected.
752 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
753 * @hide
754 */
755 public static final int NETID_UNSET = 0;
756
Erik Kline4d092232017-10-30 15:29:44 +0900757 /**
758 * Private DNS Mode values.
759 *
760 * The "private_dns_mode" global setting stores a String value which is
761 * expected to be one of the following.
762 */
763
764 /**
765 * @hide
766 */
767 public static final String PRIVATE_DNS_MODE_OFF = "off";
768 /**
769 * @hide
770 */
771 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
772 /**
773 * @hide
774 */
775 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
776 /**
777 * The default Private DNS mode.
778 *
779 * This may change from release to release or may become dependent upon
780 * the capabilities of the underlying platform.
781 *
782 * @hide
783 */
Erik Kline19841792018-05-16 16:41:57 +0900784 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline4d092232017-10-30 15:29:44 +0900785
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900786 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700787 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500788 /**
789 * A kludge to facilitate static access where a Context pointer isn't available, like in the
790 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
791 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
792 * methods that take a Context argument.
793 */
794 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900796 private final Context mContext;
797
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800798 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800799 private INetworkPolicyManager mNPManager;
Automerger Merge Worker6112c822020-03-06 00:38:43 +0000800 private final TetheringManager mTetheringManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800801
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800802 /**
803 * Tests if a given integer represents a valid network type.
804 * @param networkType the type to be tested
805 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400806 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
807 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800808 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700809 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700810 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900811 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 }
813
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800814 /**
815 * Returns a non-localized string representing a given network type.
816 * ONLY used for debugging output.
817 * @param type the type needing naming
818 * @return a String for the given type, or a string version of the type ("87")
819 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900820 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800821 * {@hide}
822 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900823 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100824 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700825 public static String getNetworkTypeName(int type) {
826 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900827 case TYPE_NONE:
828 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700829 case TYPE_MOBILE:
830 return "MOBILE";
831 case TYPE_WIFI:
832 return "WIFI";
833 case TYPE_MOBILE_MMS:
834 return "MOBILE_MMS";
835 case TYPE_MOBILE_SUPL:
836 return "MOBILE_SUPL";
837 case TYPE_MOBILE_DUN:
838 return "MOBILE_DUN";
839 case TYPE_MOBILE_HIPRI:
840 return "MOBILE_HIPRI";
841 case TYPE_WIMAX:
842 return "WIMAX";
843 case TYPE_BLUETOOTH:
844 return "BLUETOOTH";
845 case TYPE_DUMMY:
846 return "DUMMY";
847 case TYPE_ETHERNET:
848 return "ETHERNET";
849 case TYPE_MOBILE_FOTA:
850 return "MOBILE_FOTA";
851 case TYPE_MOBILE_IMS:
852 return "MOBILE_IMS";
853 case TYPE_MOBILE_CBS:
854 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700855 case TYPE_WIFI_P2P:
856 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700857 case TYPE_MOBILE_IA:
858 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700859 case TYPE_MOBILE_EMERGENCY:
860 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500861 case TYPE_PROXY:
862 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900863 case TYPE_VPN:
864 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700865 default:
866 return Integer.toString(type);
867 }
868 }
869
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800870 /**
871 * Checks if a given type uses the cellular data connection.
872 * This should be replaced in the future by a network property.
873 * @param networkType the type to check
874 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900875 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800876 * {@hide}
877 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900878 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900879 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700880 public static boolean isNetworkTypeMobile(int networkType) {
881 switch (networkType) {
882 case TYPE_MOBILE:
883 case TYPE_MOBILE_MMS:
884 case TYPE_MOBILE_SUPL:
885 case TYPE_MOBILE_DUN:
886 case TYPE_MOBILE_HIPRI:
887 case TYPE_MOBILE_FOTA:
888 case TYPE_MOBILE_IMS:
889 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700890 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700891 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700892 return true;
893 default:
894 return false;
895 }
896 }
897
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800898 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700899 * Checks if the given network type is backed by a Wi-Fi radio.
900 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900901 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700902 * @hide
903 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900904 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700905 public static boolean isNetworkTypeWifi(int networkType) {
906 switch (networkType) {
907 case TYPE_WIFI:
908 case TYPE_WIFI_P2P:
909 return true;
910 default:
911 return false;
912 }
913 }
914
915 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800916 * Specifies the preferred network type. When the device has more
917 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800918 *
919 * @param preference the network type to prefer over all others. It is
920 * unspecified what happens to the old preferred network in the
921 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700922 * @deprecated Functionality has been removed as it no longer makes sense,
923 * with many more than two networks - we'd need an array to express
924 * preference. Instead we use dynamic network properties of
925 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800926 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700927 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
930
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800931 /**
932 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800933 *
934 * @return an integer representing the preferred network type
935 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700936 * @deprecated Functionality has been removed as it no longer makes sense,
937 * with many more than two networks - we'd need an array to express
938 * preference. Instead we use dynamic network properties of
939 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800940 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700941 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600942 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700944 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 }
946
Scott Main671644c2011-10-06 19:02:28 -0700947 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800948 * Returns details about the currently active default data network. When
949 * connected, this network is the default route for outgoing connections.
950 * You should always check {@link NetworkInfo#isConnected()} before initiating
951 * network traffic. This may return {@code null} when there is no default
952 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900953 * Note that if the default network is a VPN, this method will return the
954 * NetworkInfo for one of its underlying networks instead, or null if the
955 * VPN agent did not specify any. Apps interested in learning about VPNs
956 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800957 *
958 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500959 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800960 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700961 */
junyulai3822c8a2018-12-13 12:47:51 +0800962 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600963 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900964 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 public NetworkInfo getActiveNetworkInfo() {
966 try {
967 return mService.getActiveNetworkInfo();
968 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700969 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
971 }
972
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800973 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500974 * Returns a {@link Network} object corresponding to the currently active
975 * default data network. In the event that the current active default data
976 * network disconnects, the returned {@code Network} object will no longer
977 * be usable. This will return {@code null} when there is no default
978 * network.
979 *
980 * @return a {@link Network} object for the current default network or
981 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500982 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600983 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900984 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -0500985 public Network getActiveNetwork() {
986 try {
987 return mService.getActiveNetwork();
988 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700989 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500990 }
991 }
992
993 /**
Robin Leed2baf792016-03-24 12:07:00 +0000994 * Returns a {@link Network} object corresponding to the currently active
995 * default data network for a specific UID. In the event that the default data
996 * network disconnects, the returned {@code Network} object will no longer
997 * be usable. This will return {@code null} when there is no default
998 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +0000999 *
1000 * @return a {@link Network} object for the current default network for the
1001 * given UID or {@code null} if no default network is currently active
1002 *
1003 * @hide
1004 */
paulhua6af6b62019-08-12 16:25:11 +08001005 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001006 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +00001007 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001008 return getActiveNetworkForUid(uid, false);
1009 }
1010
1011 /** {@hide} */
1012 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001013 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001014 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001015 } catch (RemoteException e) {
1016 throw e.rethrowFromSystemServer();
1017 }
1018 }
1019
1020 /**
Charles He36738632017-05-15 17:07:18 +01001021 * Checks if a VPN app supports always-on mode.
1022 *
1023 * In order to support the always-on feature, an app has to
1024 * <ul>
1025 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +01001026 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
1027 * meta-data field.
Charles He36738632017-05-15 17:07:18 +01001028 * </ul>
1029 *
1030 * @param userId The identifier of the user for whom the VPN app is installed.
1031 * @param vpnPackage The canonical package name of the VPN app.
1032 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
1033 * @hide
1034 */
1035 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1036 try {
1037 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1038 } catch (RemoteException e) {
1039 throw e.rethrowFromSystemServer();
1040 }
1041 }
1042
1043 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001044 * Configures an always-on VPN connection through a specific application.
1045 * This connection is automatically granted and persisted after a reboot.
1046 *
1047 * <p>The designated package should declare a {@link VpnService} in its
1048 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1049 * otherwise the call will fail.
1050 *
1051 * @param userId The identifier of the user to set an always-on VPN for.
1052 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1053 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001054 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1055 * {@code false} otherwise.
Pavel Grafova462bcb2019-01-25 08:50:06 +00001056 * @param lockdownWhitelist The list of packages that are allowed to access network directly
1057 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
1058 * this method must be called when a package that should be whitelisted is installed or
1059 * uninstalled.
Robin Lee244ce8e2016-01-05 18:03:46 +00001060 * @return {@code true} if the package is set as always-on VPN controller;
1061 * {@code false} otherwise.
1062 * @hide
1063 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001064 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leedc679712016-05-03 13:23:03 +01001065 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001066 boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001067 try {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001068 return mService.setAlwaysOnVpnPackage(
1069 userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
Robin Lee244ce8e2016-01-05 18:03:46 +00001070 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001071 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001072 }
1073 }
1074
Pavel Grafova462bcb2019-01-25 08:50:06 +00001075 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001076 * Returns the package name of the currently set always-on VPN application.
1077 * If there is no always-on VPN set, or the VPN is provided by the system instead
1078 * of by an app, {@code null} will be returned.
1079 *
1080 * @return Package name of VPN controller responsible for always-on VPN,
1081 * or {@code null} if none is set.
1082 * @hide
1083 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001084 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee244ce8e2016-01-05 18:03:46 +00001085 public String getAlwaysOnVpnPackageForUser(int userId) {
1086 try {
1087 return mService.getAlwaysOnVpnPackage(userId);
1088 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001089 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001090 }
1091 }
1092
1093 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001094 * @return whether always-on VPN is in lockdown mode.
1095 *
1096 * @hide
1097 **/
1098 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1099 public boolean isVpnLockdownEnabled(int userId) {
1100 try {
1101 return mService.isVpnLockdownEnabled(userId);
1102 } catch (RemoteException e) {
1103 throw e.rethrowFromSystemServer();
1104 }
1105
1106 }
1107
1108 /**
1109 * @return the list of packages that are allowed to access network when always-on VPN is in
1110 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1111 *
1112 * @hide
1113 **/
1114 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1115 public List<String> getVpnLockdownWhitelist(int userId) {
1116 try {
1117 return mService.getVpnLockdownWhitelist(userId);
1118 } catch (RemoteException e) {
1119 throw e.rethrowFromSystemServer();
1120 }
1121 }
1122
1123 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001124 * Returns details about the currently active default data network
1125 * for a given uid. This is for internal use only to avoid spying
1126 * other apps.
1127 *
1128 * @return a {@link NetworkInfo} object for the current default network
1129 * for the given uid or {@code null} if no default network is
1130 * available for the specified uid.
1131 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001132 * {@hide}
1133 */
paulhua6af6b62019-08-12 16:25:11 +08001134 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001135 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001136 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001137 return getActiveNetworkInfoForUid(uid, false);
1138 }
1139
1140 /** {@hide} */
1141 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001142 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001143 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001144 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001145 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001146 }
1147 }
1148
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001149 /**
1150 * Returns connection status information about a particular
1151 * network type.
1152 *
1153 * @param networkType integer specifying which networkType in
1154 * which you're interested.
1155 * @return a {@link NetworkInfo} object for the requested
1156 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001157 * supported by the device. If {@code networkType} is
1158 * TYPE_VPN and a VPN is active for the calling app,
1159 * then this method will try to return one of the
1160 * underlying networks for the VPN or null if the
1161 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001162 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001163 * @deprecated This method does not support multiple connected networks
1164 * of the same type. Use {@link #getAllNetworks} and
1165 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001166 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001167 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001168 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001169 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 public NetworkInfo getNetworkInfo(int networkType) {
1171 try {
1172 return mService.getNetworkInfo(networkType);
1173 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001174 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 }
1176 }
1177
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001178 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001179 * Returns connection status information about a particular
1180 * Network.
1181 *
1182 * @param network {@link Network} specifying which network
1183 * in which you're interested.
1184 * @return a {@link NetworkInfo} object for the requested
1185 * network or {@code null} if the {@code Network}
1186 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001187 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001188 */
junyulai3822c8a2018-12-13 12:47:51 +08001189 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001190 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001191 @Nullable
1192 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001193 return getNetworkInfoForUid(network, Process.myUid(), false);
1194 }
1195
1196 /** {@hide} */
1197 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001198 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001199 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001200 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001201 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001202 }
1203 }
1204
1205 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001206 * Returns connection status information about all network
1207 * types supported by the device.
1208 *
1209 * @return an array of {@link NetworkInfo} objects. Check each
1210 * {@link NetworkInfo#getType} for which type each applies.
1211 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001212 * @deprecated This method does not support multiple connected networks
1213 * of the same type. Use {@link #getAllNetworks} and
1214 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001215 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001216 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001217 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001218 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 public NetworkInfo[] getAllNetworkInfo() {
1220 try {
1221 return mService.getAllNetworkInfo();
1222 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001223 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
1225 }
1226
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001227 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001228 * Returns the {@link Network} object currently serving a given type, or
1229 * null if the given type is not connected.
1230 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001231 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001232 * @deprecated This method does not support multiple connected networks
1233 * of the same type. Use {@link #getAllNetworks} and
1234 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001235 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001236 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001237 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001238 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001239 public Network getNetworkForType(int networkType) {
1240 try {
1241 return mService.getNetworkForType(networkType);
1242 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001243 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001244 }
1245 }
1246
1247 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001248 * Returns an array of all {@link Network} currently tracked by the
1249 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001250 *
1251 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001252 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001253 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001254 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001255 public Network[] getAllNetworks() {
1256 try {
1257 return mService.getAllNetworks();
1258 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001259 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001260 }
1261 }
1262
1263 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001264 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001265 * the Networks that applications run by the given user will use by default.
1266 * @hide
1267 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001268 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001269 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1270 try {
Qingxi Li9c5d8b92020-01-08 12:51:49 -08001271 return mService.getDefaultNetworkCapabilitiesForUser(
1272 userId, mContext.getOpPackageName());
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001273 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001274 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001275 }
1276 }
1277
1278 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001279 * Returns the IP information for the current default network.
1280 *
1281 * @return a {@link LinkProperties} object describing the IP info
1282 * for the current default network, or {@code null} if there
1283 * is no current default network.
1284 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001285 * {@hide}
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001286 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1287 * value of {@link #getActiveNetwork()} instead. In particular,
1288 * this method will return non-null LinkProperties even if the
1289 * app is blocked by policy from using this network.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001290 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001291 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001292 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001293 public LinkProperties getActiveLinkProperties() {
1294 try {
1295 return mService.getActiveLinkProperties();
1296 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001297 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001298 }
1299 }
1300
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001301 /**
1302 * Returns the IP information for a given network type.
1303 *
1304 * @param networkType the network type of interest.
1305 * @return a {@link LinkProperties} object describing the IP info
1306 * for the given networkType, or {@code null} if there is
1307 * no current default network.
1308 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001309 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001310 * @deprecated This method does not support multiple connected networks
1311 * of the same type. Use {@link #getAllNetworks},
1312 * {@link #getNetworkInfo(android.net.Network)}, and
1313 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001314 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001315 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001316 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09001317 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001318 public LinkProperties getLinkProperties(int networkType) {
1319 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001320 return mService.getLinkPropertiesForType(networkType);
1321 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001322 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001323 }
1324 }
1325
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001326 /**
1327 * Get the {@link LinkProperties} for the given {@link Network}. This
1328 * will return {@code null} if the network is unknown.
1329 *
1330 * @param network The {@link Network} object identifying the network in question.
1331 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001332 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001333 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001334 @Nullable
1335 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001336 try {
1337 return mService.getLinkProperties(network);
1338 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001339 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001340 }
1341 }
1342
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001343 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001344 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001345 * will return {@code null} if the network is unknown.
1346 *
1347 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001348 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001349 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001350 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001351 @Nullable
1352 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001353 try {
Qingxi Li9c5d8b92020-01-08 12:51:49 -08001354 return mService.getNetworkCapabilities(network, mContext.getOpPackageName());
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001355 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001356 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001357 }
1358 }
1359
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001360 /**
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001361 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainib7c24872016-01-04 12:16:14 -08001362 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1363 * portal is present.
1364 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1365 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1366 *
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001367 * The system network validation may be using different strategies to detect captive portals,
1368 * so this method does not necessarily return a URL used by the system. It only returns a URL
1369 * that may be relevant for other components trying to detect captive portals.
paulhua6af6b62019-08-12 16:25:11 +08001370 *
Udam Sainib7c24872016-01-04 12:16:14 -08001371 * @hide
paulhua6af6b62019-08-12 16:25:11 +08001372 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1373 * system.
Udam Sainib7c24872016-01-04 12:16:14 -08001374 */
paulhua6af6b62019-08-12 16:25:11 +08001375 @Deprecated
Udam Sainib7c24872016-01-04 12:16:14 -08001376 @SystemApi
paulhua6af6b62019-08-12 16:25:11 +08001377 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainib7c24872016-01-04 12:16:14 -08001378 public String getCaptivePortalServerUrl() {
1379 try {
1380 return mService.getCaptivePortalServerUrl();
1381 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001382 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001383 }
1384 }
1385
1386 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 * Tells the underlying networking system that the caller wants to
1388 * begin using the named feature. The interpretation of {@code feature}
1389 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001390 *
1391 * <p>This method requires the caller to hold either the
1392 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1393 * or the ability to modify system settings as determined by
1394 * {@link android.provider.Settings.System#canWrite}.</p>
1395 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 * @param networkType specifies which network the request pertains to
1397 * @param feature the name of the feature to be used
1398 * @return an integer value representing the outcome of the request.
1399 * The interpretation of this value is specific to each networking
1400 * implementation+feature combination, except that the value {@code -1}
1401 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001402 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001403 * @deprecated Deprecated in favor of the cleaner
1404 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001405 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001406 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001407 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001409 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001411 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001412 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1413 if (netCap == null) {
1414 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1415 feature);
Chalard Jeanc06d7882019-11-21 14:48:00 +09001416 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001417 }
1418
1419 NetworkRequest request = null;
1420 synchronized (sLegacyRequests) {
1421 LegacyRequest l = sLegacyRequests.get(netCap);
1422 if (l != null) {
1423 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1424 renewRequestLocked(l);
1425 if (l.currentNetwork != null) {
Chalard Jeanc06d7882019-11-21 14:48:00 +09001426 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001427 } else {
Chalard Jeanc06d7882019-11-21 14:48:00 +09001428 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001429 }
1430 }
1431
1432 request = requestNetworkForFeatureLocked(netCap);
1433 }
1434 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001435 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanc06d7882019-11-21 14:48:00 +09001436 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001437 } else {
1438 Log.d(TAG, " request Failed");
Chalard Jeanc06d7882019-11-21 14:48:00 +09001439 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441 }
1442
1443 /**
1444 * Tells the underlying networking system that the caller is finished
1445 * using the named feature. The interpretation of {@code feature}
1446 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001447 *
1448 * <p>This method requires the caller to hold either the
1449 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1450 * or the ability to modify system settings as determined by
1451 * {@link android.provider.Settings.System#canWrite}.</p>
1452 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 * @param networkType specifies which network the request pertains to
1454 * @param feature the name of the feature that is no longer needed
1455 * @return an integer value representing the outcome of the request.
1456 * The interpretation of this value is specific to each networking
1457 * implementation+feature combination, except that the value {@code -1}
1458 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001459 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001460 * @deprecated Deprecated in favor of the cleaner
1461 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001462 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001463 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001464 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001466 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001468 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001469 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1470 if (netCap == null) {
1471 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1472 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 return -1;
1474 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001475
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001476 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001477 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001478 }
1479 return 1;
1480 }
1481
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001482 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001483 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1484 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001485 switch (feature) {
1486 case "enableCBS":
1487 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1488 case "enableDUN":
1489 case "enableDUNAlways":
1490 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1491 case "enableFOTA":
1492 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1493 case "enableHIPRI":
1494 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1495 case "enableIMS":
1496 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1497 case "enableMMS":
1498 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1499 case "enableSUPL":
1500 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1501 default:
1502 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001503 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001504 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1505 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001506 }
1507 return null;
1508 }
1509
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001510 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001511 if (netCap == null) return TYPE_NONE;
1512 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1513 return TYPE_MOBILE_CBS;
1514 }
1515 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1516 return TYPE_MOBILE_IMS;
1517 }
1518 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1519 return TYPE_MOBILE_FOTA;
1520 }
1521 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1522 return TYPE_MOBILE_DUN;
1523 }
1524 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1525 return TYPE_MOBILE_SUPL;
1526 }
1527 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1528 return TYPE_MOBILE_MMS;
1529 }
1530 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1531 return TYPE_MOBILE_HIPRI;
1532 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001533 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1534 return TYPE_WIFI_P2P;
1535 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001536 return TYPE_NONE;
1537 }
1538
1539 private static class LegacyRequest {
1540 NetworkCapabilities networkCapabilities;
1541 NetworkRequest networkRequest;
1542 int expireSequenceNumber;
1543 Network currentNetwork;
1544 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001545
1546 private void clearDnsBinding() {
1547 if (currentNetwork != null) {
1548 currentNetwork = null;
1549 setProcessDefaultNetworkForHostResolution(null);
1550 }
1551 }
1552
Robert Greenwalt6078b502014-06-11 16:05:07 -07001553 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001554 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001555 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001556 currentNetwork = network;
1557 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001558 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001559 }
1560 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001561 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001562 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001563 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1564 }
1565 };
1566 }
1567
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001568 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001569 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1570 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001571
1572 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1573 synchronized (sLegacyRequests) {
1574 LegacyRequest l = sLegacyRequests.get(netCap);
1575 if (l != null) return l.networkRequest;
1576 }
1577 return null;
1578 }
1579
1580 private void renewRequestLocked(LegacyRequest l) {
1581 l.expireSequenceNumber++;
1582 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1583 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1584 }
1585
1586 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1587 int ourSeqNum = -1;
1588 synchronized (sLegacyRequests) {
1589 LegacyRequest l = sLegacyRequests.get(netCap);
1590 if (l == null) return;
1591 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001592 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001593 }
1594 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1595 }
1596
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001597 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001598 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1599 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001600 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001601 try {
1602 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001603 } catch (RemoteException e) {
1604 throw e.rethrowFromSystemServer();
1605 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001606 LegacyRequest l = new LegacyRequest();
1607 l.networkCapabilities = netCap;
1608 l.delay = delay;
1609 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001610 l.networkRequest = sendRequestForNetwork(
1611 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001612 if (l.networkRequest == null) return null;
1613 sLegacyRequests.put(netCap, l);
1614 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1615 return l.networkRequest;
1616 }
1617
1618 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1619 if (delay >= 0) {
1620 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001621 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001622 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1623 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001624 }
1625 }
1626
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001627 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001628 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1629 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001630 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001631 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001632 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001633 if (l == null) return false;
1634 unregisterNetworkCallback(l.networkCallback);
1635 l.clearDnsBinding();
1636 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638
Erik Kline35bf06c2017-01-26 18:08:28 +09001639 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1640 static {
1641 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1642 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1643 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1644 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1645 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1646 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1647 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1648 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1649 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1650 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1651 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1652 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1653 }
1654
1655 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1656 static {
1657 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1658 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1659 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1660 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1661 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1662 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1663 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1664 }
1665
1666 /**
1667 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1668 * instance suitable for registering a request or callback. Throws an
1669 * IllegalArgumentException if no mapping from the legacy type to
1670 * NetworkCapabilities is known.
1671 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001672 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1673 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001674 * @hide
1675 */
1676 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1677 final NetworkCapabilities nc = new NetworkCapabilities();
1678
1679 // Map from type to transports.
1680 final int NOT_FOUND = -1;
1681 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001682 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001683 nc.addTransportType(transport);
1684
1685 // Map from type to capabilities.
1686 nc.addCapability(sLegacyTypeToCapability.get(
1687 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1688 nc.maybeMarkCapabilitiesRestricted();
1689 return nc;
1690 }
1691
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001692 /** @hide */
1693 public static class PacketKeepaliveCallback {
Artur Satayev751e5512019-11-15 19:12:49 +00001694 @UnsupportedAppUsage
1695 public PacketKeepaliveCallback() {
1696 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001697 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001698 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001699 public void onStarted() {}
1700 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001701 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001702 public void onStopped() {}
1703 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001704 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001705 public void onError(int error) {}
1706 }
1707
1708 /**
1709 * Allows applications to request that the system periodically send specific packets on their
1710 * behalf, using hardware offload to save battery power.
1711 *
1712 * To request that the system send keepalives, call one of the methods that return a
1713 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1714 * passing in a non-null callback. If the callback is successfully started, the callback's
1715 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1716 * specifying one of the {@code ERROR_*} constants in this class.
1717 *
Chalard Jean4d660112018-06-04 16:52:49 +09001718 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1719 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1720 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001721 *
junyulai48eac1d42018-12-27 17:25:29 +08001722 * @deprecated Use {@link SocketKeepalive} instead.
1723 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001724 * @hide
1725 */
1726 public class PacketKeepalive {
1727
1728 private static final String TAG = "PacketKeepalive";
1729
1730 /** @hide */
1731 public static final int SUCCESS = 0;
1732
1733 /** @hide */
1734 public static final int NO_KEEPALIVE = -1;
1735
1736 /** @hide */
1737 public static final int BINDER_DIED = -10;
1738
1739 /** The specified {@code Network} is not connected. */
1740 public static final int ERROR_INVALID_NETWORK = -20;
1741 /** The specified IP addresses are invalid. For example, the specified source IP address is
1742 * not configured on the specified {@code Network}. */
1743 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1744 /** The requested port is invalid. */
1745 public static final int ERROR_INVALID_PORT = -22;
1746 /** The packet length is invalid (e.g., too long). */
1747 public static final int ERROR_INVALID_LENGTH = -23;
1748 /** The packet transmission interval is invalid (e.g., too short). */
1749 public static final int ERROR_INVALID_INTERVAL = -24;
1750
1751 /** The hardware does not support this request. */
1752 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001753 /** The hardware returned an error. */
1754 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001755
Nathan Harold63dd8132018-02-14 13:09:45 -08001756 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001757 public static final int NATT_PORT = 4500;
1758
Nathan Harold63dd8132018-02-14 13:09:45 -08001759 /** The minimum interval in seconds between keepalive packet transmissions */
1760 public static final int MIN_INTERVAL = 10;
1761
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001762 private final Network mNetwork;
junyulai7c469172019-01-16 20:23:34 +08001763 private final ISocketKeepaliveCallback mCallback;
1764 private final ExecutorService mExecutor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001765
1766 private volatile Integer mSlot;
1767
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001768 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001769 public void stop() {
1770 try {
junyulai7c469172019-01-16 20:23:34 +08001771 mExecutor.execute(() -> {
1772 try {
1773 if (mSlot != null) {
1774 mService.stopKeepalive(mNetwork, mSlot);
1775 }
1776 } catch (RemoteException e) {
1777 Log.e(TAG, "Error stopping packet keepalive: ", e);
1778 throw e.rethrowFromSystemServer();
1779 }
1780 });
1781 } catch (RejectedExecutionException e) {
1782 // The internal executor has already stopped due to previous event.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001783 }
1784 }
1785
1786 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001787 Preconditions.checkNotNull(network, "network cannot be null");
1788 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001789 mNetwork = network;
junyulai7c469172019-01-16 20:23:34 +08001790 mExecutor = Executors.newSingleThreadExecutor();
1791 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001792 @Override
junyulai7c469172019-01-16 20:23:34 +08001793 public void onStarted(int slot) {
1794 Binder.withCleanCallingIdentity(() ->
1795 mExecutor.execute(() -> {
1796 mSlot = slot;
1797 callback.onStarted();
1798 }));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001799 }
junyulai7c469172019-01-16 20:23:34 +08001800
1801 @Override
1802 public void onStopped() {
1803 Binder.withCleanCallingIdentity(() ->
1804 mExecutor.execute(() -> {
1805 mSlot = null;
1806 callback.onStopped();
1807 }));
1808 mExecutor.shutdown();
1809 }
1810
1811 @Override
1812 public void onError(int error) {
1813 Binder.withCleanCallingIdentity(() ->
1814 mExecutor.execute(() -> {
1815 mSlot = null;
1816 callback.onError(error);
1817 }));
1818 mExecutor.shutdown();
1819 }
1820
1821 @Override
1822 public void onDataReceived() {
1823 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1824 // this callback when data is received.
1825 }
1826 };
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001827 }
1828 }
1829
1830 /**
1831 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1832 *
junyulai48eac1d42018-12-27 17:25:29 +08001833 * @deprecated Use {@link #createSocketKeepalive} instead.
1834 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001835 * @hide
1836 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001837 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001838 public PacketKeepalive startNattKeepalive(
1839 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1840 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1841 final PacketKeepalive k = new PacketKeepalive(network, callback);
1842 try {
junyulai7c469172019-01-16 20:23:34 +08001843 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001844 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1845 } catch (RemoteException e) {
1846 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai7c469172019-01-16 20:23:34 +08001847 throw e.rethrowFromSystemServer();
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001848 }
1849 return k;
1850 }
1851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 /**
junyulai48eac1d42018-12-27 17:25:29 +08001853 * Request that keepalives be started on a IPsec NAT-T socket.
1854 *
1855 * @param network The {@link Network} the socket is on.
1856 * @param socket The socket that needs to be kept alive.
1857 * @param source The source address of the {@link UdpEncapsulationSocket}.
1858 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1859 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1860 * must run callback sequentially, otherwise the order of callbacks cannot be
1861 * guaranteed.
1862 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1863 * changes. Must be extended by applications that use this API.
1864 *
junyulai352dc2f2019-01-08 20:04:33 +08001865 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1866 * given socket.
junyulai48eac1d42018-12-27 17:25:29 +08001867 **/
junyulai0c666972019-03-04 22:45:36 +08001868 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai48eac1d42018-12-27 17:25:29 +08001869 @NonNull UdpEncapsulationSocket socket,
1870 @NonNull InetAddress source,
1871 @NonNull InetAddress destination,
1872 @NonNull @CallbackExecutor Executor executor,
1873 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001874 ParcelFileDescriptor dup;
1875 try {
junyulai15178152019-03-27 11:00:37 +08001876 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1877 // which cannot be obtained by the app process.
junyulai0c666972019-03-04 22:45:36 +08001878 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1879 } catch (IOException ignored) {
1880 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1881 // ERROR_INVALID_SOCKET.
1882 dup = new ParcelFileDescriptor(new FileDescriptor());
1883 }
1884 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1885 destination, executor, callback);
junyulai215b8772019-01-15 11:32:44 +08001886 }
1887
1888 /**
1889 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1890 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1891 *
1892 * @param network The {@link Network} the socket is on.
junyulai0c666972019-03-04 22:45:36 +08001893 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1894 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1895 * from that port.
junyulai215b8772019-01-15 11:32:44 +08001896 * @param source The source address of the {@link UdpEncapsulationSocket}.
1897 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1898 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1899 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1900 * must run callback sequentially, otherwise the order of callbacks cannot be
1901 * guaranteed.
1902 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1903 * changes. Must be extended by applications that use this API.
1904 *
junyulai352dc2f2019-01-08 20:04:33 +08001905 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1906 * given socket.
junyulai215b8772019-01-15 11:32:44 +08001907 * @hide
1908 */
1909 @SystemApi
1910 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08001911 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1912 @NonNull ParcelFileDescriptor pfd,
junyulai215b8772019-01-15 11:32:44 +08001913 @NonNull InetAddress source,
1914 @NonNull InetAddress destination,
1915 @NonNull @CallbackExecutor Executor executor,
1916 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001917 ParcelFileDescriptor dup;
1918 try {
junyulai15178152019-03-27 11:00:37 +08001919 // TODO: Consider remove unnecessary dup.
junyulai0c666972019-03-04 22:45:36 +08001920 dup = pfd.dup();
1921 } catch (IOException ignored) {
1922 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1923 // ERROR_INVALID_SOCKET.
1924 dup = new ParcelFileDescriptor(new FileDescriptor());
1925 }
1926 return new NattSocketKeepalive(mService, network, dup,
1927 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08001928 }
1929
1930 /**
junyulai352dc2f2019-01-08 20:04:33 +08001931 * Request that keepalives be started on a TCP socket.
1932 * The socket must be established.
1933 *
1934 * @param network The {@link Network} the socket is on.
1935 * @param socket The socket that needs to be kept alive.
1936 * @param executor The executor on which callback will be invoked. This implementation assumes
1937 * the provided {@link Executor} runs the callbacks in sequence with no
1938 * concurrency. Failing this, no guarantee of correctness can be made. It is
1939 * the responsibility of the caller to ensure the executor provides this
1940 * guarantee. A simple way of creating such an executor is with the standard
1941 * tool {@code Executors.newSingleThreadExecutor}.
1942 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1943 * changes. Must be extended by applications that use this API.
1944 *
1945 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1946 * given socket.
1947 * @hide
1948 */
1949 @SystemApi
1950 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08001951 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai352dc2f2019-01-08 20:04:33 +08001952 @NonNull Socket socket,
1953 @NonNull Executor executor,
1954 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001955 ParcelFileDescriptor dup;
1956 try {
1957 dup = ParcelFileDescriptor.fromSocket(socket);
1958 } catch (UncheckedIOException ignored) {
1959 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1960 // ERROR_INVALID_SOCKET.
1961 dup = new ParcelFileDescriptor(new FileDescriptor());
1962 }
1963 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai352dc2f2019-01-08 20:04:33 +08001964 }
1965
1966 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 * Ensure that a network route exists to deliver traffic to the specified
1968 * host via the specified network interface. An attempt to add a route that
1969 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001970 *
1971 * <p>This method requires the caller to hold either the
1972 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1973 * or the ability to modify system settings as determined by
1974 * {@link android.provider.Settings.System#canWrite}.</p>
1975 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 * @param networkType the type of the network over which traffic to the specified
1977 * host is to be routed
1978 * @param hostAddress the IP address of the host to which the route is desired
1979 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001980 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001981 * @deprecated Deprecated in favor of the
1982 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
1983 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001984 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001985 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001986 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001988 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001990 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001991 }
1992
1993 /**
1994 * Ensure that a network route exists to deliver traffic to the specified
1995 * host via the specified network interface. An attempt to add a route that
1996 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001997 *
1998 * <p>This method requires the caller to hold either the
1999 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2000 * or the ability to modify system settings as determined by
2001 * {@link android.provider.Settings.System#canWrite}.</p>
2002 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002003 * @param networkType the type of the network over which traffic to the specified
2004 * host is to be routed
2005 * @param hostAddress the IP address of the host to which the route is desired
2006 * @return {@code true} on success, {@code false} on failure
2007 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002008 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002009 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002010 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002011 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002012 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002013 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002014 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002016 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002018 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 }
2020 }
2021
2022 /**
2023 * Returns the value of the setting for background data usage. If false,
2024 * applications should not use the network if the application is not in the
2025 * foreground. Developers should respect this setting, and check the value
2026 * of this before performing any background data operations.
2027 * <p>
2028 * All applications that have background services that use the network
2029 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002030 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002031 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002032 * background data depends on several combined factors, and this method will
2033 * always return {@code true}. Instead, when background data is unavailable,
2034 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002035 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 * @return Whether background data usage is allowed.
2037 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002038 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002040 // assume that background data is allowed; final authority is
2041 // NetworkInfo which may be blocked.
2042 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
2044
2045 /**
2046 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002047 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 * @param allowBackgroundData Whether an application should use data while
2049 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002050 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2052 * @see #getBackgroundDataSetting()
2053 * @hide
2054 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002055 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002056 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002058 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002060
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002061 /** {@hide} */
2062 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002063 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002064 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2065 try {
2066 return mService.getActiveNetworkQuotaInfo();
2067 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002068 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002069 }
2070 }
2071
2072 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002073 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002074 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002075 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002076 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002077 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002078 public boolean getMobileDataEnabled() {
Meng Wanga73bed82019-11-18 17:10:00 -08002079 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2080 if (tm != null) {
2081 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2082 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2083 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2084 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2085 + " retVal=" + retVal);
2086 return retVal;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002087 }
Wink Saville36ffb042014-12-05 11:10:30 -08002088 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002089 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002090 }
2091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002093 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002094 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002095 */
2096 public interface OnNetworkActiveListener {
2097 /**
2098 * Called on the main thread of the process to report that the current data network
2099 * has become active, and it is now a good time to perform any pending network
2100 * operations. Note that this listener only tells you when the network becomes
2101 * active; if at any other time you want to know whether it is active (and thus okay
2102 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002103 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002104 */
Chalard Jean4d660112018-06-04 16:52:49 +09002105 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002106 }
2107
2108 private INetworkManagementService getNetworkManagementService() {
2109 synchronized (this) {
2110 if (mNMService != null) {
2111 return mNMService;
2112 }
2113 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2114 mNMService = INetworkManagementService.Stub.asInterface(b);
2115 return mNMService;
2116 }
2117 }
2118
2119 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002120 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002121
2122 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002123 * Start listening to reports when the system's default data network is active, meaning it is
2124 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2125 * to determine the current state of the system's default network after registering the
2126 * listener.
2127 * <p>
2128 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002129 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002130 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002131 *
2132 * @param l The listener to be told when the network is active.
2133 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002134 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002135 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2136 @Override
2137 public void onNetworkActive() throws RemoteException {
2138 l.onNetworkActive();
2139 }
2140 };
2141
2142 try {
2143 getNetworkManagementService().registerNetworkActivityListener(rl);
2144 mNetworkActivityListeners.put(l, rl);
2145 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002146 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002147 }
2148 }
2149
2150 /**
2151 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002152 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002153 *
2154 * @param l Previously registered listener.
2155 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002156 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002157 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002158 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002159 try {
2160 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2161 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002162 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002163 }
2164 }
2165
2166 /**
2167 * Return whether the data network is currently active. An active network means that
2168 * it is currently in a high power state for performing data transmission. On some
2169 * types of networks, it may be expensive to move and stay in such a state, so it is
2170 * more power efficient to batch network traffic together when the radio is already in
2171 * this state. This method tells you whether right now is currently a good time to
2172 * initiate network traffic, as the network is already active.
2173 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002174 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002175 try {
2176 return getNetworkManagementService().isNetworkActive();
2177 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002178 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002179 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002180 }
2181
2182 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 * {@hide}
2184 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002185 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002186 mContext = Preconditions.checkNotNull(context, "missing context");
2187 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002188 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensene0bef712014-12-10 15:12:18 -05002189 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002191
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002192 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002193 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002194 public static ConnectivityManager from(Context context) {
2195 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2196 }
2197
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002198 /** @hide */
2199 public NetworkRequest getDefaultRequest() {
2200 try {
2201 // This is not racy as the default request is final in ConnectivityService.
2202 return mService.getDefaultRequest();
2203 } catch (RemoteException e) {
2204 throw e.rethrowFromSystemServer();
2205 }
2206 }
2207
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002208 /* TODO: These permissions checks don't belong in client-side code. Move them to
2209 * services.jar, possibly in com.android.server.net. */
2210
2211 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002212 public static final void enforceChangePermission(Context context) {
2213 int uid = Binder.getCallingUid();
2214 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2215 .getPackageNameForUid(context, uid), true /* throwException */);
2216 }
2217
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002218 /** {@hide} */
2219 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002220 Preconditions.checkNotNull(context, "Context cannot be null");
2221 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002222
Robert Greenwaltedb47662014-09-16 17:54:19 -07002223 if (context.getResources().getStringArray(
2224 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2225 // Have a provisioning app - must only let system apps (which check this app)
2226 // turn on tethering
2227 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002228 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002229 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002230 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002231 // If callingPkg's uid is not same as Binder.getCallingUid(),
2232 // AppOpsService throws SecurityException.
2233 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2234 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002235 }
2236 }
2237
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002238 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002239 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2240 * situations where a Context pointer is unavailable.
2241 * @hide
2242 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002243 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002244 static ConnectivityManager getInstanceOrNull() {
2245 return sInstance;
2246 }
2247
2248 /**
2249 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2250 * situations where a Context pointer is unavailable.
2251 * @hide
2252 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002253 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002254 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002255 private static ConnectivityManager getInstance() {
2256 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002257 throw new IllegalStateException("No ConnectivityManager yet constructed");
2258 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002259 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002260 }
2261
2262 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002263 * Get the set of tetherable, available interfaces. This list is limited by
2264 * device configuration and current interface existence.
2265 *
2266 * @return an array of 0 or more Strings of tetherable interface names.
2267 *
markchien40898ca2020-01-21 13:11:06 +08002268 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002269 * {@hide}
2270 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002271 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002272 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002273 @Deprecated
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002274 public String[] getTetherableIfaces() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002275 return mTetheringManager.getTetherableIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002276 }
2277
2278 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002279 * Get the set of tethered interfaces.
2280 *
2281 * @return an array of 0 or more String of currently tethered interface names.
2282 *
markchien40898ca2020-01-21 13:11:06 +08002283 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002284 * {@hide}
2285 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002286 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002287 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002288 @Deprecated
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002289 public String[] getTetheredIfaces() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002290 return mTetheringManager.getTetheredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002291 }
2292
2293 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002294 * Get the set of interface names which attempted to tether but
2295 * failed. Re-attempting to tether may cause them to reset to the Tethered
2296 * state. Alternatively, causing the interface to be destroyed and recreated
2297 * may cause them to reset to the available state.
2298 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2299 * information on the cause of the errors.
2300 *
2301 * @return an array of 0 or more String indicating the interface names
2302 * which failed to tether.
2303 *
markchien40898ca2020-01-21 13:11:06 +08002304 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002305 * {@hide}
2306 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002307 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002308 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002309 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002310 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002311 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002312 }
2313
2314 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002315 * Get the set of tethered dhcp ranges.
2316 *
markchien2c153702020-02-06 19:23:26 +08002317 * @deprecated This method is not supported.
2318 * TODO: remove this function when all of clients are removed.
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002319 * {@hide}
2320 */
paulhua6af6b62019-08-12 16:25:11 +08002321 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien40898ca2020-01-21 13:11:06 +08002322 @Deprecated
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002323 public String[] getTetheredDhcpRanges() {
markchien2c153702020-02-06 19:23:26 +08002324 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002325 }
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
markchiene8b9d752020-01-20 19:31:56 +08002348 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002349 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002350 * {@hide}
2351 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002352 @UnsupportedAppUsage
markchiene8b9d752020-01-20 19:31:56 +08002353 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002354 public int tether(String iface) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002355 return mTetheringManager.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002356 }
2357
2358 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002359 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002360 *
2361 * <p>This method requires the caller to hold either the
2362 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2363 * or the ability to modify system settings as determined by
2364 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002365 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002366 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2367 * and WifiStateMachine which need direct access. All other clients should use
2368 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2369 * logic.</p>
2370 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002371 * @param iface the interface name to untether.
2372 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2373 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002374 * {@hide}
2375 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002376 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002377 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002378 public int untether(String iface) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002379 return mTetheringManager.untether(iface);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002380 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002381
2382 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002383 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002384 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002385 * due to device configuration.
2386 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002387 * <p>If this app does not have permission to use this API, it will always
2388 * return false rather than throw an exception.</p>
2389 *
2390 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2391 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2392 *
2393 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2394 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2395 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002396 * @return a boolean - {@code true} indicating Tethering is supported.
2397 *
markchien40898ca2020-01-21 13:11:06 +08002398 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002399 * {@hide}
2400 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002401 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002402 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2403 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002404 public boolean isTetheringSupported() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002405 return mTetheringManager.isTetheringSupported();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002406 }
2407
2408 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002409 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchiene8b9d752020-01-20 19:31:56 +08002410 *
2411 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002412 * @hide
2413 */
2414 @SystemApi
markchiene8b9d752020-01-20 19:31:56 +08002415 @Deprecated
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002416 public static abstract class OnStartTetheringCallback {
2417 /**
2418 * Called when tethering has been successfully started.
2419 */
Chalard Jean4d660112018-06-04 16:52:49 +09002420 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002421
2422 /**
2423 * Called when starting tethering failed.
2424 */
Chalard Jean4d660112018-06-04 16:52:49 +09002425 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002426 }
2427
2428 /**
2429 * Convenient overload for
2430 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2431 * handler to run on the current thread's {@link Looper}.
markchiene8b9d752020-01-20 19:31:56 +08002432 *
2433 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002434 * @hide
2435 */
2436 @SystemApi
markchiene8b9d752020-01-20 19:31:56 +08002437 @Deprecated
Udam Saini0e94c362017-06-07 12:06:28 -07002438 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002439 public void startTethering(int type, boolean showProvisioningUi,
2440 final OnStartTetheringCallback callback) {
2441 startTethering(type, showProvisioningUi, callback, null);
2442 }
2443
2444 /**
2445 * Runs tether provisioning for the given type if needed and then starts tethering if
2446 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2447 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2448 * schedules tether provisioning re-checks if appropriate.
2449 *
2450 * @param type The type of tethering to start. Must be one of
2451 * {@link ConnectivityManager.TETHERING_WIFI},
2452 * {@link ConnectivityManager.TETHERING_USB}, or
2453 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2454 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2455 * is one. This should be true the first time this function is called and also any time
2456 * the user can see this UI. It gives users information from their carrier about the
2457 * check failing and how they can sign up for tethering if possible.
2458 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2459 * of the result of trying to tether.
2460 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchiene8b9d752020-01-20 19:31:56 +08002461 *
2462 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002463 * @hide
2464 */
2465 @SystemApi
markchiene8b9d752020-01-20 19:31:56 +08002466 @Deprecated
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002467 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002468 public void startTethering(int type, boolean showProvisioningUi,
2469 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002470 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002471
markchiene8b9d752020-01-20 19:31:56 +08002472 final Executor executor = new Executor() {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002473 @Override
markchiene8b9d752020-01-20 19:31:56 +08002474 public void execute(Runnable command) {
2475 if (handler == null) {
2476 command.run();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002477 } else {
markchiene8b9d752020-01-20 19:31:56 +08002478 handler.post(command);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002479 }
2480 }
2481 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002482
markchiene8b9d752020-01-20 19:31:56 +08002483 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2484 @Override
2485 public void onTetheringStarted() {
2486 callback.onTetheringStarted();
2487 }
2488
2489 @Override
markchien62a625d2020-03-19 13:37:43 +08002490 public void onTetheringFailed(final int error) {
markchiene8b9d752020-01-20 19:31:56 +08002491 callback.onTetheringFailed();
2492 }
2493 };
2494
2495 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien62a625d2020-03-19 13:37:43 +08002496 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchiene8b9d752020-01-20 19:31:56 +08002497
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002498 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002499 }
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}.
markchien40898ca2020-01-21 13:11:06 +08002509 *
2510 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002511 * @hide
2512 */
2513 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002514 @Deprecated
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002515 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002516 public void stopTethering(int type) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002517 mTetheringManager.stopTethering(type);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002518 }
2519
2520 /**
markchien26299ed2019-02-27 14:56:11 +08002521 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2522 * upstream status.
2523 *
Nathan Haroldedf6b3d2020-01-23 18:03:46 -08002524 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien40898ca2020-01-21 13:11:06 +08002525 * @hide
markchien26299ed2019-02-27 14:56:11 +08002526 */
2527 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002528 @Deprecated
markchien26299ed2019-02-27 14:56:11 +08002529 public abstract static class OnTetheringEventCallback {
2530
2531 /**
2532 * Called when tethering upstream changed. This can be called multiple times and can be
2533 * called any time.
2534 *
2535 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2536 * have any upstream.
2537 */
2538 public void onUpstreamChanged(@Nullable Network network) {}
2539 }
2540
markchien40898ca2020-01-21 13:11:06 +08002541 @GuardedBy("mTetheringEventCallbacks")
2542 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2543 mTetheringEventCallbacks = new ArrayMap<>();
2544
markchien26299ed2019-02-27 14:56:11 +08002545 /**
2546 * Start listening to tethering change events. Any new added callback will receive the last
markchien9f246bd2019-04-03 10:43:09 +08002547 * tethering status right away. If callback is registered when tethering has no upstream or
markchien26299ed2019-02-27 14:56:11 +08002548 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2549 * with a null argument. The same callback object cannot be registered twice.
2550 *
2551 * @param executor the executor on which callback will be invoked.
2552 * @param callback the callback to be called when tethering has change events.
markchien40898ca2020-01-21 13:11:06 +08002553 *
Nathan Haroldedf6b3d2020-01-23 18:03:46 -08002554 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien26299ed2019-02-27 14:56:11 +08002555 * @hide
2556 */
2557 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002558 @Deprecated
markchien26299ed2019-02-27 14:56:11 +08002559 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2560 public void registerTetheringEventCallback(
2561 @NonNull @CallbackExecutor Executor executor,
2562 @NonNull final OnTetheringEventCallback callback) {
2563 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2564
markchien40898ca2020-01-21 13:11:06 +08002565 final TetheringEventCallback tetherCallback =
2566 new TetheringEventCallback() {
2567 @Override
2568 public void onUpstreamChanged(@Nullable Network network) {
2569 callback.onUpstreamChanged(network);
2570 }
2571 };
2572
2573 synchronized (mTetheringEventCallbacks) {
2574 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002575 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien40898ca2020-01-21 13:11:06 +08002576 }
markchien26299ed2019-02-27 14:56:11 +08002577 }
2578
2579 /**
2580 * Remove tethering event callback previously registered with
2581 * {@link #registerTetheringEventCallback}.
2582 *
2583 * @param callback previously registered callback.
markchien40898ca2020-01-21 13:11:06 +08002584 *
2585 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien26299ed2019-02-27 14:56:11 +08002586 * @hide
2587 */
2588 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002589 @Deprecated
markchien26299ed2019-02-27 14:56:11 +08002590 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2591 public void unregisterTetheringEventCallback(
2592 @NonNull final OnTetheringEventCallback callback) {
markchien40898ca2020-01-21 13:11:06 +08002593 Objects.requireNonNull(callback, "The callback must be non-null");
2594 synchronized (mTetheringEventCallbacks) {
2595 final TetheringEventCallback tetherCallback =
2596 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002597 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien40898ca2020-01-21 13:11:06 +08002598 }
markchien26299ed2019-02-27 14:56:11 +08002599 }
2600
2601
2602 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002603 * Get the list of regular expressions that define any tetherable
2604 * USB network interfaces. If USB tethering is not supported by the
2605 * device, this list should be empty.
2606 *
2607 * @return an array of 0 or more regular expression Strings defining
2608 * what interfaces are considered tetherable usb interfaces.
2609 *
markchien40898ca2020-01-21 13:11:06 +08002610 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002611 * {@hide}
2612 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002613 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002614 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002615 @Deprecated
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002616 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002617 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002618 }
2619
2620 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002621 * Get the list of regular expressions that define any tetherable
2622 * Wifi network interfaces. If Wifi tethering is not supported by the
2623 * device, this list should be empty.
2624 *
2625 * @return an array of 0 or more regular expression Strings defining
2626 * what interfaces are considered tetherable wifi interfaces.
2627 *
markchien40898ca2020-01-21 13:11:06 +08002628 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002629 * {@hide}
2630 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002631 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002632 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002633 @Deprecated
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002634 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002635 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002636 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002637
Danica Chang6fdd0c62010-08-11 14:54:43 -07002638 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002639 * Get the list of regular expressions that define any tetherable
2640 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2641 * device, this list should be empty.
2642 *
2643 * @return an array of 0 or more regular expression Strings defining
2644 * what interfaces are considered tetherable bluetooth interfaces.
2645 *
markchien40898ca2020-01-21 13:11:06 +08002646 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2647 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002648 * {@hide}
2649 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002650 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002651 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002652 @Deprecated
Danica Chang6fdd0c62010-08-11 14:54:43 -07002653 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002654 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002655 }
2656
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002657 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002658 * Attempt to both alter the mode of USB and Tethering of USB. A
2659 * utility method to deal with some of the complexity of USB - will
2660 * attempt to switch to Rndis and subsequently tether the resulting
2661 * interface on {@code true} or turn off tethering and switch off
2662 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002663 *
2664 * <p>This method requires the caller to hold either the
2665 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2666 * or the ability to modify system settings as determined by
2667 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002668 *
2669 * @param enable a boolean - {@code true} to enable tethering
2670 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiene8b9d752020-01-20 19:31:56 +08002671 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002672 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002673 * {@hide}
2674 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002675 @UnsupportedAppUsage
markchiene8b9d752020-01-20 19:31:56 +08002676 @Deprecated
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002677 public int setUsbTethering(boolean enable) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002678 return mTetheringManager.setUsbTethering(enable);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002679 }
2680
markchien40898ca2020-01-21 13:11:06 +08002681 /**
2682 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2683 * {@hide}
2684 */
markchienf2731272019-01-16 17:44:13 +08002685 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002686 @Deprecated
2687 public static final int TETHER_ERROR_NO_ERROR = TetheringManager.TETHER_ERROR_NO_ERROR;
2688 /**
2689 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2690 * {@hide}
2691 */
2692 @Deprecated
2693 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2694 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2695 /**
2696 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2697 * {@hide}
2698 */
2699 @Deprecated
2700 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2701 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2702 /**
2703 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2704 * {@hide}
2705 */
2706 @Deprecated
2707 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2708 /**
2709 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2710 * {@hide}
2711 */
2712 @Deprecated
2713 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2714 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2715 /**
markchien62a625d2020-03-19 13:37:43 +08002716 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien40898ca2020-01-21 13:11:06 +08002717 * {@hide}
2718 */
2719 @Deprecated
markchien62a625d2020-03-19 13:37:43 +08002720 public static final int TETHER_ERROR_MASTER_ERROR =
2721 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien40898ca2020-01-21 13:11:06 +08002722 /**
2723 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2724 * {@hide}
2725 */
2726 @Deprecated
2727 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2728 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2729 /**
2730 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2731 * {@hide}
2732 */
2733 @Deprecated
2734 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2735 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2736 /**
markchien62a625d2020-03-19 13:37:43 +08002737 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien40898ca2020-01-21 13:11:06 +08002738 * {@hide}
2739 */
2740 @Deprecated
2741 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien62a625d2020-03-19 13:37:43 +08002742 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien40898ca2020-01-21 13:11:06 +08002743 /**
markchien62a625d2020-03-19 13:37:43 +08002744 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien40898ca2020-01-21 13:11:06 +08002745 * {@hide}
2746 */
2747 @Deprecated
2748 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien62a625d2020-03-19 13:37:43 +08002749 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien40898ca2020-01-21 13:11:06 +08002750 /**
2751 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2752 * {@hide}
2753 */
2754 @Deprecated
2755 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2756 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2757 /**
markchien62a625d2020-03-19 13:37:43 +08002758 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien40898ca2020-01-21 13:11:06 +08002759 * {@hide}
2760 */
markchienf2731272019-01-16 17:44:13 +08002761 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002762 @Deprecated
2763 public static final int TETHER_ERROR_PROVISION_FAILED =
markchien62a625d2020-03-19 13:37:43 +08002764 TetheringManager.TETHER_ERROR_PROVISIONING_FAILED;
markchien40898ca2020-01-21 13:11:06 +08002765 /**
2766 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2767 * {@hide}
2768 */
2769 @Deprecated
2770 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2771 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2772 /**
2773 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2774 * {@hide}
2775 */
markchienf2731272019-01-16 17:44:13 +08002776 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002777 @Deprecated
2778 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN =
2779 TetheringManager.TETHER_ERROR_ENTITLEMENT_UNKNOWN;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002780
2781 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002782 * Get a more detailed error code after a Tethering or Untethering
2783 * request asynchronously failed.
2784 *
2785 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002786 * @return error The error code of the last error tethering or untethering the named
2787 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002788 *
markchien40898ca2020-01-21 13:11:06 +08002789 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt5a735062010-03-02 17:25:02 -08002790 * {@hide}
2791 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002792 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002793 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002794 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002795 public int getLastTetherError(String iface) {
markchien62a625d2020-03-19 13:37:43 +08002796 int error = mTetheringManager.getLastTetherError(iface);
2797 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2798 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2799 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2800 // instead.
2801 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2802 }
2803 return error;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002804 }
2805
markchien9554abf2019-03-06 16:25:00 +08002806 /** @hide */
2807 @Retention(RetentionPolicy.SOURCE)
2808 @IntDef(value = {
2809 TETHER_ERROR_NO_ERROR,
2810 TETHER_ERROR_PROVISION_FAILED,
2811 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2812 })
2813 public @interface EntitlementResultCode {
2814 }
2815
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002816 /**
markchien9554abf2019-03-06 16:25:00 +08002817 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchienf2731272019-01-16 17:44:13 +08002818 * entitlement succeeded.
markchien40898ca2020-01-21 13:11:06 +08002819 *
2820 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchienf2731272019-01-16 17:44:13 +08002821 * @hide
2822 */
2823 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002824 @Deprecated
markchien9554abf2019-03-06 16:25:00 +08002825 public interface OnTetheringEntitlementResultListener {
2826 /**
2827 * Called to notify entitlement result.
2828 *
2829 * @param resultCode an int value of entitlement result. It may be one of
2830 * {@link #TETHER_ERROR_NO_ERROR},
2831 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2832 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2833 */
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002834 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchien9554abf2019-03-06 16:25:00 +08002835 }
2836
2837 /**
markchienf2731272019-01-16 17:44:13 +08002838 * Get the last value of the entitlement check on this downstream. If the cached value is
2839 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2840 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2841 * guaranteed that the UI-based entitlement check will complete in any specific time period
2842 * and may in fact never complete. Any successful entitlement check the platform performs for
2843 * any reason will update the cached value.
2844 *
2845 * @param type the downstream type of tethering. Must be one of
2846 * {@link #TETHERING_WIFI},
2847 * {@link #TETHERING_USB}, or
2848 * {@link #TETHERING_BLUETOOTH}.
2849 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchien9554abf2019-03-06 16:25:00 +08002850 * @param executor the executor on which callback will be invoked.
2851 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2852 * notify the caller of the result of entitlement check. The listener may be called zero
2853 * or one time.
markchien40898ca2020-01-21 13:11:06 +08002854 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchienf2731272019-01-16 17:44:13 +08002855 * {@hide}
2856 */
2857 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002858 @Deprecated
markchienf2731272019-01-16 17:44:13 +08002859 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchien9554abf2019-03-06 16:25:00 +08002860 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2861 @NonNull @CallbackExecutor Executor executor,
2862 @NonNull final OnTetheringEntitlementResultListener listener) {
2863 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2864 ResultReceiver wrappedListener = new ResultReceiver(null) {
2865 @Override
2866 protected void onReceiveResult(int resultCode, Bundle resultData) {
2867 Binder.withCleanCallingIdentity(() ->
2868 executor.execute(() -> {
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002869 listener.onTetheringEntitlementResult(resultCode);
markchien9554abf2019-03-06 16:25:00 +08002870 }));
2871 }
2872 };
2873
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002874 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienae8aa642019-12-16 20:15:20 +08002875 showEntitlementUi);
markchien9554abf2019-03-06 16:25:00 +08002876 }
2877
2878 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002879 * Report network connectivity status. This is currently used only
2880 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002881 * <p>This method requires the caller to hold the permission
2882 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002883 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002884 * @param networkType The type of network you want to report on
2885 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002886 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002887 * {@hide}
2888 */
2889 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002890 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002891 try {
2892 mService.reportInetCondition(networkType, percentage);
2893 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002894 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002895 }
2896 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002897
2898 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002899 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002900 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002901 * the framework to re-evaluate network connectivity and/or switch to another
2902 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002903 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002904 * @param network The {@link Network} the application was attempting to use
2905 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002906 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2907 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002908 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002909 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002910 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002911 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002912 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002913 // One of these will be ignored because it matches system's current state.
2914 // The other will trigger the necessary reevaluation.
2915 mService.reportNetworkConnectivity(network, true);
2916 mService.reportNetworkConnectivity(network, false);
2917 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002918 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002919 }
2920 }
2921
2922 /**
2923 * Report to the framework whether a network has working connectivity.
2924 * This provides a hint to the system that a particular network is providing
2925 * working connectivity or not. In response the framework may re-evaluate
2926 * the network's connectivity and might take further action thereafter.
2927 *
2928 * @param network The {@link Network} the application was attempting to use
2929 * or {@code null} to indicate the current default network.
2930 * @param hasConnectivity {@code true} if the application was able to successfully access the
2931 * Internet using {@code network} or {@code false} if not.
2932 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002933 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002934 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002935 try {
2936 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002937 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002938 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002939 }
2940 }
2941
2942 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002943 * Set a network-independent global http proxy. This is not normally what you want
2944 * for typical HTTP proxies - they are general network dependent. However if you're
2945 * doing something unusual like general internal filtering this may be useful. On
2946 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002947 *
2948 * @param p A {@link ProxyInfo} object defining the new global
2949 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002950 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002951 */
paulhua6af6b62019-08-12 16:25:11 +08002952 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk207900c2014-04-25 15:00:09 -04002953 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002954 try {
2955 mService.setGlobalProxy(p);
2956 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002957 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002958 }
2959 }
2960
2961 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002962 * Retrieve any network-independent global HTTP proxy.
2963 *
Jason Monk207900c2014-04-25 15:00:09 -04002964 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002965 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002966 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002967 */
Jason Monk207900c2014-04-25 15:00:09 -04002968 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002969 try {
2970 return mService.getGlobalProxy();
2971 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002972 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002973 }
2974 }
2975
2976 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002977 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2978 * network-specific HTTP proxy. If {@code network} is null, the
2979 * network-specific proxy returned is the proxy of the default active
2980 * network.
2981 *
2982 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2983 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2984 * or when {@code network} is {@code null},
2985 * the {@code ProxyInfo} for the default active network. Returns
2986 * {@code null} when no proxy applies or the caller doesn't have
2987 * permission to use {@code network}.
2988 * @hide
2989 */
2990 public ProxyInfo getProxyForNetwork(Network network) {
2991 try {
2992 return mService.getProxyForNetwork(network);
2993 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002994 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04002995 }
2996 }
2997
2998 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002999 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3000 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04003001 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05003002 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003003 *
Jason Monk207900c2014-04-25 15:00:09 -04003004 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003005 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07003006 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003007 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05003008 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04003009 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07003010 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003011
3012 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003013 * Returns true if the hardware supports the given network type
3014 * else it returns false. This doesn't indicate we have coverage
3015 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003016 * hardware supports it. For example a GSM phone without a SIM
3017 * should still return {@code true} for mobile data, but a wifi only
3018 * tablet would return {@code false}.
3019 *
3020 * @param networkType The network type we'd like to check
3021 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003022 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003023 * @hide
3024 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003025 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003026 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09003027 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003028 public boolean isNetworkSupported(int networkType) {
3029 try {
3030 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003031 } catch (RemoteException e) {
3032 throw e.rethrowFromSystemServer();
3033 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003034 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003035
3036 /**
3037 * Returns if the currently active data network is metered. A network is
3038 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003039 * that connection due to monetary costs, data limitations or
3040 * battery/performance issues. You should check this before doing large
3041 * data transfers, and warn the user or delay the operation until another
3042 * network is available.
3043 *
3044 * @return {@code true} if large transfers should be avoided, otherwise
3045 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003046 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003047 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003048 public boolean isActiveNetworkMetered() {
3049 try {
3050 return mService.isActiveNetworkMetered();
3051 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003052 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003053 }
3054 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003055
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003056 /**
3057 * If the LockdownVpn mechanism is enabled, updates the vpn
3058 * with a reload of its profile.
3059 *
3060 * @return a boolean with {@code} indicating success
3061 *
3062 * <p>This method can only be called by the system UID
3063 * {@hide}
3064 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003065 public boolean updateLockdownVpn() {
3066 try {
3067 return mService.updateLockdownVpn();
3068 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003069 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003070 }
3071 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07003072
3073 /**
Wink Saville948282b2013-08-29 08:55:16 -07003074 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07003075 *
Wink Savilleab9321d2013-06-29 21:10:57 -07003076 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07003077 *
3078 * @return time out that will be used, maybe less that suggestedTimeOutMs
3079 * -1 if an error.
3080 *
3081 * {@hide}
3082 */
Wink Saville948282b2013-08-29 08:55:16 -07003083 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003084 int timeOutMs = -1;
3085 try {
Wink Saville948282b2013-08-29 08:55:16 -07003086 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07003087 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003088 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07003089 }
3090 return timeOutMs;
3091 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003092
3093 /**
Wink Saville42d4f082013-07-20 20:31:59 -07003094 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003095 * {@hide}
3096 */
paulhua6af6b62019-08-12 16:25:11 +08003097 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003098 public String getMobileProvisioningUrl() {
3099 try {
3100 return mService.getMobileProvisioningUrl();
3101 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003102 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003103 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003104 }
Wink Saville42d4f082013-07-20 20:31:59 -07003105
3106 /**
Wink Saville948282b2013-08-29 08:55:16 -07003107 * Set sign in error notification to visible or in visible
3108 *
Wink Saville948282b2013-08-29 08:55:16 -07003109 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04003110 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07003111 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003112 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07003113 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003114 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003115 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04003116 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07003117 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003118 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07003119 }
3120 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003121
3122 /**
3123 * Set the value for enabling/disabling airplane mode
3124 *
3125 * @param enable whether to enable airplane mode or not
3126 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003127 * @hide
3128 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003129 @RequiresPermission(anyOf = {
Edward Savage-Jonesaffb2292019-11-26 13:18:08 +01003130 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003131 android.Manifest.permission.NETWORK_SETTINGS,
3132 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3133 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09003134 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003135 public void setAirplaneMode(boolean enable) {
3136 try {
3137 mService.setAirplaneMode(enable);
3138 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003139 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003140 }
3141 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003142
Chalard Jean05ab6812018-05-02 21:14:54 +09003143 /** {@hide} - returns the factory serial number */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003144 @UnsupportedAppUsage
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003145 @RequiresPermission(anyOf = {
3146 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3147 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean05ab6812018-05-02 21:14:54 +09003148 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003149 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003150 return mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003151 } catch (RemoteException e) {
3152 throw e.rethrowFromSystemServer();
3153 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003154 }
3155
3156 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00003157 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003158 @RequiresPermission(anyOf = {
3159 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3160 android.Manifest.permission.NETWORK_FACTORY})
Robert Greenwalta67be032014-05-16 15:49:14 -07003161 public void unregisterNetworkFactory(Messenger messenger) {
3162 try {
3163 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003164 } catch (RemoteException e) {
3165 throw e.rethrowFromSystemServer();
3166 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003167 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003168
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003169 /**
3170 * Registers the specified {@link NetworkProvider}.
3171 * Each listener must only be registered once. The listener can be unregistered with
3172 * {@link #unregisterNetworkProvider}.
3173 *
3174 * @param provider the provider to register
3175 * @return the ID of the provider. This ID must be used by the provider when registering
3176 * {@link android.net.NetworkAgent}s.
3177 * @hide
3178 */
3179 @SystemApi
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003180 @RequiresPermission(anyOf = {
3181 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3182 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003183 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3184 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003185 throw new IllegalStateException("NetworkProviders can only be registered once");
3186 }
3187
3188 try {
3189 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3190 provider.getName());
3191 provider.setProviderId(providerId);
3192 } catch (RemoteException e) {
3193 throw e.rethrowFromSystemServer();
3194 }
3195 return provider.getProviderId();
3196 }
3197
3198 /**
3199 * Unregisters the specified NetworkProvider.
3200 *
3201 * @param provider the provider to unregister
3202 * @hide
3203 */
3204 @SystemApi
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003205 @RequiresPermission(anyOf = {
3206 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3207 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003208 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3209 try {
3210 mService.unregisterNetworkProvider(provider.getMessenger());
3211 } catch (RemoteException e) {
3212 throw e.rethrowFromSystemServer();
3213 }
3214 provider.setProviderId(NetworkProvider.ID_NONE);
3215 }
3216
3217
3218 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003219 @RequiresPermission(anyOf = {
3220 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3221 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003222 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3223 try {
3224 mService.declareNetworkRequestUnfulfillable(request);
3225 } catch (RemoteException e) {
3226 throw e.rethrowFromSystemServer();
3227 }
3228 }
3229
Chalard Jean05ab6812018-05-02 21:14:54 +09003230 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3231 // of dependent changes that would conflict throughout the automerger graph. Having this
3232 // temporarily helps with the process of going through with all these dependent changes across
3233 // the entire tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05003234 /**
3235 * @hide
3236 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003237 * @return Network corresponding to NetworkAgent.
Paul Jensen31a94f42015-02-13 14:18:39 -05003238 */
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003239 @RequiresPermission(anyOf = {
3240 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3241 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003242 public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittid9696562020-01-12 22:28:37 +09003243 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Chalard Jeana11593c2020-02-21 19:37:21 +09003244 return registerNetworkAgent(messenger, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean05ab6812018-05-02 21:14:54 +09003245 }
3246
3247 /**
3248 * @hide
3249 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003250 * @return Network corresponding to NetworkAgent.
Chalard Jean05ab6812018-05-02 21:14:54 +09003251 */
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003252 @RequiresPermission(anyOf = {
3253 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3254 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003255 public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Chalard Jeana11593c2020-02-21 19:37:21 +09003256 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003257 try {
Lorenzo Colittid9696562020-01-12 22:28:37 +09003258 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, config, providerId);
Paul Jensen31a94f42015-02-13 14:18:39 -05003259 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003260 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05003261 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003262 }
3263
Robert Greenwalt9258c642014-03-26 16:47:06 -07003264 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003265 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3266 * changes. Should be extended by applications wanting notifications.
3267 *
3268 * A {@code NetworkCallback} is registered by calling
3269 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3270 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09003271 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09003272 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3273 * A {@code NetworkCallback} should be registered at most once at any time.
3274 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003275 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003276 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003277 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003278 * Called when the framework connects to a new network to evaluate whether it satisfies this
3279 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3280 * callback. There is no guarantee that this new network will satisfy any requests, or that
3281 * the network will stay connected for longer than the time necessary to evaluate it.
3282 * <p>
3283 * Most applications <b>should not</b> act on this callback, and should instead use
3284 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3285 * the framework in properly evaluating the network &mdash; for example, an application that
3286 * can automatically log in to a captive portal without user intervention.
3287 *
3288 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09003289 *
3290 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07003291 */
paulhu3d67f532019-03-22 16:35:06 +08003292 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003293
3294 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003295 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003296 * This callback may be called more than once if the {@link Network} that is
3297 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003298 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003299 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003300 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3301 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08003302 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003303 * @hide
3304 */
paulhu3d67f532019-03-22 16:35:06 +08003305 public void onAvailable(@NonNull Network network,
3306 @NonNull NetworkCapabilities networkCapabilities,
3307 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003308 // Internally only this method is called when a new network is available, and
3309 // it calls the callback in the same way and order that older versions used
3310 // to call so as not to change the behavior.
3311 onAvailable(network);
3312 if (!networkCapabilities.hasCapability(
3313 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3314 onNetworkSuspended(network);
3315 }
3316 onCapabilitiesChanged(network, networkCapabilities);
3317 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003318 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003319 }
3320
3321 /**
3322 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean599ce752019-08-30 16:27:28 +09003323 *
3324 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3325 * be available at the same time, and onAvailable will be called for each of these as they
3326 * appear.
3327 *
3328 * <p>For callbacks registered with {@link #requestNetwork} and
3329 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3330 * is the new best network for this request and is now tracked by this callback ; this
3331 * callback will no longer receive method calls about other networks that may have been
3332 * passed to this method previously. The previously-best network may have disconnected, or
3333 * it may still be around and the newly-best network may simply be better.
3334 *
3335 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3336 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3337 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3338 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3339 *
3340 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3341 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3342 * this callback as this is prone to race conditions (there is no guarantee the objects
3343 * returned by these methods will be current). Instead, wait for a call to
3344 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3345 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3346 * to be well-ordered with respect to other callbacks.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003347 *
3348 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003349 */
paulhu3d67f532019-03-22 16:35:06 +08003350 public void onAvailable(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003351
3352 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003353 * Called when the network is about to be lost, typically because there are no outstanding
3354 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3355 * with the new replacement network for graceful handover. This method is not guaranteed
3356 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3357 * network is suddenly disconnected.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003358 *
Chalard Jean599ce752019-08-30 16:27:28 +09003359 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3360 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3361 * this callback as this is prone to race conditions ; calling these methods while in a
3362 * callback may return an outdated or even a null object.
3363 *
3364 * @param network The {@link Network} that is about to be lost.
3365 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3366 * connected for graceful handover; note that the network may still
3367 * suffer a hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003368 */
paulhu3d67f532019-03-22 16:35:06 +08003369 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003370
3371 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003372 * Called when a network disconnects or otherwise no longer satisfies this request or
3373 * callback.
3374 *
3375 * <p>If the callback was registered with requestNetwork() or
3376 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3377 * returned by onAvailable() when that network is lost and no other network satisfies
3378 * the criteria of the request.
3379 *
3380 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3381 * each network which no longer satisfies the criteria of the callback.
3382 *
3383 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3384 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3385 * this callback as this is prone to race conditions ; calling these methods while in a
3386 * callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003387 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003388 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003389 */
paulhu3d67f532019-03-22 16:35:06 +08003390 public void onLost(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003391
3392 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003393 * Called if no network is found within the timeout time specified in
Etan Cohenddb720a2019-01-08 12:09:18 -08003394 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3395 * requested network request cannot be fulfilled (whether or not a timeout was
3396 * specified). When this callback is invoked the associated
Etan Cohenaebf17e2017-03-01 12:47:28 -08003397 * {@link NetworkRequest} will have already been removed and released, as if
3398 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003399 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003400 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003401
3402 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003403 * Called when the network corresponding to this request changes capabilities but still
3404 * satisfies the requested criteria.
3405 *
3406 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3407 * to be called immediately after {@link #onAvailable}.
3408 *
3409 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3410 * ConnectivityManager methods in this callback as this is prone to race conditions :
3411 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003412 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003413 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003414 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3415 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003416 */
paulhu3d67f532019-03-22 16:35:06 +08003417 public void onCapabilitiesChanged(@NonNull Network network,
3418 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003419
3420 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003421 * Called when the network corresponding to this request changes {@link LinkProperties}.
3422 *
3423 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3424 * to be called immediately after {@link #onAvailable}.
3425 *
3426 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3427 * ConnectivityManager methods in this callback as this is prone to race conditions :
3428 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003429 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003430 * @param network The {@link Network} whose link properties have changed.
3431 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003432 */
paulhu3d67f532019-03-22 16:35:06 +08003433 public void onLinkPropertiesChanged(@NonNull Network network,
3434 @NonNull LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003435
Robert Greenwalt8d482522015-06-24 13:23:42 -07003436 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003437 * Called when the network the framework connected to for this request suspends data
3438 * transmission temporarily.
3439 *
3440 * <p>This generally means that while the TCP connections are still live temporarily
3441 * network data fails to transfer. To give a specific example, this is used on cellular
3442 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3443 * means read operations on sockets on this network will block once the buffers are
3444 * drained, and write operations will block once the buffers are full.
3445 *
3446 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3447 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3448 * this callback as this is prone to race conditions (there is no guarantee the objects
3449 * returned by these methods will be current).
3450 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003451 * @hide
3452 */
paulhu3d67f532019-03-22 16:35:06 +08003453 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003454
3455 /**
3456 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003457 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3458 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean599ce752019-08-30 16:27:28 +09003459
3460 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3461 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3462 * this callback as this is prone to race conditions : calling these methods while in a
3463 * callback may return an outdated or even a null object.
3464 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003465 * @hide
3466 */
paulhu3d67f532019-03-22 16:35:06 +08003467 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003468
junyulai05986c62018-08-07 19:50:45 +08003469 /**
3470 * Called when access to the specified network is blocked or unblocked.
3471 *
Chalard Jean599ce752019-08-30 16:27:28 +09003472 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3473 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3474 * this callback as this is prone to race conditions : calling these methods while in a
3475 * callback may return an outdated or even a null object.
3476 *
junyulai05986c62018-08-07 19:50:45 +08003477 * @param network The {@link Network} whose blocked status has changed.
3478 * @param blocked The blocked status of this {@link Network}.
3479 */
junyulai0c666972019-03-04 22:45:36 +08003480 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai05986c62018-08-07 19:50:45 +08003481
Robert Greenwalt6078b502014-06-11 16:05:07 -07003482 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003483 }
3484
Hugo Benichicb883232017-05-11 13:16:17 +09003485 /**
3486 * Constant error codes used by ConnectivityService to communicate about failures and errors
3487 * across a Binder boundary.
3488 * @hide
3489 */
3490 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003491 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003492 }
3493
3494 /** @hide */
3495 public static class TooManyRequestsException extends RuntimeException {}
3496
3497 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3498 switch (e.errorCode) {
3499 case Errors.TOO_MANY_REQUESTS:
3500 return new TooManyRequestsException();
3501 default:
3502 Log.w(TAG, "Unknown service error code " + e.errorCode);
3503 return new RuntimeException(e);
3504 }
3505 }
3506
Robert Greenwalt9258c642014-03-26 16:47:06 -07003507 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003508 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003509 public static final int CALLBACK_PRECHECK = BASE + 1;
3510 /** @hide */
3511 public static final int CALLBACK_AVAILABLE = BASE + 2;
3512 /** @hide arg1 = TTL */
3513 public static final int CALLBACK_LOSING = BASE + 3;
3514 /** @hide */
3515 public static final int CALLBACK_LOST = BASE + 4;
3516 /** @hide */
3517 public static final int CALLBACK_UNAVAIL = BASE + 5;
3518 /** @hide */
3519 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3520 /** @hide */
3521 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003522 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003523 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003524 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003525 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003526 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003527 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003528 /** @hide */
3529 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003530
Erik Kline57faba92015-11-25 12:49:38 +09003531 /** @hide */
3532 public static String getCallbackName(int whichCallback) {
3533 switch (whichCallback) {
3534 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3535 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3536 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3537 case CALLBACK_LOST: return "CALLBACK_LOST";
3538 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3539 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3540 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003541 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3542 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3543 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003544 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003545 default:
3546 return Integer.toString(whichCallback);
3547 }
3548 }
3549
Robert Greenwalt562cc542014-05-15 18:07:26 -07003550 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003551 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003552 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003553
Hugo Benichid42650f2016-07-06 22:53:17 +09003554 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003555 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003556 }
3557
Hugo Benichi2583ef02017-02-02 17:02:36 +09003558 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003559 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003560 }
3561
Robert Greenwalt9258c642014-03-26 16:47:06 -07003562 @Override
3563 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003564 if (message.what == EXPIRE_LEGACY_REQUEST) {
3565 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3566 return;
3567 }
3568
3569 final NetworkRequest request = getObject(message, NetworkRequest.class);
3570 final Network network = getObject(message, Network.class);
3571 final NetworkCallback callback;
3572 synchronized (sCallbacks) {
3573 callback = sCallbacks.get(request);
Etan Cohen4a62d1d2019-05-21 12:06:04 -07003574 if (callback == null) {
3575 Log.w(TAG,
3576 "callback not found for " + getCallbackName(message.what) + " message");
3577 return;
3578 }
Etan Cohen9b09a162019-04-16 15:07:55 -07003579 if (message.what == CALLBACK_UNAVAIL) {
3580 sCallbacks.remove(request);
3581 callback.networkRequest = ALREADY_UNREGISTERED;
3582 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003583 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003584 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003585 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003586 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003587
Robert Greenwalt9258c642014-03-26 16:47:06 -07003588 switch (message.what) {
3589 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003590 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003591 break;
3592 }
3593 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003594 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3595 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003596 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003597 break;
3598 }
3599 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003600 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003601 break;
3602 }
3603 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003604 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003605 break;
3606 }
3607 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003608 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003609 break;
3610 }
3611 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003612 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3613 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003614 break;
3615 }
3616 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003617 LinkProperties lp = getObject(message, LinkProperties.class);
3618 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003619 break;
3620 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003621 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003622 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003623 break;
3624 }
3625 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003626 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003627 break;
3628 }
junyulai05986c62018-08-07 19:50:45 +08003629 case CALLBACK_BLK_CHANGED: {
3630 boolean blocked = message.arg1 != 0;
3631 callback.onBlockedStatusChanged(network, blocked);
3632 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003633 }
3634 }
3635
Hugo Benichid42650f2016-07-06 22:53:17 +09003636 private <T> T getObject(Message msg, Class<T> c) {
3637 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003638 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003639 }
3640
Hugo Benichi2583ef02017-02-02 17:02:36 +09003641 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003642 synchronized (sCallbacks) {
3643 if (sCallbackHandler == null) {
3644 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003645 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003646 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003647 }
3648 }
3649
Hugo Benichi6f260f32017-02-03 14:18:44 +09003650 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3651 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003652
Hugo Benichi6f260f32017-02-03 14:18:44 +09003653 private static final int LISTEN = 1;
3654 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003655
Hugo Benichi6f260f32017-02-03 14:18:44 +09003656 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3657 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003658 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003659 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003660 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003661 final NetworkRequest request;
Roshan Piuse38acab2020-01-16 12:17:17 -08003662 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003663 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003664 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003665 if (callback.networkRequest != null
3666 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003667 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3668 // and requests (http://b/20701525).
3669 Log.e(TAG, "NetworkCallback was already registered");
3670 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003671 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003672 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003673 if (action == LISTEN) {
Roshan Piuse38acab2020-01-16 12:17:17 -08003674 request = mService.listenForNetwork(
3675 need, messenger, binder, callingPackageName);
Paul Jensen7221cc32014-06-27 11:05:32 -04003676 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003677 request = mService.requestNetwork(
Roshan Piuse38acab2020-01-16 12:17:17 -08003678 need, messenger, timeoutMs, binder, legacyType, callingPackageName);
Paul Jensen7221cc32014-06-27 11:05:32 -04003679 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003680 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003681 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003682 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003683 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003684 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003685 } catch (RemoteException e) {
3686 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003687 } catch (ServiceSpecificException e) {
3688 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003689 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003690 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003691 }
3692
3693 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003694 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003695 *
markchien97c029e2020-03-18 21:16:15 +08003696 * This API is only for use in internal system code that requests networks with legacy type and
3697 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchienace1d342020-01-14 12:54:40 +08003698 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003699 *
markchienace1d342020-01-14 12:54:40 +08003700 * @param request {@link NetworkRequest} describing this request.
markchienace1d342020-01-14 12:54:40 +08003701 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3702 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3703 * be a positive value (i.e. >0).
3704 * @param legacyType to specify the network type(#TYPE_*).
3705 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien97c029e2020-03-18 21:16:15 +08003706 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3707 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003708 *
3709 * @hide
3710 */
markchienace1d342020-01-14 12:54:40 +08003711 @SystemApi
markchien97c029e2020-03-18 21:16:15 +08003712 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003713 public void requestNetwork(@NonNull NetworkRequest request,
markchien97c029e2020-03-18 21:16:15 +08003714 int timeoutMs, int legacyType, @NonNull Handler handler,
3715 @NonNull NetworkCallback networkCallback) {
3716 if (legacyType == TYPE_NONE) {
3717 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3718 }
Hugo Benichi2583ef02017-02-02 17:02:36 +09003719 CallbackHandler cbHandler = new CallbackHandler(handler);
3720 NetworkCapabilities nc = request.networkCapabilities;
3721 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003722 }
3723
3724 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003725 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003726 *
Chalard Jean599ce752019-08-30 16:27:28 +09003727 * <p>This method will attempt to find the best network that matches the passed
3728 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3729 * criteria. The platform will evaluate which network is the best at its own discretion.
3730 * Throughput, latency, cost per byte, policy, user preference and other considerations
3731 * may be factored in the decision of what is considered the best network.
3732 *
3733 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3734 * matching this request, while always attempting to match the request to a better network if
3735 * possible. If a better match is found, the platform will switch this request to the now-best
3736 * network and inform the app of the newly best network by invoking
3737 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3738 * will not try to maintain any other network than the best one currently matching the request:
3739 * a network not matching any network request may be disconnected at any time.
3740 *
3741 * <p>For example, an application could use this method to obtain a connected cellular network
3742 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3743 * radio to consume additional power. Or, an application could inform the system that it wants
3744 * a network supporting sending MMSes and have the system let it know about the currently best
3745 * MMS-supporting network through the provided {@link NetworkCallback}.
3746 *
3747 * <p>The status of the request can be followed by listening to the various callbacks described
3748 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3749 * used to direct traffic to the network (although accessing some networks may be subject to
3750 * holding specific permissions). Callers will learn about the specific characteristics of the
3751 * network through
3752 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3753 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3754 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3755 * matching the request at any given time; therefore when a better network matching the request
3756 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3757 * with the new network after which no further updates are given about the previously-best
3758 * network, unless it becomes the best again at some later time. All callbacks are invoked
3759 * in order on the same thread, which by default is a thread created by the framework running
3760 * in the app.
3761 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3762 * callbacks are invoked.
3763 *
3764 * <p>This{@link NetworkRequest} will live until released via
3765 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3766 * which point the system may let go of the network at any time.
3767 *
3768 * <p>A version of this method which takes a timeout is
3769 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3770 * wait for a limited amount of time for the network to become unavailable.
3771 *
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003772 * <p>It is presently unsupported to request a network with mutable
3773 * {@link NetworkCapabilities} such as
3774 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3775 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3776 * as these {@code NetworkCapabilities} represent states that a particular
3777 * network may never attain, and whether a network will attain these states
3778 * is unknown prior to bringing up the network so the framework does not
Chalard Jean599ce752019-08-30 16:27:28 +09003779 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003780 *
3781 * <p>This method requires the caller to hold either the
3782 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3783 * or the ability to modify system settings as determined by
3784 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003785 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003786 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003787 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3788 * the callback must not be shared - it uniquely specifies this request.
3789 * The callback is invoked on the default internal Handler.
Chalard Jean92c8b672019-05-13 15:13:58 +09003790 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3791 * @throws SecurityException if missing the appropriate permissions.
3792 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003793 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003794 public void requestNetwork(@NonNull NetworkRequest request,
3795 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003796 requestNetwork(request, networkCallback, getDefaultHandler());
3797 }
3798
3799 /**
3800 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3801 *
Chalard Jean599ce752019-08-30 16:27:28 +09003802 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3803 * but runs all the callbacks on the passed Handler.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003804 *
Chalard Jean599ce752019-08-30 16:27:28 +09003805 * <p>This method has the same permission requirements as
3806 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3807 * the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003808 *
3809 * @param request {@link NetworkRequest} describing this request.
3810 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3811 * the callback must not be shared - it uniquely specifies this request.
3812 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003813 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003814 public void requestNetwork(@NonNull NetworkRequest request,
3815 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003816 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien97c029e2020-03-18 21:16:15 +08003817 NetworkCapabilities nc = request.networkCapabilities;
3818 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003819 }
3820
3821 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003822 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3823 * by a timeout.
3824 *
3825 * This function behaves identically to the non-timed-out version
3826 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3827 * is not found within the given time (in milliseconds) the
3828 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3829 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3830 * not have to be released if timed-out (it is automatically released). Unregistering a
3831 * request that timed out is not an error.
3832 *
3833 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3834 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3835 * for that purpose. Calling this method will attempt to bring up the requested network.
3836 *
Chalard Jean599ce752019-08-30 16:27:28 +09003837 * <p>This method has the same permission requirements as
3838 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3839 * the same conditions.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003840 *
3841 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003842 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3843 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003844 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3845 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3846 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003847 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003848 public void requestNetwork(@NonNull NetworkRequest request,
3849 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003850 checkTimeout(timeoutMs);
markchien97c029e2020-03-18 21:16:15 +08003851 NetworkCapabilities nc = request.networkCapabilities;
3852 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3853 getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003854 }
3855
Hugo Benichi2583ef02017-02-02 17:02:36 +09003856 /**
3857 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3858 * by a timeout.
3859 *
Chalard Jean599ce752019-08-30 16:27:28 +09003860 * This method behaves identically to
3861 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3862 * on the passed Handler.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003863 *
Chalard Jean599ce752019-08-30 16:27:28 +09003864 * <p>This method has the same permission requirements as
3865 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} and throws the same exceptions
3866 * in the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003867 *
3868 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003869 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3870 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003871 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003872 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3873 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003874 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003875 public void requestNetwork(@NonNull NetworkRequest request,
3876 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003877 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003878 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien97c029e2020-03-18 21:16:15 +08003879 NetworkCapabilities nc = request.networkCapabilities;
3880 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003881 }
3882
3883 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003884 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003885 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003886 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003887 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003888 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3889 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003890 */
Erik Kline90e93072014-11-19 12:12:24 +09003891 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003892
3893 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003894 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003895 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003896 * {@link android.content.Intent#getParcelableExtra(String)}.
3897 */
Erik Kline90e93072014-11-19 12:12:24 +09003898 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003899
3900
3901 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003902 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003903 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003904 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003905 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003906 * the request may outlive the calling application and get called back when a suitable
3907 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003908 * <p>
3909 * The operation is an Intent broadcast that goes to a broadcast receiver that
3910 * you registered with {@link Context#registerReceiver} or through the
3911 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3912 * <p>
3913 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003914 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3915 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003916 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003917 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003918 * Intent to reserve the network or it will be released shortly after the Intent
3919 * is processed.
3920 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003921 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003922 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003923 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003924 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003925 * The request may be released normally by calling
3926 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003927 * <p>It is presently unsupported to request a network with either
3928 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3929 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3930 * as these {@code NetworkCapabilities} represent states that a particular
3931 * network may never attain, and whether a network will attain these states
3932 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003933 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003934 *
3935 * <p>This method requires the caller to hold either the
3936 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3937 * or the ability to modify system settings as determined by
3938 * {@link android.provider.Settings.System#canWrite}.</p>
3939 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003940 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003941 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003942 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003943 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean92c8b672019-05-13 15:13:58 +09003944 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3945 * @throws SecurityException if missing the appropriate permissions.
3946 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003947 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003948 public void requestNetwork(@NonNull NetworkRequest request,
3949 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003950 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003951 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003952 try {
Roshan Piuse38acab2020-01-16 12:17:17 -08003953 mService.pendingRequestForNetwork(
Qingxi Li9c5d8b92020-01-08 12:51:49 -08003954 request.networkCapabilities, operation, mContext.getOpPackageName());
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003955 } catch (RemoteException e) {
3956 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003957 } catch (ServiceSpecificException e) {
3958 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003959 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003960 }
3961
3962 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003963 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3964 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003965 * This method has the same behavior as
3966 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003967 * releasing network resources and disconnecting.
3968 *
3969 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3970 * PendingIntent passed to
3971 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3972 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3973 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003974 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003975 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003976 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003977 try {
3978 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003979 } catch (RemoteException e) {
3980 throw e.rethrowFromSystemServer();
3981 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003982 }
3983
Hugo Benichie7678512017-05-09 15:19:01 +09003984 private static void checkPendingIntentNotNull(PendingIntent intent) {
3985 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3986 }
3987
3988 private static void checkCallbackNotNull(NetworkCallback callback) {
3989 Preconditions.checkNotNull(callback, "null NetworkCallback");
3990 }
3991
3992 private static void checkTimeout(int timeoutMs) {
3993 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003994 }
3995
3996 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003997 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003998 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003999 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4000 * called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004001 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07004002 * @param request {@link NetworkRequest} describing this request.
4003 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4004 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004005 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004006 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004007 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004008 public void registerNetworkCallback(@NonNull NetworkRequest request,
4009 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004010 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4011 }
4012
4013 /**
4014 * Registers to receive notifications about all networks which satisfy the given
4015 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08004016 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4017 * called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004018 *
4019 * @param request {@link NetworkRequest} describing this request.
4020 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4021 * networks change state.
4022 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004023 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004024 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004025 public void registerNetworkCallback(@NonNull NetworkRequest request,
4026 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004027 CallbackHandler cbHandler = new CallbackHandler(handler);
4028 NetworkCapabilities nc = request.networkCapabilities;
4029 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004030 }
4031
4032 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04004033 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4034 * {@link NetworkRequest}.
4035 *
4036 * This function behaves identically to the version that takes a NetworkCallback, but instead
4037 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4038 * the request may outlive the calling application and get called back when a suitable
4039 * network is found.
4040 * <p>
4041 * The operation is an Intent broadcast that goes to a broadcast receiver that
4042 * you registered with {@link Context#registerReceiver} or through the
4043 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4044 * <p>
4045 * The operation Intent is delivered with two extras, a {@link Network} typed
4046 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4047 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4048 * the original requests parameters.
4049 * <p>
4050 * If there is already a request for this Intent registered (with the equality of
4051 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4052 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4053 * <p>
4054 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004055 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04004056 * @param request {@link NetworkRequest} describing this request.
4057 * @param operation Action to perform when the network is available (corresponds
4058 * to the {@link NetworkCallback#onAvailable} call. Typically
4059 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4060 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004061 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004062 public void registerNetworkCallback(@NonNull NetworkRequest request,
4063 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004064 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004065 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04004066 try {
Roshan Piuse38acab2020-01-16 12:17:17 -08004067 mService.pendingListenForNetwork(
Qingxi Li9c5d8b92020-01-08 12:51:49 -08004068 request.networkCapabilities, operation, mContext.getOpPackageName());
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004069 } catch (RemoteException e) {
4070 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09004071 } catch (ServiceSpecificException e) {
4072 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004073 }
Paul Jensen694f2b82015-06-17 14:15:39 -04004074 }
4075
4076 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004077 * Registers to receive notifications about changes in the system default network. The callbacks
4078 * will continue to be called until either the application exits or
4079 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09004080 *
4081 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4082 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004083 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09004084 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004085 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004086 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004087 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4088 }
4089
4090 /**
4091 * Registers to receive notifications about changes in the system default network. The callbacks
4092 * will continue to be called until either the application exits or
4093 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004094 *
4095 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4096 * system default network changes.
4097 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004098 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004099 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004100 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4101 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09004102 // This works because if the NetworkCapabilities are null,
4103 // ConnectivityService takes them from the default request.
4104 //
4105 // Since the capabilities are exactly the same as the default request's
4106 // capabilities, this request is guaranteed, at all times, to be
4107 // satisfied by the same network, if any, that satisfies the default
4108 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004109 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09004110 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4111 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09004112 }
4113
4114 /**
fengludb571472015-04-21 17:12:05 -07004115 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4116 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4117 * network connection for updated bandwidth information. The caller will be notified via
4118 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004119 * method assumes that the caller has previously called
4120 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4121 * changes.
fenglub15e72b2015-03-20 11:29:56 -07004122 *
fengluae519192015-04-27 14:28:04 -07004123 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07004124 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07004125 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004126 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004127 try {
fengludb571472015-04-21 17:12:05 -07004128 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07004129 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004130 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07004131 }
4132 }
4133
4134 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09004135 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004136 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4137 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4138 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09004139 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4140 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004141 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09004142 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4143 * triggering it as soon as this call returns.
4144 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07004145 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004146 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004147 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004148 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004149 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09004150 final List<NetworkRequest> reqs = new ArrayList<>();
4151 // Find all requests associated to this callback and stop callback triggers immediately.
4152 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4153 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09004154 Preconditions.checkArgument(networkCallback.networkRequest != null,
4155 "NetworkCallback was not registered");
Etan Cohen9b09a162019-04-16 15:07:55 -07004156 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4157 Log.d(TAG, "NetworkCallback was already unregistered");
4158 return;
4159 }
Hugo Benichidafed3d2017-03-06 09:17:06 +09004160 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4161 if (e.getValue() == networkCallback) {
4162 reqs.add(e.getKey());
4163 }
4164 }
4165 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4166 for (NetworkRequest r : reqs) {
4167 try {
4168 mService.releaseNetworkRequest(r);
4169 } catch (RemoteException e) {
4170 throw e.rethrowFromSystemServer();
4171 }
4172 // Only remove mapping if rpc was successful.
4173 sCallbacks.remove(r);
4174 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09004175 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004176 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004177 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004178
4179 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004180 * Unregisters a callback previously registered via
4181 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4182 *
4183 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4184 * PendingIntent passed to
4185 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4186 * Cannot be null.
4187 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004188 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09004189 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004190 releaseNetworkRequest(operation);
4191 }
4192
4193 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004194 * Informs the system whether it should switch to {@code network} regardless of whether it is
4195 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4196 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4197 * the system default network regardless of any other network that's currently connected. If
4198 * {@code always} is true, then the choice is remembered, so that the next time the user
4199 * connects to this network, the system will switch to it.
4200 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004201 * @param network The network to accept.
4202 * @param accept Whether to accept the network even if unvalidated.
4203 * @param always Whether to remember this choice in the future.
4204 *
4205 * @hide
4206 */
lucasline252a742019-03-12 13:08:03 +08004207 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004208 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4209 try {
4210 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004211 } catch (RemoteException e) {
4212 throw e.rethrowFromSystemServer();
4213 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004214 }
4215
4216 /**
lucasline252a742019-03-12 13:08:03 +08004217 * Informs the system whether it should consider the network as validated even if it only has
4218 * partial connectivity. If {@code accept} is true, then the network will be considered as
4219 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4220 * is remembered, so that the next time the user connects to this network, the system will
4221 * switch to it.
4222 *
4223 * @param network The network to accept.
4224 * @param accept Whether to consider the network as validated even if it has partial
4225 * connectivity.
4226 * @param always Whether to remember this choice in the future.
4227 *
4228 * @hide
4229 */
4230 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4231 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4232 try {
4233 mService.setAcceptPartialConnectivity(network, accept, always);
4234 } catch (RemoteException e) {
4235 throw e.rethrowFromSystemServer();
4236 }
4237 }
4238
4239 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004240 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4241 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4242 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4243 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4244 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004245 * @param network The network to accept.
4246 *
4247 * @hide
4248 */
lucasline252a742019-03-12 13:08:03 +08004249 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004250 public void setAvoidUnvalidated(Network network) {
4251 try {
4252 mService.setAvoidUnvalidated(network);
4253 } catch (RemoteException e) {
4254 throw e.rethrowFromSystemServer();
4255 }
4256 }
4257
4258 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004259 * Requests that the system open the captive portal app on the specified network.
4260 *
4261 * @param network The network to log into.
4262 *
4263 * @hide
4264 */
paulhua6af6b62019-08-12 16:25:11 +08004265 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004266 public void startCaptivePortalApp(Network network) {
4267 try {
4268 mService.startCaptivePortalApp(network);
4269 } catch (RemoteException e) {
4270 throw e.rethrowFromSystemServer();
4271 }
4272 }
4273
4274 /**
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004275 * Requests that the system open the captive portal app with the specified extras.
4276 *
4277 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4278 * corresponding permission.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004279 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004280 * @param appExtras Extras to include in the app start intent.
4281 * @hide
4282 */
4283 @SystemApi
4284 @TestApi
4285 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhud9736de2019-03-08 16:35:20 +08004286 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004287 try {
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004288 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004289 } catch (RemoteException e) {
4290 throw e.rethrowFromSystemServer();
4291 }
4292 }
4293
4294 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004295 * Determine whether the device is configured to avoid bad wifi.
4296 * @hide
4297 */
4298 @SystemApi
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004299 @RequiresPermission(anyOf = {
4300 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4301 android.Manifest.permission.NETWORK_STACK})
4302 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004303 try {
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004304 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004305 } catch (RemoteException e) {
4306 throw e.rethrowFromSystemServer();
4307 }
4308 }
4309
4310 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004311 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4312 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09004313 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4314 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004315 *
4316 * An example of such an operation might be a time-sensitive foreground activity, such as a
4317 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4318 */
4319 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4320
4321 /**
4322 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4323 * a backup channel for traffic that is primarily going over another network.
4324 *
4325 * An example might be maintaining backup connections to peers or servers for the purpose of
4326 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4327 * on backup paths should be negligible compared to the traffic on the main path.
4328 */
4329 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4330
4331 /**
4332 * It is acceptable to use metered data to improve network latency and performance.
4333 */
4334 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4335
4336 /**
4337 * Return value to use for unmetered networks. On such networks we currently set all the flags
4338 * to true.
4339 * @hide
4340 */
4341 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4342 MULTIPATH_PREFERENCE_HANDOVER |
4343 MULTIPATH_PREFERENCE_RELIABILITY |
4344 MULTIPATH_PREFERENCE_PERFORMANCE;
4345
4346 /** @hide */
4347 @Retention(RetentionPolicy.SOURCE)
4348 @IntDef(flag = true, value = {
4349 MULTIPATH_PREFERENCE_HANDOVER,
4350 MULTIPATH_PREFERENCE_RELIABILITY,
4351 MULTIPATH_PREFERENCE_PERFORMANCE,
4352 })
4353 public @interface MultipathPreference {
4354 }
4355
4356 /**
4357 * Provides a hint to the calling application on whether it is desirable to use the
4358 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4359 * for multipath data transfer on this network when it is not the system default network.
4360 * Applications desiring to use multipath network protocols should call this method before
4361 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004362 *
4363 * @param network The network on which the application desires to use multipath data.
4364 * If {@code null}, this method will return the a preference that will generally
4365 * apply to metered networks.
4366 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4367 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004368 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004369 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004370 try {
4371 return mService.getMultipathPreference(network);
4372 } catch (RemoteException e) {
4373 throw e.rethrowFromSystemServer();
4374 }
4375 }
4376
4377 /**
Stuart Scott984dc852015-03-30 13:17:11 -07004378 * Resets all connectivity manager settings back to factory defaults.
4379 * @hide
4380 */
paulhua6af6b62019-08-12 16:25:11 +08004381 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott984dc852015-03-30 13:17:11 -07004382 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07004383 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07004384 mService.factoryReset();
Automerger Merge Worker6112c822020-03-06 00:38:43 +00004385 mTetheringManager.stopAllTethering();
Stuart Scott984dc852015-03-30 13:17:11 -07004386 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004387 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07004388 }
4389 }
4390
4391 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004392 * Binds the current process to {@code network}. All Sockets created in the future
4393 * (and not explicitly bound via a bound SocketFactory from
4394 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4395 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4396 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4397 * work and all host name resolutions will fail. This is by design so an application doesn't
4398 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4399 * To clear binding pass {@code null} for {@code network}. Using individually bound
4400 * Sockets created by Network.getSocketFactory().createSocket() and
4401 * performing network-specific host name resolutions via
4402 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04004403 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004404 *
4405 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4406 * the current binding.
4407 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4408 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004409 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09004410 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04004411 // instantiated.
4412 return setProcessDefaultNetwork(network);
4413 }
4414
4415 /**
4416 * Binds the current process to {@code network}. All Sockets created in the future
4417 * (and not explicitly bound via a bound SocketFactory from
4418 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4419 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4420 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4421 * work and all host name resolutions will fail. This is by design so an application doesn't
4422 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4423 * To clear binding pass {@code null} for {@code network}. Using individually bound
4424 * Sockets created by Network.getSocketFactory().createSocket() and
4425 * performing network-specific host name resolutions via
4426 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4427 * {@code setProcessDefaultNetwork}.
4428 *
4429 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4430 * the current binding.
4431 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4432 * @deprecated This function can throw {@link IllegalStateException}. Use
4433 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4434 * is a direct replacement.
4435 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004436 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004437 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04004438 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004439 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4440
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09004441 if (netId != NETID_UNSET) {
4442 netId = network.getNetIdForResolv();
Paul Jensenc91b5342014-08-27 12:38:45 -04004443 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004444
4445 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4446 return false;
4447 }
4448
4449 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05004450 // Set HTTP proxy system properties to match network.
4451 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09004452 try {
4453 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4454 } catch (SecurityException e) {
4455 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4456 Log.e(TAG, "Can't set proxy properties", e);
4457 }
Paul Jensenc91b5342014-08-27 12:38:45 -04004458 // Must flush DNS cache as new network may have different DNS resolutions.
4459 InetAddress.clearDnsCache();
4460 // Must flush socket pool as idle sockets will be bound to previous network and may
4461 // cause subsequent fetches to be performed on old network.
4462 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04004463 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004464
4465 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004466 }
4467
4468 /**
4469 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004470 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004471 *
4472 * @return {@code Network} to which this process is bound, or {@code null}.
4473 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004474 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004475 public Network getBoundNetworkForProcess() {
4476 // Forcing callers to call thru non-static function ensures ConnectivityManager
4477 // instantiated.
4478 return getProcessDefaultNetwork();
4479 }
4480
4481 /**
4482 * Returns the {@link Network} currently bound to this process via
4483 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4484 *
4485 * @return {@code Network} to which this process is bound, or {@code null}.
4486 * @deprecated Using this function can lead to other functions throwing
4487 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4488 * {@code getBoundNetworkForProcess} is a direct replacement.
4489 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004490 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004491 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004492 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004493 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004494 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004495 return new Network(netId);
4496 }
4497
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004498 private void unsupportedStartingFrom(int version) {
4499 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004500 // The getApplicationInfo() call we make below is not supported in system context. Let
4501 // the call through here, and rely on the fact that ConnectivityService will refuse to
4502 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004503 return;
4504 }
4505
4506 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4507 throw new UnsupportedOperationException(
4508 "This method is not supported in target SDK version " + version + " and above");
4509 }
4510 }
4511
4512 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4513 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004514 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004515 // remove these exemptions. Note that this check is not secure, and apps can still access these
4516 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4517 // so is unsupported and may break in the future. http://b/22728205
4518 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004519 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004520 }
4521
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004522 /**
4523 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004524 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004525 *
4526 * @param network The {@link Network} to bind host resolutions from the current process to, or
4527 * {@code null} to clear the current binding.
4528 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4529 * @hide
4530 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4531 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004532 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004533 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004534 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004535 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004536 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004537 }
Felipe Leme1b103232016-01-22 09:44:57 -08004538
4539 /**
4540 * Device is not restricting metered network activity while application is running on
4541 * background.
4542 */
4543 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4544
4545 /**
4546 * Device is restricting metered network activity while application is running on background,
4547 * but application is allowed to bypass it.
4548 * <p>
4549 * In this state, application should take action to mitigate metered network access.
4550 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4551 */
4552 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4553
4554 /**
4555 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004556 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004557 * In this state, application should not try to use the network while running on background,
4558 * because it would be denied.
4559 */
4560 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4561
Felipe Leme9778f762016-01-27 14:46:39 -08004562 /**
4563 * A change in the background metered network activity restriction has occurred.
4564 * <p>
4565 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4566 * applies to them.
4567 * <p>
4568 * This is only sent to registered receivers, not manifest receivers.
4569 */
4570 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4571 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4572 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4573
Felipe Lemeecfccea2016-01-25 11:48:04 -08004574 /** @hide */
4575 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004576 @IntDef(flag = false, value = {
4577 RESTRICT_BACKGROUND_STATUS_DISABLED,
4578 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4579 RESTRICT_BACKGROUND_STATUS_ENABLED,
4580 })
Felipe Leme1b103232016-01-22 09:44:57 -08004581 public @interface RestrictBackgroundStatus {
4582 }
4583
4584 private INetworkPolicyManager getNetworkPolicyManager() {
4585 synchronized (this) {
4586 if (mNPManager != null) {
4587 return mNPManager;
4588 }
4589 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4590 .getService(Context.NETWORK_POLICY_SERVICE));
4591 return mNPManager;
4592 }
4593 }
4594
4595 /**
4596 * Determines if the calling application is subject to metered network restrictions while
4597 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004598 *
4599 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4600 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4601 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004602 */
4603 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4604 try {
4605 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4606 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004607 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004608 }
4609 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004610
4611 /**
4612 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004613 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4614 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004615 *
4616 * @return Hash of network watchlist config file. Null if config does not exist.
4617 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004618 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004619 public byte[] getNetworkWatchlistConfigHash() {
4620 try {
4621 return mService.getNetworkWatchlistConfigHash();
4622 } catch (RemoteException e) {
4623 Log.e(TAG, "Unable to get watchlist config hash");
4624 throw e.rethrowFromSystemServer();
4625 }
4626 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004627
4628 /**
4629 * Returns the {@code uid} of the owner of a network connection.
4630 *
Benedict Wong5d50ce82020-01-20 22:14:59 -08004631 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4632 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004633 * @param local The local {@link InetSocketAddress} of a connection.
4634 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004635 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong5d50ce82020-01-20 22:14:59 -08004636 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4637 * android.os.Process#INVALID_UID} if the connection is not found.
4638 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4639 * user.
4640 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004641 */
Benedict Wong5d50ce82020-01-20 22:14:59 -08004642 public int getConnectionOwnerUid(
4643 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004644 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4645 try {
4646 return mService.getConnectionOwnerUid(connectionInfo);
4647 } catch (RemoteException e) {
4648 throw e.rethrowFromSystemServer();
4649 }
4650 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004651
4652 private void printStackTrace() {
4653 if (DEBUG) {
4654 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4655 final StringBuffer sb = new StringBuffer();
4656 for (int i = 3; i < callStack.length; i++) {
4657 final String stackTrace = callStack[i].toString();
4658 if (stackTrace == null || stackTrace.contains("android.os")) {
4659 break;
4660 }
4661 sb.append(" [").append(stackTrace).append("]");
4662 }
4663 Log.d(TAG, "StackLog:" + sb.toString());
4664 }
4665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004666}