blob: 7332ede0b997a9248d5c9fbac6780fa325228a80 [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 Jean1d2d35d2020-03-25 01:24:04 +0900708 /**
709 * @deprecated Use {@link NetworkCapabilities} instead.
710 * @hide
711 */
712 @Deprecated
713 @Retention(RetentionPolicy.SOURCE)
714 @IntDef(prefix = { "TYPE_" }, value = {
715 TYPE_NONE,
716 TYPE_MOBILE,
717 TYPE_WIFI,
718 TYPE_MOBILE_MMS,
719 TYPE_MOBILE_SUPL,
720 TYPE_MOBILE_DUN,
721 TYPE_MOBILE_HIPRI,
722 TYPE_WIMAX,
723 TYPE_BLUETOOTH,
724 TYPE_DUMMY,
725 TYPE_ETHERNET,
726 TYPE_MOBILE_FOTA,
727 TYPE_MOBILE_IMS,
728 TYPE_MOBILE_CBS,
729 TYPE_WIFI_P2P,
730 TYPE_MOBILE_IA,
731 TYPE_MOBILE_EMERGENCY,
732 TYPE_PROXY,
733 TYPE_VPN,
734 TYPE_TEST
735 })
736 public @interface LegacyNetworkType {}
737
Chalard Jeanc06d7882019-11-21 14:48:00 +0900738 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
739 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
740 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
741 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
742 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
743
Robert Greenwalt8283f882014-07-07 17:09:01 -0700744 /** {@hide} */
Benedict Wong89ce5e32018-11-14 17:40:55 -0800745 public static final int MAX_RADIO_TYPE = TYPE_TEST;
746
747 /** {@hide} */
748 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749
Hugo Benichi16f0a942017-06-20 14:07:59 +0900750 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
751
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800752 /**
753 * If you want to set the default network preference,you can directly
754 * change the networkAttributes array in framework's config.xml.
755 *
756 * @deprecated Since we support so many more networks now, the single
757 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800758 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800759 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800760 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800761 * from an App.
762 */
763 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
765
Jeff Sharkey625239a2012-09-26 22:03:49 -0700766 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700767 * @hide
768 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900769 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700770
Paul Jensen5d59e782014-07-11 12:28:19 -0400771 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900772 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
773 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean4d660112018-06-04 16:52:49 +0900774 * registered from those that were already unregistered.
Hugo Benichi31c176d2017-06-17 13:14:12 +0900775 * @hide
776 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900777 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900778 new NetworkRequest.Builder().clearCapabilities().build();
779
780 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400781 * A NetID indicating no Network is selected.
782 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
783 * @hide
784 */
785 public static final int NETID_UNSET = 0;
786
Erik Kline4d092232017-10-30 15:29:44 +0900787 /**
788 * Private DNS Mode values.
789 *
790 * The "private_dns_mode" global setting stores a String value which is
791 * expected to be one of the following.
792 */
793
794 /**
795 * @hide
796 */
797 public static final String PRIVATE_DNS_MODE_OFF = "off";
798 /**
799 * @hide
800 */
801 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
802 /**
803 * @hide
804 */
805 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
806 /**
807 * The default Private DNS mode.
808 *
809 * This may change from release to release or may become dependent upon
810 * the capabilities of the underlying platform.
811 *
812 * @hide
813 */
Erik Kline19841792018-05-16 16:41:57 +0900814 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline4d092232017-10-30 15:29:44 +0900815
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900816 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700817 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500818 /**
819 * A kludge to facilitate static access where a Context pointer isn't available, like in the
820 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
821 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
822 * methods that take a Context argument.
823 */
824 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900826 private final Context mContext;
827
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800828 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800829 private INetworkPolicyManager mNPManager;
Automerger Merge Worker6112c822020-03-06 00:38:43 +0000830 private final TetheringManager mTetheringManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800831
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800832 /**
833 * Tests if a given integer represents a valid network type.
834 * @param networkType the type to be tested
835 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400836 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
837 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800838 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700839 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700840 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900841 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
843
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800844 /**
845 * Returns a non-localized string representing a given network type.
846 * ONLY used for debugging output.
847 * @param type the type needing naming
848 * @return a String for the given type, or a string version of the type ("87")
849 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900850 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800851 * {@hide}
852 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900853 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100854 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700855 public static String getNetworkTypeName(int type) {
856 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900857 case TYPE_NONE:
858 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700859 case TYPE_MOBILE:
860 return "MOBILE";
861 case TYPE_WIFI:
862 return "WIFI";
863 case TYPE_MOBILE_MMS:
864 return "MOBILE_MMS";
865 case TYPE_MOBILE_SUPL:
866 return "MOBILE_SUPL";
867 case TYPE_MOBILE_DUN:
868 return "MOBILE_DUN";
869 case TYPE_MOBILE_HIPRI:
870 return "MOBILE_HIPRI";
871 case TYPE_WIMAX:
872 return "WIMAX";
873 case TYPE_BLUETOOTH:
874 return "BLUETOOTH";
875 case TYPE_DUMMY:
876 return "DUMMY";
877 case TYPE_ETHERNET:
878 return "ETHERNET";
879 case TYPE_MOBILE_FOTA:
880 return "MOBILE_FOTA";
881 case TYPE_MOBILE_IMS:
882 return "MOBILE_IMS";
883 case TYPE_MOBILE_CBS:
884 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700885 case TYPE_WIFI_P2P:
886 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700887 case TYPE_MOBILE_IA:
888 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700889 case TYPE_MOBILE_EMERGENCY:
890 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500891 case TYPE_PROXY:
892 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900893 case TYPE_VPN:
894 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700895 default:
896 return Integer.toString(type);
897 }
898 }
899
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800900 /**
901 * Checks if a given type uses the cellular data connection.
902 * This should be replaced in the future by a network property.
903 * @param networkType the type to check
904 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900905 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800906 * {@hide}
907 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900908 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900909 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700910 public static boolean isNetworkTypeMobile(int networkType) {
911 switch (networkType) {
912 case TYPE_MOBILE:
913 case TYPE_MOBILE_MMS:
914 case TYPE_MOBILE_SUPL:
915 case TYPE_MOBILE_DUN:
916 case TYPE_MOBILE_HIPRI:
917 case TYPE_MOBILE_FOTA:
918 case TYPE_MOBILE_IMS:
919 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700920 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700921 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700922 return true;
923 default:
924 return false;
925 }
926 }
927
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800928 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700929 * Checks if the given network type is backed by a Wi-Fi radio.
930 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900931 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700932 * @hide
933 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900934 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700935 public static boolean isNetworkTypeWifi(int networkType) {
936 switch (networkType) {
937 case TYPE_WIFI:
938 case TYPE_WIFI_P2P:
939 return true;
940 default:
941 return false;
942 }
943 }
944
945 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800946 * Specifies the preferred network type. When the device has more
947 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800948 *
949 * @param preference the network type to prefer over all others. It is
950 * unspecified what happens to the old preferred network in the
951 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700952 * @deprecated Functionality has been removed as it no longer makes sense,
953 * with many more than two networks - we'd need an array to express
954 * preference. Instead we use dynamic network properties of
955 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800956 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700957 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 }
960
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800961 /**
962 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800963 *
964 * @return an integer representing the preferred network type
965 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700966 * @deprecated Functionality has been removed as it no longer makes sense,
967 * with many more than two networks - we'd need an array to express
968 * preference. Instead we use dynamic network properties of
969 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800970 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700971 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600972 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700974 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976
Scott Main671644c2011-10-06 19:02:28 -0700977 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800978 * Returns details about the currently active default data network. When
979 * connected, this network is the default route for outgoing connections.
980 * You should always check {@link NetworkInfo#isConnected()} before initiating
981 * network traffic. This may return {@code null} when there is no default
982 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900983 * Note that if the default network is a VPN, this method will return the
984 * NetworkInfo for one of its underlying networks instead, or null if the
985 * VPN agent did not specify any. Apps interested in learning about VPNs
986 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800987 *
988 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500989 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800990 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700991 */
junyulai3822c8a2018-12-13 12:47:51 +0800992 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600993 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900994 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 public NetworkInfo getActiveNetworkInfo() {
996 try {
997 return mService.getActiveNetworkInfo();
998 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700999 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 }
1001 }
1002
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001003 /**
Paul Jensen31a94f42015-02-13 14:18:39 -05001004 * Returns a {@link Network} object corresponding to the currently active
1005 * default data network. In the event that the current active default data
1006 * network disconnects, the returned {@code Network} object will no longer
1007 * be usable. This will return {@code null} when there is no default
1008 * network.
1009 *
1010 * @return a {@link Network} object for the current default network or
1011 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -05001012 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001013 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001014 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -05001015 public Network getActiveNetwork() {
1016 try {
1017 return mService.getActiveNetwork();
1018 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001019 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05001020 }
1021 }
1022
1023 /**
Robin Leed2baf792016-03-24 12:07:00 +00001024 * Returns a {@link Network} object corresponding to the currently active
1025 * default data network for a specific UID. In the event that the default data
1026 * network disconnects, the returned {@code Network} object will no longer
1027 * be usable. This will return {@code null} when there is no default
1028 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +00001029 *
1030 * @return a {@link Network} object for the current default network for the
1031 * given UID or {@code null} if no default network is currently active
1032 *
1033 * @hide
1034 */
paulhua6af6b62019-08-12 16:25:11 +08001035 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001036 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +00001037 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001038 return getActiveNetworkForUid(uid, false);
1039 }
1040
1041 /** {@hide} */
1042 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001043 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001044 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001045 } catch (RemoteException e) {
1046 throw e.rethrowFromSystemServer();
1047 }
1048 }
1049
1050 /**
Charles He36738632017-05-15 17:07:18 +01001051 * Checks if a VPN app supports always-on mode.
1052 *
1053 * In order to support the always-on feature, an app has to
1054 * <ul>
1055 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +01001056 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
1057 * meta-data field.
Charles He36738632017-05-15 17:07:18 +01001058 * </ul>
1059 *
1060 * @param userId The identifier of the user for whom the VPN app is installed.
1061 * @param vpnPackage The canonical package name of the VPN app.
1062 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
1063 * @hide
1064 */
1065 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1066 try {
1067 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1068 } catch (RemoteException e) {
1069 throw e.rethrowFromSystemServer();
1070 }
1071 }
1072
1073 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001074 * Configures an always-on VPN connection through a specific application.
1075 * This connection is automatically granted and persisted after a reboot.
1076 *
1077 * <p>The designated package should declare a {@link VpnService} in its
1078 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1079 * otherwise the call will fail.
1080 *
1081 * @param userId The identifier of the user to set an always-on VPN for.
1082 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1083 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001084 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1085 * {@code false} otherwise.
Pavel Grafova462bcb2019-01-25 08:50:06 +00001086 * @param lockdownWhitelist The list of packages that are allowed to access network directly
1087 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
1088 * this method must be called when a package that should be whitelisted is installed or
1089 * uninstalled.
Robin Lee244ce8e2016-01-05 18:03:46 +00001090 * @return {@code true} if the package is set as always-on VPN controller;
1091 * {@code false} otherwise.
1092 * @hide
1093 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001094 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leedc679712016-05-03 13:23:03 +01001095 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001096 boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001097 try {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001098 return mService.setAlwaysOnVpnPackage(
1099 userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
Robin Lee244ce8e2016-01-05 18:03:46 +00001100 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001101 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001102 }
1103 }
1104
Pavel Grafova462bcb2019-01-25 08:50:06 +00001105 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001106 * Returns the package name of the currently set always-on VPN application.
1107 * If there is no always-on VPN set, or the VPN is provided by the system instead
1108 * of by an app, {@code null} will be returned.
1109 *
1110 * @return Package name of VPN controller responsible for always-on VPN,
1111 * or {@code null} if none is set.
1112 * @hide
1113 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001114 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee244ce8e2016-01-05 18:03:46 +00001115 public String getAlwaysOnVpnPackageForUser(int userId) {
1116 try {
1117 return mService.getAlwaysOnVpnPackage(userId);
1118 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001119 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001120 }
1121 }
1122
1123 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001124 * @return whether always-on VPN is in lockdown mode.
1125 *
1126 * @hide
1127 **/
1128 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1129 public boolean isVpnLockdownEnabled(int userId) {
1130 try {
1131 return mService.isVpnLockdownEnabled(userId);
1132 } catch (RemoteException e) {
1133 throw e.rethrowFromSystemServer();
1134 }
1135
1136 }
1137
1138 /**
1139 * @return the list of packages that are allowed to access network when always-on VPN is in
1140 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1141 *
1142 * @hide
1143 **/
1144 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1145 public List<String> getVpnLockdownWhitelist(int userId) {
1146 try {
1147 return mService.getVpnLockdownWhitelist(userId);
1148 } catch (RemoteException e) {
1149 throw e.rethrowFromSystemServer();
1150 }
1151 }
1152
1153 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001154 * Returns details about the currently active default data network
1155 * for a given uid. This is for internal use only to avoid spying
1156 * other apps.
1157 *
1158 * @return a {@link NetworkInfo} object for the current default network
1159 * for the given uid or {@code null} if no default network is
1160 * available for the specified uid.
1161 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001162 * {@hide}
1163 */
paulhua6af6b62019-08-12 16:25:11 +08001164 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001165 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001166 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001167 return getActiveNetworkInfoForUid(uid, false);
1168 }
1169
1170 /** {@hide} */
1171 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001172 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001173 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001174 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001175 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001176 }
1177 }
1178
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001179 /**
1180 * Returns connection status information about a particular
1181 * network type.
1182 *
1183 * @param networkType integer specifying which networkType in
1184 * which you're interested.
1185 * @return a {@link NetworkInfo} object for the requested
1186 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001187 * supported by the device. If {@code networkType} is
1188 * TYPE_VPN and a VPN is active for the calling app,
1189 * then this method will try to return one of the
1190 * underlying networks for the VPN or null if the
1191 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001192 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001193 * @deprecated This method does not support multiple connected networks
1194 * of the same type. Use {@link #getAllNetworks} and
1195 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001196 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001197 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001198 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001199 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 public NetworkInfo getNetworkInfo(int networkType) {
1201 try {
1202 return mService.getNetworkInfo(networkType);
1203 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001204 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 }
1206 }
1207
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001208 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001209 * Returns connection status information about a particular
1210 * Network.
1211 *
1212 * @param network {@link Network} specifying which network
1213 * in which you're interested.
1214 * @return a {@link NetworkInfo} object for the requested
1215 * network or {@code null} if the {@code Network}
1216 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001217 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001218 */
junyulai3822c8a2018-12-13 12:47:51 +08001219 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001220 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001221 @Nullable
1222 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001223 return getNetworkInfoForUid(network, Process.myUid(), false);
1224 }
1225
1226 /** {@hide} */
1227 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001229 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001230 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001231 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001232 }
1233 }
1234
1235 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001236 * Returns connection status information about all network
1237 * types supported by the device.
1238 *
1239 * @return an array of {@link NetworkInfo} objects. Check each
1240 * {@link NetworkInfo#getType} for which type each applies.
1241 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001242 * @deprecated This method does not support multiple connected networks
1243 * of the same type. Use {@link #getAllNetworks} and
1244 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001245 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001246 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001247 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001248 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 public NetworkInfo[] getAllNetworkInfo() {
1250 try {
1251 return mService.getAllNetworkInfo();
1252 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001253 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 }
1255 }
1256
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001257 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001258 * Returns the {@link Network} object currently serving a given type, or
1259 * null if the given type is not connected.
1260 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001261 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001262 * @deprecated This method does not support multiple connected networks
1263 * of the same type. Use {@link #getAllNetworks} and
1264 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001265 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001266 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001267 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001268 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001269 public Network getNetworkForType(int networkType) {
1270 try {
1271 return mService.getNetworkForType(networkType);
1272 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001273 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001274 }
1275 }
1276
1277 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001278 * Returns an array of all {@link Network} currently tracked by the
1279 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001280 *
1281 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001282 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001283 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001284 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001285 public Network[] getAllNetworks() {
1286 try {
1287 return mService.getAllNetworks();
1288 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001289 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001290 }
1291 }
1292
1293 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001294 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001295 * the Networks that applications run by the given user will use by default.
1296 * @hide
1297 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001298 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001299 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1300 try {
Qingxi Li9c5d8b92020-01-08 12:51:49 -08001301 return mService.getDefaultNetworkCapabilitiesForUser(
1302 userId, mContext.getOpPackageName());
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001303 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001304 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001305 }
1306 }
1307
1308 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001309 * Returns the IP information for the current default network.
1310 *
1311 * @return a {@link LinkProperties} object describing the IP info
1312 * for the current default network, or {@code null} if there
1313 * is no current default network.
1314 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001315 * {@hide}
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001316 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1317 * value of {@link #getActiveNetwork()} instead. In particular,
1318 * this method will return non-null LinkProperties even if the
1319 * app is blocked by policy from using this network.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001320 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001321 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001322 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001323 public LinkProperties getActiveLinkProperties() {
1324 try {
1325 return mService.getActiveLinkProperties();
1326 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001327 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001328 }
1329 }
1330
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001331 /**
1332 * Returns the IP information for a given network type.
1333 *
1334 * @param networkType the network type of interest.
1335 * @return a {@link LinkProperties} object describing the IP info
1336 * for the given networkType, or {@code null} if there is
1337 * no current default network.
1338 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001339 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001340 * @deprecated This method does not support multiple connected networks
1341 * of the same type. Use {@link #getAllNetworks},
1342 * {@link #getNetworkInfo(android.net.Network)}, and
1343 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001344 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001345 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001346 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09001347 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001348 public LinkProperties getLinkProperties(int networkType) {
1349 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001350 return mService.getLinkPropertiesForType(networkType);
1351 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001352 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001353 }
1354 }
1355
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001356 /**
1357 * Get the {@link LinkProperties} for the given {@link Network}. This
1358 * will return {@code null} if the network is unknown.
1359 *
1360 * @param network The {@link Network} object identifying the network in question.
1361 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001362 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001363 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001364 @Nullable
1365 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001366 try {
1367 return mService.getLinkProperties(network);
1368 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001369 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001370 }
1371 }
1372
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001373 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001374 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001375 * will return {@code null} if the network is unknown.
1376 *
1377 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001378 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001379 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001380 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001381 @Nullable
1382 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001383 try {
Qingxi Li9c5d8b92020-01-08 12:51:49 -08001384 return mService.getNetworkCapabilities(network, mContext.getOpPackageName());
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001385 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001386 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001387 }
1388 }
1389
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001390 /**
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001391 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainib7c24872016-01-04 12:16:14 -08001392 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1393 * portal is present.
1394 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1395 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1396 *
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001397 * The system network validation may be using different strategies to detect captive portals,
1398 * so this method does not necessarily return a URL used by the system. It only returns a URL
1399 * that may be relevant for other components trying to detect captive portals.
paulhua6af6b62019-08-12 16:25:11 +08001400 *
Udam Sainib7c24872016-01-04 12:16:14 -08001401 * @hide
paulhua6af6b62019-08-12 16:25:11 +08001402 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1403 * system.
Udam Sainib7c24872016-01-04 12:16:14 -08001404 */
paulhua6af6b62019-08-12 16:25:11 +08001405 @Deprecated
Udam Sainib7c24872016-01-04 12:16:14 -08001406 @SystemApi
paulhua6af6b62019-08-12 16:25:11 +08001407 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainib7c24872016-01-04 12:16:14 -08001408 public String getCaptivePortalServerUrl() {
1409 try {
1410 return mService.getCaptivePortalServerUrl();
1411 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001412 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001413 }
1414 }
1415
1416 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 * Tells the underlying networking system that the caller wants to
1418 * begin using the named feature. The interpretation of {@code feature}
1419 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001420 *
1421 * <p>This method requires the caller to hold either the
1422 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1423 * or the ability to modify system settings as determined by
1424 * {@link android.provider.Settings.System#canWrite}.</p>
1425 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 * @param networkType specifies which network the request pertains to
1427 * @param feature the name of the feature to be used
1428 * @return an integer value representing the outcome of the request.
1429 * The interpretation of this value is specific to each networking
1430 * implementation+feature combination, except that the value {@code -1}
1431 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001432 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001433 * @deprecated Deprecated in favor of the cleaner
1434 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001435 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001436 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001437 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001439 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001441 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001442 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1443 if (netCap == null) {
1444 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1445 feature);
Chalard Jeanc06d7882019-11-21 14:48:00 +09001446 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001447 }
1448
1449 NetworkRequest request = null;
1450 synchronized (sLegacyRequests) {
1451 LegacyRequest l = sLegacyRequests.get(netCap);
1452 if (l != null) {
1453 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1454 renewRequestLocked(l);
1455 if (l.currentNetwork != null) {
Chalard Jeanc06d7882019-11-21 14:48:00 +09001456 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001457 } else {
Chalard Jeanc06d7882019-11-21 14:48:00 +09001458 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001459 }
1460 }
1461
1462 request = requestNetworkForFeatureLocked(netCap);
1463 }
1464 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001465 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanc06d7882019-11-21 14:48:00 +09001466 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001467 } else {
1468 Log.d(TAG, " request Failed");
Chalard Jeanc06d7882019-11-21 14:48:00 +09001469 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
1471 }
1472
1473 /**
1474 * Tells the underlying networking system that the caller is finished
1475 * using the named feature. The interpretation of {@code feature}
1476 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001477 *
1478 * <p>This method requires the caller to hold either the
1479 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1480 * or the ability to modify system settings as determined by
1481 * {@link android.provider.Settings.System#canWrite}.</p>
1482 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 * @param networkType specifies which network the request pertains to
1484 * @param feature the name of the feature that is no longer needed
1485 * @return an integer value representing the outcome of the request.
1486 * The interpretation of this value is specific to each networking
1487 * implementation+feature combination, except that the value {@code -1}
1488 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001489 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001490 * @deprecated Deprecated in favor of the cleaner
1491 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001492 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001493 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001494 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001496 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001498 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001499 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1500 if (netCap == null) {
1501 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1502 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 return -1;
1504 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001505
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001506 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001507 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001508 }
1509 return 1;
1510 }
1511
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001512 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001513 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1514 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001515 switch (feature) {
1516 case "enableCBS":
1517 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1518 case "enableDUN":
1519 case "enableDUNAlways":
1520 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1521 case "enableFOTA":
1522 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1523 case "enableHIPRI":
1524 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1525 case "enableIMS":
1526 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1527 case "enableMMS":
1528 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1529 case "enableSUPL":
1530 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1531 default:
1532 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001533 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001534 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1535 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001536 }
1537 return null;
1538 }
1539
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001540 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001541 if (netCap == null) return TYPE_NONE;
1542 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1543 return TYPE_MOBILE_CBS;
1544 }
1545 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1546 return TYPE_MOBILE_IMS;
1547 }
1548 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1549 return TYPE_MOBILE_FOTA;
1550 }
1551 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1552 return TYPE_MOBILE_DUN;
1553 }
1554 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1555 return TYPE_MOBILE_SUPL;
1556 }
1557 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1558 return TYPE_MOBILE_MMS;
1559 }
1560 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1561 return TYPE_MOBILE_HIPRI;
1562 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001563 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1564 return TYPE_WIFI_P2P;
1565 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001566 return TYPE_NONE;
1567 }
1568
1569 private static class LegacyRequest {
1570 NetworkCapabilities networkCapabilities;
1571 NetworkRequest networkRequest;
1572 int expireSequenceNumber;
1573 Network currentNetwork;
1574 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001575
1576 private void clearDnsBinding() {
1577 if (currentNetwork != null) {
1578 currentNetwork = null;
1579 setProcessDefaultNetworkForHostResolution(null);
1580 }
1581 }
1582
Robert Greenwalt6078b502014-06-11 16:05:07 -07001583 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001584 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001585 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001586 currentNetwork = network;
1587 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001588 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001589 }
1590 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001591 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001592 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001593 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1594 }
1595 };
1596 }
1597
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001598 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001599 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1600 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001601
1602 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1603 synchronized (sLegacyRequests) {
1604 LegacyRequest l = sLegacyRequests.get(netCap);
1605 if (l != null) return l.networkRequest;
1606 }
1607 return null;
1608 }
1609
1610 private void renewRequestLocked(LegacyRequest l) {
1611 l.expireSequenceNumber++;
1612 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1613 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1614 }
1615
1616 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1617 int ourSeqNum = -1;
1618 synchronized (sLegacyRequests) {
1619 LegacyRequest l = sLegacyRequests.get(netCap);
1620 if (l == null) return;
1621 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001622 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001623 }
1624 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1625 }
1626
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001627 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001628 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1629 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001630 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001631 try {
1632 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001633 } catch (RemoteException e) {
1634 throw e.rethrowFromSystemServer();
1635 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001636 LegacyRequest l = new LegacyRequest();
1637 l.networkCapabilities = netCap;
1638 l.delay = delay;
1639 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001640 l.networkRequest = sendRequestForNetwork(
1641 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001642 if (l.networkRequest == null) return null;
1643 sLegacyRequests.put(netCap, l);
1644 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1645 return l.networkRequest;
1646 }
1647
1648 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1649 if (delay >= 0) {
1650 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001651 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001652 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1653 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001654 }
1655 }
1656
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001657 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001658 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1659 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001660 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001661 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001662 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001663 if (l == null) return false;
1664 unregisterNetworkCallback(l.networkCallback);
1665 l.clearDnsBinding();
1666 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 }
1668
Erik Kline35bf06c2017-01-26 18:08:28 +09001669 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1670 static {
1671 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1672 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1673 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1674 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1675 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1676 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1677 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1678 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1679 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1680 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1681 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1682 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1683 }
1684
1685 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1686 static {
1687 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1688 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1689 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1690 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1691 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1692 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1693 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1694 }
1695
1696 /**
1697 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1698 * instance suitable for registering a request or callback. Throws an
1699 * IllegalArgumentException if no mapping from the legacy type to
1700 * NetworkCapabilities is known.
1701 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001702 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1703 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001704 * @hide
1705 */
1706 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1707 final NetworkCapabilities nc = new NetworkCapabilities();
1708
1709 // Map from type to transports.
1710 final int NOT_FOUND = -1;
1711 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001712 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001713 nc.addTransportType(transport);
1714
1715 // Map from type to capabilities.
1716 nc.addCapability(sLegacyTypeToCapability.get(
1717 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1718 nc.maybeMarkCapabilitiesRestricted();
1719 return nc;
1720 }
1721
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001722 /** @hide */
1723 public static class PacketKeepaliveCallback {
Artur Satayev751e5512019-11-15 19:12:49 +00001724 @UnsupportedAppUsage
1725 public PacketKeepaliveCallback() {
1726 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001727 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001728 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001729 public void onStarted() {}
1730 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001731 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001732 public void onStopped() {}
1733 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001734 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001735 public void onError(int error) {}
1736 }
1737
1738 /**
1739 * Allows applications to request that the system periodically send specific packets on their
1740 * behalf, using hardware offload to save battery power.
1741 *
1742 * To request that the system send keepalives, call one of the methods that return a
1743 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1744 * passing in a non-null callback. If the callback is successfully started, the callback's
1745 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1746 * specifying one of the {@code ERROR_*} constants in this class.
1747 *
Chalard Jean4d660112018-06-04 16:52:49 +09001748 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1749 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1750 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001751 *
junyulai48eac1d42018-12-27 17:25:29 +08001752 * @deprecated Use {@link SocketKeepalive} instead.
1753 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001754 * @hide
1755 */
1756 public class PacketKeepalive {
1757
1758 private static final String TAG = "PacketKeepalive";
1759
1760 /** @hide */
1761 public static final int SUCCESS = 0;
1762
1763 /** @hide */
1764 public static final int NO_KEEPALIVE = -1;
1765
1766 /** @hide */
1767 public static final int BINDER_DIED = -10;
1768
1769 /** The specified {@code Network} is not connected. */
1770 public static final int ERROR_INVALID_NETWORK = -20;
1771 /** The specified IP addresses are invalid. For example, the specified source IP address is
1772 * not configured on the specified {@code Network}. */
1773 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1774 /** The requested port is invalid. */
1775 public static final int ERROR_INVALID_PORT = -22;
1776 /** The packet length is invalid (e.g., too long). */
1777 public static final int ERROR_INVALID_LENGTH = -23;
1778 /** The packet transmission interval is invalid (e.g., too short). */
1779 public static final int ERROR_INVALID_INTERVAL = -24;
1780
1781 /** The hardware does not support this request. */
1782 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001783 /** The hardware returned an error. */
1784 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001785
Nathan Harold63dd8132018-02-14 13:09:45 -08001786 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001787 public static final int NATT_PORT = 4500;
1788
Nathan Harold63dd8132018-02-14 13:09:45 -08001789 /** The minimum interval in seconds between keepalive packet transmissions */
1790 public static final int MIN_INTERVAL = 10;
1791
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001792 private final Network mNetwork;
junyulai7c469172019-01-16 20:23:34 +08001793 private final ISocketKeepaliveCallback mCallback;
1794 private final ExecutorService mExecutor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001795
1796 private volatile Integer mSlot;
1797
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001798 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001799 public void stop() {
1800 try {
junyulai7c469172019-01-16 20:23:34 +08001801 mExecutor.execute(() -> {
1802 try {
1803 if (mSlot != null) {
1804 mService.stopKeepalive(mNetwork, mSlot);
1805 }
1806 } catch (RemoteException e) {
1807 Log.e(TAG, "Error stopping packet keepalive: ", e);
1808 throw e.rethrowFromSystemServer();
1809 }
1810 });
1811 } catch (RejectedExecutionException e) {
1812 // The internal executor has already stopped due to previous event.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001813 }
1814 }
1815
1816 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001817 Preconditions.checkNotNull(network, "network cannot be null");
1818 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001819 mNetwork = network;
junyulai7c469172019-01-16 20:23:34 +08001820 mExecutor = Executors.newSingleThreadExecutor();
1821 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001822 @Override
junyulai7c469172019-01-16 20:23:34 +08001823 public void onStarted(int slot) {
1824 Binder.withCleanCallingIdentity(() ->
1825 mExecutor.execute(() -> {
1826 mSlot = slot;
1827 callback.onStarted();
1828 }));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001829 }
junyulai7c469172019-01-16 20:23:34 +08001830
1831 @Override
1832 public void onStopped() {
1833 Binder.withCleanCallingIdentity(() ->
1834 mExecutor.execute(() -> {
1835 mSlot = null;
1836 callback.onStopped();
1837 }));
1838 mExecutor.shutdown();
1839 }
1840
1841 @Override
1842 public void onError(int error) {
1843 Binder.withCleanCallingIdentity(() ->
1844 mExecutor.execute(() -> {
1845 mSlot = null;
1846 callback.onError(error);
1847 }));
1848 mExecutor.shutdown();
1849 }
1850
1851 @Override
1852 public void onDataReceived() {
1853 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1854 // this callback when data is received.
1855 }
1856 };
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001857 }
1858 }
1859
1860 /**
1861 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1862 *
junyulai48eac1d42018-12-27 17:25:29 +08001863 * @deprecated Use {@link #createSocketKeepalive} instead.
1864 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001865 * @hide
1866 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001867 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001868 public PacketKeepalive startNattKeepalive(
1869 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1870 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1871 final PacketKeepalive k = new PacketKeepalive(network, callback);
1872 try {
junyulai7c469172019-01-16 20:23:34 +08001873 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001874 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1875 } catch (RemoteException e) {
1876 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai7c469172019-01-16 20:23:34 +08001877 throw e.rethrowFromSystemServer();
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001878 }
1879 return k;
1880 }
1881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 /**
junyulai48eac1d42018-12-27 17:25:29 +08001883 * Request that keepalives be started on a IPsec NAT-T socket.
1884 *
1885 * @param network The {@link Network} the socket is on.
1886 * @param socket The socket that needs to be kept alive.
1887 * @param source The source address of the {@link UdpEncapsulationSocket}.
1888 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1889 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1890 * must run callback sequentially, otherwise the order of callbacks cannot be
1891 * guaranteed.
1892 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1893 * changes. Must be extended by applications that use this API.
1894 *
junyulai352dc2f2019-01-08 20:04:33 +08001895 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1896 * given socket.
junyulai48eac1d42018-12-27 17:25:29 +08001897 **/
junyulai0c666972019-03-04 22:45:36 +08001898 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai48eac1d42018-12-27 17:25:29 +08001899 @NonNull UdpEncapsulationSocket socket,
1900 @NonNull InetAddress source,
1901 @NonNull InetAddress destination,
1902 @NonNull @CallbackExecutor Executor executor,
1903 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001904 ParcelFileDescriptor dup;
1905 try {
junyulai15178152019-03-27 11:00:37 +08001906 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1907 // which cannot be obtained by the app process.
junyulai0c666972019-03-04 22:45:36 +08001908 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1909 } catch (IOException ignored) {
1910 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1911 // ERROR_INVALID_SOCKET.
1912 dup = new ParcelFileDescriptor(new FileDescriptor());
1913 }
1914 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1915 destination, executor, callback);
junyulai215b8772019-01-15 11:32:44 +08001916 }
1917
1918 /**
1919 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1920 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1921 *
1922 * @param network The {@link Network} the socket is on.
junyulai0c666972019-03-04 22:45:36 +08001923 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1924 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1925 * from that port.
junyulai215b8772019-01-15 11:32:44 +08001926 * @param source The source address of the {@link UdpEncapsulationSocket}.
1927 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1928 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1929 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1930 * must run callback sequentially, otherwise the order of callbacks cannot be
1931 * guaranteed.
1932 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1933 * changes. Must be extended by applications that use this API.
1934 *
junyulai352dc2f2019-01-08 20:04:33 +08001935 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1936 * given socket.
junyulai215b8772019-01-15 11:32:44 +08001937 * @hide
1938 */
1939 @SystemApi
1940 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08001941 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1942 @NonNull ParcelFileDescriptor pfd,
junyulai215b8772019-01-15 11:32:44 +08001943 @NonNull InetAddress source,
1944 @NonNull InetAddress destination,
1945 @NonNull @CallbackExecutor Executor executor,
1946 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001947 ParcelFileDescriptor dup;
1948 try {
junyulai15178152019-03-27 11:00:37 +08001949 // TODO: Consider remove unnecessary dup.
junyulai0c666972019-03-04 22:45:36 +08001950 dup = pfd.dup();
1951 } catch (IOException ignored) {
1952 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1953 // ERROR_INVALID_SOCKET.
1954 dup = new ParcelFileDescriptor(new FileDescriptor());
1955 }
1956 return new NattSocketKeepalive(mService, network, dup,
1957 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08001958 }
1959
1960 /**
junyulai352dc2f2019-01-08 20:04:33 +08001961 * Request that keepalives be started on a TCP socket.
1962 * The socket must be established.
1963 *
1964 * @param network The {@link Network} the socket is on.
1965 * @param socket The socket that needs to be kept alive.
1966 * @param executor The executor on which callback will be invoked. This implementation assumes
1967 * the provided {@link Executor} runs the callbacks in sequence with no
1968 * concurrency. Failing this, no guarantee of correctness can be made. It is
1969 * the responsibility of the caller to ensure the executor provides this
1970 * guarantee. A simple way of creating such an executor is with the standard
1971 * tool {@code Executors.newSingleThreadExecutor}.
1972 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1973 * changes. Must be extended by applications that use this API.
1974 *
1975 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1976 * given socket.
1977 * @hide
1978 */
1979 @SystemApi
1980 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08001981 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai352dc2f2019-01-08 20:04:33 +08001982 @NonNull Socket socket,
1983 @NonNull Executor executor,
1984 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001985 ParcelFileDescriptor dup;
1986 try {
1987 dup = ParcelFileDescriptor.fromSocket(socket);
1988 } catch (UncheckedIOException ignored) {
1989 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1990 // ERROR_INVALID_SOCKET.
1991 dup = new ParcelFileDescriptor(new FileDescriptor());
1992 }
1993 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai352dc2f2019-01-08 20:04:33 +08001994 }
1995
1996 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 * Ensure that a network route exists to deliver traffic to the specified
1998 * host via the specified network interface. An attempt to add a route that
1999 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002000 *
2001 * <p>This method requires the caller to hold either the
2002 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2003 * or the ability to modify system settings as determined by
2004 * {@link android.provider.Settings.System#canWrite}.</p>
2005 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 * @param networkType the type of the network over which traffic to the specified
2007 * host is to be routed
2008 * @param hostAddress the IP address of the host to which the route is desired
2009 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002010 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002011 * @deprecated Deprecated in favor of the
2012 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2013 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07002014 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002015 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09002016 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002018 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002020 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002021 }
2022
2023 /**
2024 * Ensure that a network route exists to deliver traffic to the specified
2025 * host via the specified network interface. An attempt to add a route that
2026 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002027 *
2028 * <p>This method requires the caller to hold either the
2029 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2030 * or the ability to modify system settings as determined by
2031 * {@link android.provider.Settings.System#canWrite}.</p>
2032 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002033 * @param networkType the type of the network over which traffic to the specified
2034 * host is to be routed
2035 * @param hostAddress the IP address of the host to which the route is desired
2036 * @return {@code true} on success, {@code false} on failure
2037 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002038 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002039 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002040 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002041 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002042 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002043 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002044 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002046 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002048 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 }
2050 }
2051
2052 /**
2053 * Returns the value of the setting for background data usage. If false,
2054 * applications should not use the network if the application is not in the
2055 * foreground. Developers should respect this setting, and check the value
2056 * of this before performing any background data operations.
2057 * <p>
2058 * All applications that have background services that use the network
2059 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002060 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002061 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002062 * background data depends on several combined factors, and this method will
2063 * always return {@code true}. Instead, when background data is unavailable,
2064 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002065 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 * @return Whether background data usage is allowed.
2067 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002068 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002070 // assume that background data is allowed; final authority is
2071 // NetworkInfo which may be blocked.
2072 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 }
2074
2075 /**
2076 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002077 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 * @param allowBackgroundData Whether an application should use data while
2079 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002080 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2082 * @see #getBackgroundDataSetting()
2083 * @hide
2084 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002085 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002086 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002088 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002090
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002091 /** {@hide} */
2092 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002093 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002094 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2095 try {
2096 return mService.getActiveNetworkQuotaInfo();
2097 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002098 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002099 }
2100 }
2101
2102 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002103 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002104 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002105 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002106 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002107 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002108 public boolean getMobileDataEnabled() {
Meng Wanga73bed82019-11-18 17:10:00 -08002109 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2110 if (tm != null) {
2111 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2112 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2113 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2114 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2115 + " retVal=" + retVal);
2116 return retVal;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002117 }
Wink Saville36ffb042014-12-05 11:10:30 -08002118 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002119 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002120 }
2121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002123 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002124 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002125 */
2126 public interface OnNetworkActiveListener {
2127 /**
2128 * Called on the main thread of the process to report that the current data network
2129 * has become active, and it is now a good time to perform any pending network
2130 * operations. Note that this listener only tells you when the network becomes
2131 * active; if at any other time you want to know whether it is active (and thus okay
2132 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002133 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002134 */
Chalard Jean4d660112018-06-04 16:52:49 +09002135 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002136 }
2137
2138 private INetworkManagementService getNetworkManagementService() {
2139 synchronized (this) {
2140 if (mNMService != null) {
2141 return mNMService;
2142 }
2143 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2144 mNMService = INetworkManagementService.Stub.asInterface(b);
2145 return mNMService;
2146 }
2147 }
2148
2149 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002150 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002151
2152 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002153 * Start listening to reports when the system's default data network is active, meaning it is
2154 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2155 * to determine the current state of the system's default network after registering the
2156 * listener.
2157 * <p>
2158 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002159 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002160 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002161 *
2162 * @param l The listener to be told when the network is active.
2163 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002164 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002165 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2166 @Override
2167 public void onNetworkActive() throws RemoteException {
2168 l.onNetworkActive();
2169 }
2170 };
2171
2172 try {
2173 getNetworkManagementService().registerNetworkActivityListener(rl);
2174 mNetworkActivityListeners.put(l, rl);
2175 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002176 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002177 }
2178 }
2179
2180 /**
2181 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002182 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002183 *
2184 * @param l Previously registered listener.
2185 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002186 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002187 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002188 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002189 try {
2190 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2191 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002192 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002193 }
2194 }
2195
2196 /**
2197 * Return whether the data network is currently active. An active network means that
2198 * it is currently in a high power state for performing data transmission. On some
2199 * types of networks, it may be expensive to move and stay in such a state, so it is
2200 * more power efficient to batch network traffic together when the radio is already in
2201 * this state. This method tells you whether right now is currently a good time to
2202 * initiate network traffic, as the network is already active.
2203 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002204 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002205 try {
2206 return getNetworkManagementService().isNetworkActive();
2207 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002208 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002209 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002210 }
2211
2212 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 * {@hide}
2214 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002215 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002216 mContext = Preconditions.checkNotNull(context, "missing context");
2217 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002218 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensene0bef712014-12-10 15:12:18 -05002219 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002221
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002222 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002223 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002224 public static ConnectivityManager from(Context context) {
2225 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2226 }
2227
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002228 /** @hide */
2229 public NetworkRequest getDefaultRequest() {
2230 try {
2231 // This is not racy as the default request is final in ConnectivityService.
2232 return mService.getDefaultRequest();
2233 } catch (RemoteException e) {
2234 throw e.rethrowFromSystemServer();
2235 }
2236 }
2237
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002238 /* TODO: These permissions checks don't belong in client-side code. Move them to
2239 * services.jar, possibly in com.android.server.net. */
2240
2241 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002242 public static final void enforceChangePermission(Context context) {
2243 int uid = Binder.getCallingUid();
2244 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2245 .getPackageNameForUid(context, uid), true /* throwException */);
2246 }
2247
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002248 /** {@hide} */
2249 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002250 Preconditions.checkNotNull(context, "Context cannot be null");
2251 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002252
Robert Greenwaltedb47662014-09-16 17:54:19 -07002253 if (context.getResources().getStringArray(
2254 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2255 // Have a provisioning app - must only let system apps (which check this app)
2256 // turn on tethering
2257 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002258 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002259 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002260 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002261 // If callingPkg's uid is not same as Binder.getCallingUid(),
2262 // AppOpsService throws SecurityException.
2263 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2264 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002265 }
2266 }
2267
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002268 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002269 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2270 * situations where a Context pointer is unavailable.
2271 * @hide
2272 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002273 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002274 static ConnectivityManager getInstanceOrNull() {
2275 return sInstance;
2276 }
2277
2278 /**
2279 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2280 * situations where a Context pointer is unavailable.
2281 * @hide
2282 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002283 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002284 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002285 private static ConnectivityManager getInstance() {
2286 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002287 throw new IllegalStateException("No ConnectivityManager yet constructed");
2288 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002289 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002290 }
2291
2292 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002293 * Get the set of tetherable, available interfaces. This list is limited by
2294 * device configuration and current interface existence.
2295 *
2296 * @return an array of 0 or more Strings of tetherable interface names.
2297 *
markchien40898ca2020-01-21 13:11:06 +08002298 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002299 * {@hide}
2300 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002301 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002302 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002303 @Deprecated
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002304 public String[] getTetherableIfaces() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002305 return mTetheringManager.getTetherableIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002306 }
2307
2308 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002309 * Get the set of tethered interfaces.
2310 *
2311 * @return an array of 0 or more String of currently tethered interface names.
2312 *
markchien40898ca2020-01-21 13:11:06 +08002313 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002314 * {@hide}
2315 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002316 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002317 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002318 @Deprecated
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002319 public String[] getTetheredIfaces() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002320 return mTetheringManager.getTetheredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002321 }
2322
2323 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002324 * Get the set of interface names which attempted to tether but
2325 * failed. Re-attempting to tether may cause them to reset to the Tethered
2326 * state. Alternatively, causing the interface to be destroyed and recreated
2327 * may cause them to reset to the available state.
2328 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2329 * information on the cause of the errors.
2330 *
2331 * @return an array of 0 or more String indicating the interface names
2332 * which failed to tether.
2333 *
markchien40898ca2020-01-21 13:11:06 +08002334 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002335 * {@hide}
2336 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002337 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002338 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002339 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002340 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002341 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002342 }
2343
2344 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002345 * Get the set of tethered dhcp ranges.
2346 *
markchien2c153702020-02-06 19:23:26 +08002347 * @deprecated This method is not supported.
2348 * TODO: remove this function when all of clients are removed.
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002349 * {@hide}
2350 */
paulhua6af6b62019-08-12 16:25:11 +08002351 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien40898ca2020-01-21 13:11:06 +08002352 @Deprecated
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002353 public String[] getTetheredDhcpRanges() {
markchien2c153702020-02-06 19:23:26 +08002354 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002355 }
2356
2357 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002358 * Attempt to tether the named interface. This will setup a dhcp server
2359 * on the interface, forward and NAT IP packets and forward DNS requests
2360 * to the best active upstream network interface. Note that if no upstream
2361 * IP network interface is available, dhcp will still run and traffic will be
2362 * allowed between the tethered devices and this device, though upstream net
2363 * access will of course fail until an upstream network interface becomes
2364 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002365 *
2366 * <p>This method requires the caller to hold either the
2367 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2368 * or the ability to modify system settings as determined by
2369 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002370 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002371 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2372 * and WifiStateMachine which need direct access. All other clients should use
2373 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2374 * logic.</p>
2375 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002376 * @param iface the interface name to tether.
2377 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiene8b9d752020-01-20 19:31:56 +08002378 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002379 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002380 * {@hide}
2381 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002382 @UnsupportedAppUsage
markchiene8b9d752020-01-20 19:31:56 +08002383 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002384 public int tether(String iface) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002385 return mTetheringManager.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002386 }
2387
2388 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002389 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002390 *
2391 * <p>This method requires the caller to hold either the
2392 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2393 * or the ability to modify system settings as determined by
2394 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002395 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002396 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2397 * and WifiStateMachine which need direct access. All other clients should use
2398 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2399 * logic.</p>
2400 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002401 * @param iface the interface name to untether.
2402 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2403 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002404 * {@hide}
2405 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002406 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002407 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002408 public int untether(String iface) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002409 return mTetheringManager.untether(iface);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002410 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002411
2412 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002413 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002414 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002415 * due to device configuration.
2416 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002417 * <p>If this app does not have permission to use this API, it will always
2418 * return false rather than throw an exception.</p>
2419 *
2420 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2421 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2422 *
2423 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2424 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2425 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002426 * @return a boolean - {@code true} indicating Tethering is supported.
2427 *
markchien40898ca2020-01-21 13:11:06 +08002428 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002429 * {@hide}
2430 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002431 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002432 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2433 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002434 public boolean isTetheringSupported() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002435 return mTetheringManager.isTetheringSupported();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002436 }
2437
2438 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002439 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchiene8b9d752020-01-20 19:31:56 +08002440 *
2441 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002442 * @hide
2443 */
2444 @SystemApi
markchiene8b9d752020-01-20 19:31:56 +08002445 @Deprecated
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002446 public static abstract class OnStartTetheringCallback {
2447 /**
2448 * Called when tethering has been successfully started.
2449 */
Chalard Jean4d660112018-06-04 16:52:49 +09002450 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002451
2452 /**
2453 * Called when starting tethering failed.
2454 */
Chalard Jean4d660112018-06-04 16:52:49 +09002455 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002456 }
2457
2458 /**
2459 * Convenient overload for
2460 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2461 * handler to run on the current thread's {@link Looper}.
markchiene8b9d752020-01-20 19:31:56 +08002462 *
2463 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002464 * @hide
2465 */
2466 @SystemApi
markchiene8b9d752020-01-20 19:31:56 +08002467 @Deprecated
Udam Saini0e94c362017-06-07 12:06:28 -07002468 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002469 public void startTethering(int type, boolean showProvisioningUi,
2470 final OnStartTetheringCallback callback) {
2471 startTethering(type, showProvisioningUi, callback, null);
2472 }
2473
2474 /**
2475 * Runs tether provisioning for the given type if needed and then starts tethering if
2476 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2477 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2478 * schedules tether provisioning re-checks if appropriate.
2479 *
2480 * @param type The type of tethering to start. Must be one of
2481 * {@link ConnectivityManager.TETHERING_WIFI},
2482 * {@link ConnectivityManager.TETHERING_USB}, or
2483 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2484 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2485 * is one. This should be true the first time this function is called and also any time
2486 * the user can see this UI. It gives users information from their carrier about the
2487 * check failing and how they can sign up for tethering if possible.
2488 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2489 * of the result of trying to tether.
2490 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchiene8b9d752020-01-20 19:31:56 +08002491 *
2492 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002493 * @hide
2494 */
2495 @SystemApi
markchiene8b9d752020-01-20 19:31:56 +08002496 @Deprecated
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002497 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002498 public void startTethering(int type, boolean showProvisioningUi,
2499 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002500 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002501
markchiene8b9d752020-01-20 19:31:56 +08002502 final Executor executor = new Executor() {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002503 @Override
markchiene8b9d752020-01-20 19:31:56 +08002504 public void execute(Runnable command) {
2505 if (handler == null) {
2506 command.run();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002507 } else {
markchiene8b9d752020-01-20 19:31:56 +08002508 handler.post(command);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002509 }
2510 }
2511 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002512
markchiene8b9d752020-01-20 19:31:56 +08002513 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2514 @Override
2515 public void onTetheringStarted() {
2516 callback.onTetheringStarted();
2517 }
2518
2519 @Override
markchien62a625d2020-03-19 13:37:43 +08002520 public void onTetheringFailed(final int error) {
markchiene8b9d752020-01-20 19:31:56 +08002521 callback.onTetheringFailed();
2522 }
2523 };
2524
2525 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien62a625d2020-03-19 13:37:43 +08002526 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchiene8b9d752020-01-20 19:31:56 +08002527
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002528 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002529 }
2530
2531 /**
2532 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2533 * applicable.
2534 *
2535 * @param type The type of tethering to stop. Must be one of
2536 * {@link ConnectivityManager.TETHERING_WIFI},
2537 * {@link ConnectivityManager.TETHERING_USB}, or
2538 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien40898ca2020-01-21 13:11:06 +08002539 *
2540 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002541 * @hide
2542 */
2543 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002544 @Deprecated
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002545 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002546 public void stopTethering(int type) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002547 mTetheringManager.stopTethering(type);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002548 }
2549
2550 /**
markchien26299ed2019-02-27 14:56:11 +08002551 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2552 * upstream status.
2553 *
Nathan Haroldedf6b3d2020-01-23 18:03:46 -08002554 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien40898ca2020-01-21 13:11:06 +08002555 * @hide
markchien26299ed2019-02-27 14:56:11 +08002556 */
2557 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002558 @Deprecated
markchien26299ed2019-02-27 14:56:11 +08002559 public abstract static class OnTetheringEventCallback {
2560
2561 /**
2562 * Called when tethering upstream changed. This can be called multiple times and can be
2563 * called any time.
2564 *
2565 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2566 * have any upstream.
2567 */
2568 public void onUpstreamChanged(@Nullable Network network) {}
2569 }
2570
markchien40898ca2020-01-21 13:11:06 +08002571 @GuardedBy("mTetheringEventCallbacks")
2572 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2573 mTetheringEventCallbacks = new ArrayMap<>();
2574
markchien26299ed2019-02-27 14:56:11 +08002575 /**
2576 * Start listening to tethering change events. Any new added callback will receive the last
markchien9f246bd2019-04-03 10:43:09 +08002577 * tethering status right away. If callback is registered when tethering has no upstream or
markchien26299ed2019-02-27 14:56:11 +08002578 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2579 * with a null argument. The same callback object cannot be registered twice.
2580 *
2581 * @param executor the executor on which callback will be invoked.
2582 * @param callback the callback to be called when tethering has change events.
markchien40898ca2020-01-21 13:11:06 +08002583 *
Nathan Haroldedf6b3d2020-01-23 18:03:46 -08002584 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien26299ed2019-02-27 14:56:11 +08002585 * @hide
2586 */
2587 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002588 @Deprecated
markchien26299ed2019-02-27 14:56:11 +08002589 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2590 public void registerTetheringEventCallback(
2591 @NonNull @CallbackExecutor Executor executor,
2592 @NonNull final OnTetheringEventCallback callback) {
2593 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2594
markchien40898ca2020-01-21 13:11:06 +08002595 final TetheringEventCallback tetherCallback =
2596 new TetheringEventCallback() {
2597 @Override
2598 public void onUpstreamChanged(@Nullable Network network) {
2599 callback.onUpstreamChanged(network);
2600 }
2601 };
2602
2603 synchronized (mTetheringEventCallbacks) {
2604 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002605 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien40898ca2020-01-21 13:11:06 +08002606 }
markchien26299ed2019-02-27 14:56:11 +08002607 }
2608
2609 /**
2610 * Remove tethering event callback previously registered with
2611 * {@link #registerTetheringEventCallback}.
2612 *
2613 * @param callback previously registered callback.
markchien40898ca2020-01-21 13:11:06 +08002614 *
2615 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien26299ed2019-02-27 14:56:11 +08002616 * @hide
2617 */
2618 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002619 @Deprecated
markchien26299ed2019-02-27 14:56:11 +08002620 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2621 public void unregisterTetheringEventCallback(
2622 @NonNull final OnTetheringEventCallback callback) {
markchien40898ca2020-01-21 13:11:06 +08002623 Objects.requireNonNull(callback, "The callback must be non-null");
2624 synchronized (mTetheringEventCallbacks) {
2625 final TetheringEventCallback tetherCallback =
2626 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002627 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien40898ca2020-01-21 13:11:06 +08002628 }
markchien26299ed2019-02-27 14:56:11 +08002629 }
2630
2631
2632 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002633 * Get the list of regular expressions that define any tetherable
2634 * USB network interfaces. If USB tethering is not supported by the
2635 * device, this list should be empty.
2636 *
2637 * @return an array of 0 or more regular expression Strings defining
2638 * what interfaces are considered tetherable usb interfaces.
2639 *
markchien40898ca2020-01-21 13:11:06 +08002640 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002641 * {@hide}
2642 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002643 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002644 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002645 @Deprecated
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002646 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002647 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002648 }
2649
2650 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002651 * Get the list of regular expressions that define any tetherable
2652 * Wifi network interfaces. If Wifi tethering is not supported by the
2653 * device, this list should be empty.
2654 *
2655 * @return an array of 0 or more regular expression Strings defining
2656 * what interfaces are considered tetherable wifi interfaces.
2657 *
markchien40898ca2020-01-21 13:11:06 +08002658 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002659 * {@hide}
2660 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002661 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002662 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002663 @Deprecated
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002664 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002665 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002666 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002667
Danica Chang6fdd0c62010-08-11 14:54:43 -07002668 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002669 * Get the list of regular expressions that define any tetherable
2670 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2671 * device, this list should be empty.
2672 *
2673 * @return an array of 0 or more regular expression Strings defining
2674 * what interfaces are considered tetherable bluetooth interfaces.
2675 *
markchien40898ca2020-01-21 13:11:06 +08002676 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2677 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002678 * {@hide}
2679 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002680 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002681 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002682 @Deprecated
Danica Chang6fdd0c62010-08-11 14:54:43 -07002683 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002684 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002685 }
2686
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002687 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002688 * Attempt to both alter the mode of USB and Tethering of USB. A
2689 * utility method to deal with some of the complexity of USB - will
2690 * attempt to switch to Rndis and subsequently tether the resulting
2691 * interface on {@code true} or turn off tethering and switch off
2692 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002693 *
2694 * <p>This method requires the caller to hold either the
2695 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2696 * or the ability to modify system settings as determined by
2697 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002698 *
2699 * @param enable a boolean - {@code true} to enable tethering
2700 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiene8b9d752020-01-20 19:31:56 +08002701 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002702 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002703 * {@hide}
2704 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002705 @UnsupportedAppUsage
markchiene8b9d752020-01-20 19:31:56 +08002706 @Deprecated
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002707 public int setUsbTethering(boolean enable) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002708 return mTetheringManager.setUsbTethering(enable);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002709 }
2710
markchien40898ca2020-01-21 13:11:06 +08002711 /**
2712 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2713 * {@hide}
2714 */
markchienf2731272019-01-16 17:44:13 +08002715 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002716 @Deprecated
2717 public static final int TETHER_ERROR_NO_ERROR = TetheringManager.TETHER_ERROR_NO_ERROR;
2718 /**
2719 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2720 * {@hide}
2721 */
2722 @Deprecated
2723 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2724 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2725 /**
2726 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2727 * {@hide}
2728 */
2729 @Deprecated
2730 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2731 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2732 /**
2733 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2734 * {@hide}
2735 */
2736 @Deprecated
2737 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2738 /**
2739 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2740 * {@hide}
2741 */
2742 @Deprecated
2743 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2744 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2745 /**
markchien62a625d2020-03-19 13:37:43 +08002746 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien40898ca2020-01-21 13:11:06 +08002747 * {@hide}
2748 */
2749 @Deprecated
markchien62a625d2020-03-19 13:37:43 +08002750 public static final int TETHER_ERROR_MASTER_ERROR =
2751 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien40898ca2020-01-21 13:11:06 +08002752 /**
2753 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2754 * {@hide}
2755 */
2756 @Deprecated
2757 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2758 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2759 /**
2760 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2761 * {@hide}
2762 */
2763 @Deprecated
2764 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2765 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2766 /**
markchien62a625d2020-03-19 13:37:43 +08002767 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien40898ca2020-01-21 13:11:06 +08002768 * {@hide}
2769 */
2770 @Deprecated
2771 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien62a625d2020-03-19 13:37:43 +08002772 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien40898ca2020-01-21 13:11:06 +08002773 /**
markchien62a625d2020-03-19 13:37:43 +08002774 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien40898ca2020-01-21 13:11:06 +08002775 * {@hide}
2776 */
2777 @Deprecated
2778 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien62a625d2020-03-19 13:37:43 +08002779 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien40898ca2020-01-21 13:11:06 +08002780 /**
2781 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2782 * {@hide}
2783 */
2784 @Deprecated
2785 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2786 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2787 /**
markchien62a625d2020-03-19 13:37:43 +08002788 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien40898ca2020-01-21 13:11:06 +08002789 * {@hide}
2790 */
markchienf2731272019-01-16 17:44:13 +08002791 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002792 @Deprecated
2793 public static final int TETHER_ERROR_PROVISION_FAILED =
markchien62a625d2020-03-19 13:37:43 +08002794 TetheringManager.TETHER_ERROR_PROVISIONING_FAILED;
markchien40898ca2020-01-21 13:11:06 +08002795 /**
2796 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2797 * {@hide}
2798 */
2799 @Deprecated
2800 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2801 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2802 /**
2803 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2804 * {@hide}
2805 */
markchienf2731272019-01-16 17:44:13 +08002806 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002807 @Deprecated
2808 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN =
2809 TetheringManager.TETHER_ERROR_ENTITLEMENT_UNKNOWN;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002810
2811 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002812 * Get a more detailed error code after a Tethering or Untethering
2813 * request asynchronously failed.
2814 *
2815 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002816 * @return error The error code of the last error tethering or untethering the named
2817 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002818 *
markchien40898ca2020-01-21 13:11:06 +08002819 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt5a735062010-03-02 17:25:02 -08002820 * {@hide}
2821 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002822 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002823 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002824 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002825 public int getLastTetherError(String iface) {
markchien62a625d2020-03-19 13:37:43 +08002826 int error = mTetheringManager.getLastTetherError(iface);
2827 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2828 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2829 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2830 // instead.
2831 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2832 }
2833 return error;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002834 }
2835
markchien9554abf2019-03-06 16:25:00 +08002836 /** @hide */
2837 @Retention(RetentionPolicy.SOURCE)
2838 @IntDef(value = {
2839 TETHER_ERROR_NO_ERROR,
2840 TETHER_ERROR_PROVISION_FAILED,
2841 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2842 })
2843 public @interface EntitlementResultCode {
2844 }
2845
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002846 /**
markchien9554abf2019-03-06 16:25:00 +08002847 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchienf2731272019-01-16 17:44:13 +08002848 * entitlement succeeded.
markchien40898ca2020-01-21 13:11:06 +08002849 *
2850 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchienf2731272019-01-16 17:44:13 +08002851 * @hide
2852 */
2853 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002854 @Deprecated
markchien9554abf2019-03-06 16:25:00 +08002855 public interface OnTetheringEntitlementResultListener {
2856 /**
2857 * Called to notify entitlement result.
2858 *
2859 * @param resultCode an int value of entitlement result. It may be one of
2860 * {@link #TETHER_ERROR_NO_ERROR},
2861 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2862 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2863 */
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002864 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchien9554abf2019-03-06 16:25:00 +08002865 }
2866
2867 /**
markchienf2731272019-01-16 17:44:13 +08002868 * Get the last value of the entitlement check on this downstream. If the cached value is
2869 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2870 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2871 * guaranteed that the UI-based entitlement check will complete in any specific time period
2872 * and may in fact never complete. Any successful entitlement check the platform performs for
2873 * any reason will update the cached value.
2874 *
2875 * @param type the downstream type of tethering. Must be one of
2876 * {@link #TETHERING_WIFI},
2877 * {@link #TETHERING_USB}, or
2878 * {@link #TETHERING_BLUETOOTH}.
2879 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchien9554abf2019-03-06 16:25:00 +08002880 * @param executor the executor on which callback will be invoked.
2881 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2882 * notify the caller of the result of entitlement check. The listener may be called zero
2883 * or one time.
markchien40898ca2020-01-21 13:11:06 +08002884 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchienf2731272019-01-16 17:44:13 +08002885 * {@hide}
2886 */
2887 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002888 @Deprecated
markchienf2731272019-01-16 17:44:13 +08002889 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchien9554abf2019-03-06 16:25:00 +08002890 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2891 @NonNull @CallbackExecutor Executor executor,
2892 @NonNull final OnTetheringEntitlementResultListener listener) {
2893 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2894 ResultReceiver wrappedListener = new ResultReceiver(null) {
2895 @Override
2896 protected void onReceiveResult(int resultCode, Bundle resultData) {
2897 Binder.withCleanCallingIdentity(() ->
2898 executor.execute(() -> {
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002899 listener.onTetheringEntitlementResult(resultCode);
markchien9554abf2019-03-06 16:25:00 +08002900 }));
2901 }
2902 };
2903
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002904 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienae8aa642019-12-16 20:15:20 +08002905 showEntitlementUi);
markchien9554abf2019-03-06 16:25:00 +08002906 }
2907
2908 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002909 * Report network connectivity status. This is currently used only
2910 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002911 * <p>This method requires the caller to hold the permission
2912 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002913 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002914 * @param networkType The type of network you want to report on
2915 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002916 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002917 * {@hide}
2918 */
2919 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002920 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002921 try {
2922 mService.reportInetCondition(networkType, percentage);
2923 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002924 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002925 }
2926 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002927
2928 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002929 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002930 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002931 * the framework to re-evaluate network connectivity and/or switch to another
2932 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002933 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002934 * @param network The {@link Network} the application was attempting to use
2935 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002936 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2937 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002938 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002939 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002940 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002941 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002942 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002943 // One of these will be ignored because it matches system's current state.
2944 // The other will trigger the necessary reevaluation.
2945 mService.reportNetworkConnectivity(network, true);
2946 mService.reportNetworkConnectivity(network, false);
2947 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002948 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002949 }
2950 }
2951
2952 /**
2953 * Report to the framework whether a network has working connectivity.
2954 * This provides a hint to the system that a particular network is providing
2955 * working connectivity or not. In response the framework may re-evaluate
2956 * the network's connectivity and might take further action thereafter.
2957 *
2958 * @param network The {@link Network} the application was attempting to use
2959 * or {@code null} to indicate the current default network.
2960 * @param hasConnectivity {@code true} if the application was able to successfully access the
2961 * Internet using {@code network} or {@code false} if not.
2962 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002963 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002964 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002965 try {
2966 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002967 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002968 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002969 }
2970 }
2971
2972 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002973 * Set a network-independent global http proxy. This is not normally what you want
2974 * for typical HTTP proxies - they are general network dependent. However if you're
2975 * doing something unusual like general internal filtering this may be useful. On
2976 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002977 *
2978 * @param p A {@link ProxyInfo} object defining the new global
2979 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002980 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002981 */
paulhua6af6b62019-08-12 16:25:11 +08002982 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk207900c2014-04-25 15:00:09 -04002983 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002984 try {
2985 mService.setGlobalProxy(p);
2986 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002987 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002988 }
2989 }
2990
2991 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002992 * Retrieve any network-independent global HTTP proxy.
2993 *
Jason Monk207900c2014-04-25 15:00:09 -04002994 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002995 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002996 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002997 */
Jason Monk207900c2014-04-25 15:00:09 -04002998 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002999 try {
3000 return mService.getGlobalProxy();
3001 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003002 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003003 }
3004 }
3005
3006 /**
Paul Jensencee9b512015-05-06 07:32:40 -04003007 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3008 * network-specific HTTP proxy. If {@code network} is null, the
3009 * network-specific proxy returned is the proxy of the default active
3010 * network.
3011 *
3012 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3013 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3014 * or when {@code network} is {@code null},
3015 * the {@code ProxyInfo} for the default active network. Returns
3016 * {@code null} when no proxy applies or the caller doesn't have
3017 * permission to use {@code network}.
3018 * @hide
3019 */
3020 public ProxyInfo getProxyForNetwork(Network network) {
3021 try {
3022 return mService.getProxyForNetwork(network);
3023 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003024 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04003025 }
3026 }
3027
3028 /**
Paul Jensene0bef712014-12-10 15:12:18 -05003029 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3030 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04003031 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05003032 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003033 *
Jason Monk207900c2014-04-25 15:00:09 -04003034 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003035 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07003036 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003037 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05003038 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04003039 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07003040 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003041
3042 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003043 * Returns true if the hardware supports the given network type
3044 * else it returns false. This doesn't indicate we have coverage
3045 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003046 * hardware supports it. For example a GSM phone without a SIM
3047 * should still return {@code true} for mobile data, but a wifi only
3048 * tablet would return {@code false}.
3049 *
3050 * @param networkType The network type we'd like to check
3051 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003052 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003053 * @hide
3054 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003055 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003056 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09003057 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003058 public boolean isNetworkSupported(int networkType) {
3059 try {
3060 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003061 } catch (RemoteException e) {
3062 throw e.rethrowFromSystemServer();
3063 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003064 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003065
3066 /**
3067 * Returns if the currently active data network is metered. A network is
3068 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003069 * that connection due to monetary costs, data limitations or
3070 * battery/performance issues. You should check this before doing large
3071 * data transfers, and warn the user or delay the operation until another
3072 * network is available.
3073 *
3074 * @return {@code true} if large transfers should be avoided, otherwise
3075 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003076 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003077 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003078 public boolean isActiveNetworkMetered() {
3079 try {
3080 return mService.isActiveNetworkMetered();
3081 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003082 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003083 }
3084 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003085
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003086 /**
3087 * If the LockdownVpn mechanism is enabled, updates the vpn
3088 * with a reload of its profile.
3089 *
3090 * @return a boolean with {@code} indicating success
3091 *
3092 * <p>This method can only be called by the system UID
3093 * {@hide}
3094 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003095 public boolean updateLockdownVpn() {
3096 try {
3097 return mService.updateLockdownVpn();
3098 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003099 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003100 }
3101 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07003102
3103 /**
Wink Saville948282b2013-08-29 08:55:16 -07003104 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07003105 *
Wink Savilleab9321d2013-06-29 21:10:57 -07003106 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07003107 *
3108 * @return time out that will be used, maybe less that suggestedTimeOutMs
3109 * -1 if an error.
3110 *
3111 * {@hide}
3112 */
Wink Saville948282b2013-08-29 08:55:16 -07003113 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003114 int timeOutMs = -1;
3115 try {
Wink Saville948282b2013-08-29 08:55:16 -07003116 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07003117 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003118 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07003119 }
3120 return timeOutMs;
3121 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003122
3123 /**
Wink Saville42d4f082013-07-20 20:31:59 -07003124 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003125 * {@hide}
3126 */
paulhua6af6b62019-08-12 16:25:11 +08003127 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003128 public String getMobileProvisioningUrl() {
3129 try {
3130 return mService.getMobileProvisioningUrl();
3131 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003132 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003133 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003134 }
Wink Saville42d4f082013-07-20 20:31:59 -07003135
3136 /**
Wink Saville948282b2013-08-29 08:55:16 -07003137 * Set sign in error notification to visible or in visible
3138 *
Wink Saville948282b2013-08-29 08:55:16 -07003139 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04003140 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07003141 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003142 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07003143 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003144 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003145 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04003146 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07003147 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003148 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07003149 }
3150 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003151
3152 /**
3153 * Set the value for enabling/disabling airplane mode
3154 *
3155 * @param enable whether to enable airplane mode or not
3156 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003157 * @hide
3158 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003159 @RequiresPermission(anyOf = {
Edward Savage-Jonesaffb2292019-11-26 13:18:08 +01003160 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003161 android.Manifest.permission.NETWORK_SETTINGS,
3162 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3163 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09003164 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003165 public void setAirplaneMode(boolean enable) {
3166 try {
3167 mService.setAirplaneMode(enable);
3168 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003169 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003170 }
3171 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003172
Chalard Jean05ab6812018-05-02 21:14:54 +09003173 /** {@hide} - returns the factory serial number */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003174 @UnsupportedAppUsage
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003175 @RequiresPermission(anyOf = {
3176 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3177 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean05ab6812018-05-02 21:14:54 +09003178 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003179 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003180 return mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003181 } catch (RemoteException e) {
3182 throw e.rethrowFromSystemServer();
3183 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003184 }
3185
3186 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00003187 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003188 @RequiresPermission(anyOf = {
3189 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3190 android.Manifest.permission.NETWORK_FACTORY})
Robert Greenwalta67be032014-05-16 15:49:14 -07003191 public void unregisterNetworkFactory(Messenger messenger) {
3192 try {
3193 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003194 } catch (RemoteException e) {
3195 throw e.rethrowFromSystemServer();
3196 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003197 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003198
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003199 /**
3200 * Registers the specified {@link NetworkProvider}.
3201 * Each listener must only be registered once. The listener can be unregistered with
3202 * {@link #unregisterNetworkProvider}.
3203 *
3204 * @param provider the provider to register
3205 * @return the ID of the provider. This ID must be used by the provider when registering
3206 * {@link android.net.NetworkAgent}s.
3207 * @hide
3208 */
3209 @SystemApi
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003210 @RequiresPermission(anyOf = {
3211 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3212 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003213 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3214 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003215 throw new IllegalStateException("NetworkProviders can only be registered once");
3216 }
3217
3218 try {
3219 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3220 provider.getName());
3221 provider.setProviderId(providerId);
3222 } catch (RemoteException e) {
3223 throw e.rethrowFromSystemServer();
3224 }
3225 return provider.getProviderId();
3226 }
3227
3228 /**
3229 * Unregisters the specified NetworkProvider.
3230 *
3231 * @param provider the provider to unregister
3232 * @hide
3233 */
3234 @SystemApi
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003235 @RequiresPermission(anyOf = {
3236 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3237 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003238 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3239 try {
3240 mService.unregisterNetworkProvider(provider.getMessenger());
3241 } catch (RemoteException e) {
3242 throw e.rethrowFromSystemServer();
3243 }
3244 provider.setProviderId(NetworkProvider.ID_NONE);
3245 }
3246
3247
3248 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003249 @RequiresPermission(anyOf = {
3250 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3251 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003252 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3253 try {
3254 mService.declareNetworkRequestUnfulfillable(request);
3255 } catch (RemoteException e) {
3256 throw e.rethrowFromSystemServer();
3257 }
3258 }
3259
Chalard Jean05ab6812018-05-02 21:14:54 +09003260 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3261 // of dependent changes that would conflict throughout the automerger graph. Having this
3262 // temporarily helps with the process of going through with all these dependent changes across
3263 // the entire tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05003264 /**
3265 * @hide
3266 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003267 * @return Network corresponding to NetworkAgent.
Paul Jensen31a94f42015-02-13 14:18:39 -05003268 */
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003269 @RequiresPermission(anyOf = {
3270 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3271 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003272 public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittid9696562020-01-12 22:28:37 +09003273 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Chalard Jeana11593c2020-02-21 19:37:21 +09003274 return registerNetworkAgent(messenger, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean05ab6812018-05-02 21:14:54 +09003275 }
3276
3277 /**
3278 * @hide
3279 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003280 * @return Network corresponding to NetworkAgent.
Chalard Jean05ab6812018-05-02 21:14:54 +09003281 */
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003282 @RequiresPermission(anyOf = {
3283 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3284 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003285 public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Chalard Jeana11593c2020-02-21 19:37:21 +09003286 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003287 try {
Lorenzo Colittid9696562020-01-12 22:28:37 +09003288 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, config, providerId);
Paul Jensen31a94f42015-02-13 14:18:39 -05003289 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003290 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05003291 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003292 }
3293
Robert Greenwalt9258c642014-03-26 16:47:06 -07003294 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003295 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3296 * changes. Should be extended by applications wanting notifications.
3297 *
3298 * A {@code NetworkCallback} is registered by calling
3299 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3300 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09003301 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09003302 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3303 * A {@code NetworkCallback} should be registered at most once at any time.
3304 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003305 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003306 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003307 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003308 * Called when the framework connects to a new network to evaluate whether it satisfies this
3309 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3310 * callback. There is no guarantee that this new network will satisfy any requests, or that
3311 * the network will stay connected for longer than the time necessary to evaluate it.
3312 * <p>
3313 * Most applications <b>should not</b> act on this callback, and should instead use
3314 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3315 * the framework in properly evaluating the network &mdash; for example, an application that
3316 * can automatically log in to a captive portal without user intervention.
3317 *
3318 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09003319 *
3320 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07003321 */
paulhu3d67f532019-03-22 16:35:06 +08003322 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003323
3324 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003325 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003326 * This callback may be called more than once if the {@link Network} that is
3327 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003328 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003329 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003330 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3331 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08003332 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003333 * @hide
3334 */
paulhu3d67f532019-03-22 16:35:06 +08003335 public void onAvailable(@NonNull Network network,
3336 @NonNull NetworkCapabilities networkCapabilities,
3337 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003338 // Internally only this method is called when a new network is available, and
3339 // it calls the callback in the same way and order that older versions used
3340 // to call so as not to change the behavior.
3341 onAvailable(network);
3342 if (!networkCapabilities.hasCapability(
3343 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3344 onNetworkSuspended(network);
3345 }
3346 onCapabilitiesChanged(network, networkCapabilities);
3347 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003348 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003349 }
3350
3351 /**
3352 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean599ce752019-08-30 16:27:28 +09003353 *
3354 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3355 * be available at the same time, and onAvailable will be called for each of these as they
3356 * appear.
3357 *
3358 * <p>For callbacks registered with {@link #requestNetwork} and
3359 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3360 * is the new best network for this request and is now tracked by this callback ; this
3361 * callback will no longer receive method calls about other networks that may have been
3362 * passed to this method previously. The previously-best network may have disconnected, or
3363 * it may still be around and the newly-best network may simply be better.
3364 *
3365 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3366 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3367 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3368 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3369 *
3370 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3371 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3372 * this callback as this is prone to race conditions (there is no guarantee the objects
3373 * returned by these methods will be current). Instead, wait for a call to
3374 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3375 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3376 * to be well-ordered with respect to other callbacks.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003377 *
3378 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003379 */
paulhu3d67f532019-03-22 16:35:06 +08003380 public void onAvailable(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003381
3382 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003383 * Called when the network is about to be lost, typically because there are no outstanding
3384 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3385 * with the new replacement network for graceful handover. This method is not guaranteed
3386 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3387 * network is suddenly disconnected.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003388 *
Chalard Jean599ce752019-08-30 16:27:28 +09003389 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3390 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3391 * this callback as this is prone to race conditions ; calling these methods while in a
3392 * callback may return an outdated or even a null object.
3393 *
3394 * @param network The {@link Network} that is about to be lost.
3395 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3396 * connected for graceful handover; note that the network may still
3397 * suffer a hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003398 */
paulhu3d67f532019-03-22 16:35:06 +08003399 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003400
3401 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003402 * Called when a network disconnects or otherwise no longer satisfies this request or
3403 * callback.
3404 *
3405 * <p>If the callback was registered with requestNetwork() or
3406 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3407 * returned by onAvailable() when that network is lost and no other network satisfies
3408 * the criteria of the request.
3409 *
3410 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3411 * each network which no longer satisfies the criteria of the callback.
3412 *
3413 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3414 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3415 * this callback as this is prone to race conditions ; calling these methods while in a
3416 * callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003417 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003418 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003419 */
paulhu3d67f532019-03-22 16:35:06 +08003420 public void onLost(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003421
3422 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003423 * Called if no network is found within the timeout time specified in
Etan Cohenddb720a2019-01-08 12:09:18 -08003424 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3425 * requested network request cannot be fulfilled (whether or not a timeout was
3426 * specified). When this callback is invoked the associated
Etan Cohenaebf17e2017-03-01 12:47:28 -08003427 * {@link NetworkRequest} will have already been removed and released, as if
3428 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003429 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003430 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003431
3432 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003433 * Called when the network corresponding to this request changes capabilities but still
3434 * satisfies the requested criteria.
3435 *
3436 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3437 * to be called immediately after {@link #onAvailable}.
3438 *
3439 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3440 * ConnectivityManager methods in this callback as this is prone to race conditions :
3441 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003442 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003443 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003444 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3445 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003446 */
paulhu3d67f532019-03-22 16:35:06 +08003447 public void onCapabilitiesChanged(@NonNull Network network,
3448 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003449
3450 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003451 * Called when the network corresponding to this request changes {@link LinkProperties}.
3452 *
3453 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3454 * to be called immediately after {@link #onAvailable}.
3455 *
3456 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3457 * ConnectivityManager methods in this callback as this is prone to race conditions :
3458 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003459 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003460 * @param network The {@link Network} whose link properties have changed.
3461 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003462 */
paulhu3d67f532019-03-22 16:35:06 +08003463 public void onLinkPropertiesChanged(@NonNull Network network,
3464 @NonNull LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003465
Robert Greenwalt8d482522015-06-24 13:23:42 -07003466 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003467 * Called when the network the framework connected to for this request suspends data
3468 * transmission temporarily.
3469 *
3470 * <p>This generally means that while the TCP connections are still live temporarily
3471 * network data fails to transfer. To give a specific example, this is used on cellular
3472 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3473 * means read operations on sockets on this network will block once the buffers are
3474 * drained, and write operations will block once the buffers are full.
3475 *
3476 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3477 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3478 * this callback as this is prone to race conditions (there is no guarantee the objects
3479 * returned by these methods will be current).
3480 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003481 * @hide
3482 */
paulhu3d67f532019-03-22 16:35:06 +08003483 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003484
3485 /**
3486 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003487 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3488 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean599ce752019-08-30 16:27:28 +09003489
3490 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3491 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3492 * this callback as this is prone to race conditions : calling these methods while in a
3493 * callback may return an outdated or even a null object.
3494 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003495 * @hide
3496 */
paulhu3d67f532019-03-22 16:35:06 +08003497 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003498
junyulai05986c62018-08-07 19:50:45 +08003499 /**
3500 * Called when access to the specified network is blocked or unblocked.
3501 *
Chalard Jean599ce752019-08-30 16:27:28 +09003502 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3503 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3504 * this callback as this is prone to race conditions : calling these methods while in a
3505 * callback may return an outdated or even a null object.
3506 *
junyulai05986c62018-08-07 19:50:45 +08003507 * @param network The {@link Network} whose blocked status has changed.
3508 * @param blocked The blocked status of this {@link Network}.
3509 */
junyulai0c666972019-03-04 22:45:36 +08003510 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai05986c62018-08-07 19:50:45 +08003511
Robert Greenwalt6078b502014-06-11 16:05:07 -07003512 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003513 }
3514
Hugo Benichicb883232017-05-11 13:16:17 +09003515 /**
3516 * Constant error codes used by ConnectivityService to communicate about failures and errors
3517 * across a Binder boundary.
3518 * @hide
3519 */
3520 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003521 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003522 }
3523
3524 /** @hide */
3525 public static class TooManyRequestsException extends RuntimeException {}
3526
3527 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3528 switch (e.errorCode) {
3529 case Errors.TOO_MANY_REQUESTS:
3530 return new TooManyRequestsException();
3531 default:
3532 Log.w(TAG, "Unknown service error code " + e.errorCode);
3533 return new RuntimeException(e);
3534 }
3535 }
3536
Robert Greenwalt9258c642014-03-26 16:47:06 -07003537 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003538 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003539 public static final int CALLBACK_PRECHECK = BASE + 1;
3540 /** @hide */
3541 public static final int CALLBACK_AVAILABLE = BASE + 2;
3542 /** @hide arg1 = TTL */
3543 public static final int CALLBACK_LOSING = BASE + 3;
3544 /** @hide */
3545 public static final int CALLBACK_LOST = BASE + 4;
3546 /** @hide */
3547 public static final int CALLBACK_UNAVAIL = BASE + 5;
3548 /** @hide */
3549 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3550 /** @hide */
3551 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003552 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003553 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003554 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003555 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003556 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003557 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003558 /** @hide */
3559 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003560
Erik Kline57faba92015-11-25 12:49:38 +09003561 /** @hide */
3562 public static String getCallbackName(int whichCallback) {
3563 switch (whichCallback) {
3564 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3565 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3566 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3567 case CALLBACK_LOST: return "CALLBACK_LOST";
3568 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3569 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3570 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003571 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3572 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3573 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003574 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003575 default:
3576 return Integer.toString(whichCallback);
3577 }
3578 }
3579
Robert Greenwalt562cc542014-05-15 18:07:26 -07003580 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003581 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003582 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003583
Hugo Benichid42650f2016-07-06 22:53:17 +09003584 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003585 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003586 }
3587
Hugo Benichi2583ef02017-02-02 17:02:36 +09003588 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003589 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003590 }
3591
Robert Greenwalt9258c642014-03-26 16:47:06 -07003592 @Override
3593 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003594 if (message.what == EXPIRE_LEGACY_REQUEST) {
3595 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3596 return;
3597 }
3598
3599 final NetworkRequest request = getObject(message, NetworkRequest.class);
3600 final Network network = getObject(message, Network.class);
3601 final NetworkCallback callback;
3602 synchronized (sCallbacks) {
3603 callback = sCallbacks.get(request);
Etan Cohen4a62d1d2019-05-21 12:06:04 -07003604 if (callback == null) {
3605 Log.w(TAG,
3606 "callback not found for " + getCallbackName(message.what) + " message");
3607 return;
3608 }
Etan Cohen9b09a162019-04-16 15:07:55 -07003609 if (message.what == CALLBACK_UNAVAIL) {
3610 sCallbacks.remove(request);
3611 callback.networkRequest = ALREADY_UNREGISTERED;
3612 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003613 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003614 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003615 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003616 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003617
Robert Greenwalt9258c642014-03-26 16:47:06 -07003618 switch (message.what) {
3619 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003620 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003621 break;
3622 }
3623 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003624 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3625 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003626 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003627 break;
3628 }
3629 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003630 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003631 break;
3632 }
3633 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003634 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003635 break;
3636 }
3637 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003638 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003639 break;
3640 }
3641 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003642 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3643 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003644 break;
3645 }
3646 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003647 LinkProperties lp = getObject(message, LinkProperties.class);
3648 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003649 break;
3650 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003651 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003652 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003653 break;
3654 }
3655 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003656 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003657 break;
3658 }
junyulai05986c62018-08-07 19:50:45 +08003659 case CALLBACK_BLK_CHANGED: {
3660 boolean blocked = message.arg1 != 0;
3661 callback.onBlockedStatusChanged(network, blocked);
3662 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003663 }
3664 }
3665
Hugo Benichid42650f2016-07-06 22:53:17 +09003666 private <T> T getObject(Message msg, Class<T> c) {
3667 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003668 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003669 }
3670
Hugo Benichi2583ef02017-02-02 17:02:36 +09003671 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003672 synchronized (sCallbacks) {
3673 if (sCallbackHandler == null) {
3674 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003675 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003676 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003677 }
3678 }
3679
Hugo Benichi6f260f32017-02-03 14:18:44 +09003680 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3681 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003682
Hugo Benichi6f260f32017-02-03 14:18:44 +09003683 private static final int LISTEN = 1;
3684 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003685
Hugo Benichi6f260f32017-02-03 14:18:44 +09003686 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3687 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003688 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003689 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003690 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003691 final NetworkRequest request;
Roshan Piuse38acab2020-01-16 12:17:17 -08003692 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003693 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003694 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003695 if (callback.networkRequest != null
3696 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003697 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3698 // and requests (http://b/20701525).
3699 Log.e(TAG, "NetworkCallback was already registered");
3700 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003701 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003702 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003703 if (action == LISTEN) {
Roshan Piuse38acab2020-01-16 12:17:17 -08003704 request = mService.listenForNetwork(
3705 need, messenger, binder, callingPackageName);
Paul Jensen7221cc32014-06-27 11:05:32 -04003706 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003707 request = mService.requestNetwork(
Roshan Piuse38acab2020-01-16 12:17:17 -08003708 need, messenger, timeoutMs, binder, legacyType, callingPackageName);
Paul Jensen7221cc32014-06-27 11:05:32 -04003709 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003710 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003711 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003712 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003713 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003714 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003715 } catch (RemoteException e) {
3716 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003717 } catch (ServiceSpecificException e) {
3718 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003719 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003720 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003721 }
3722
3723 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003724 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003725 *
markchien97c029e2020-03-18 21:16:15 +08003726 * This API is only for use in internal system code that requests networks with legacy type and
3727 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchienace1d342020-01-14 12:54:40 +08003728 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003729 *
markchienace1d342020-01-14 12:54:40 +08003730 * @param request {@link NetworkRequest} describing this request.
markchienace1d342020-01-14 12:54:40 +08003731 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3732 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3733 * be a positive value (i.e. >0).
3734 * @param legacyType to specify the network type(#TYPE_*).
3735 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien97c029e2020-03-18 21:16:15 +08003736 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3737 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003738 *
3739 * @hide
3740 */
markchienace1d342020-01-14 12:54:40 +08003741 @SystemApi
markchien97c029e2020-03-18 21:16:15 +08003742 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003743 public void requestNetwork(@NonNull NetworkRequest request,
markchien97c029e2020-03-18 21:16:15 +08003744 int timeoutMs, int legacyType, @NonNull Handler handler,
3745 @NonNull NetworkCallback networkCallback) {
3746 if (legacyType == TYPE_NONE) {
3747 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3748 }
Hugo Benichi2583ef02017-02-02 17:02:36 +09003749 CallbackHandler cbHandler = new CallbackHandler(handler);
3750 NetworkCapabilities nc = request.networkCapabilities;
3751 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003752 }
3753
3754 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003755 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003756 *
Chalard Jean599ce752019-08-30 16:27:28 +09003757 * <p>This method will attempt to find the best network that matches the passed
3758 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3759 * criteria. The platform will evaluate which network is the best at its own discretion.
3760 * Throughput, latency, cost per byte, policy, user preference and other considerations
3761 * may be factored in the decision of what is considered the best network.
3762 *
3763 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3764 * matching this request, while always attempting to match the request to a better network if
3765 * possible. If a better match is found, the platform will switch this request to the now-best
3766 * network and inform the app of the newly best network by invoking
3767 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3768 * will not try to maintain any other network than the best one currently matching the request:
3769 * a network not matching any network request may be disconnected at any time.
3770 *
3771 * <p>For example, an application could use this method to obtain a connected cellular network
3772 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3773 * radio to consume additional power. Or, an application could inform the system that it wants
3774 * a network supporting sending MMSes and have the system let it know about the currently best
3775 * MMS-supporting network through the provided {@link NetworkCallback}.
3776 *
3777 * <p>The status of the request can be followed by listening to the various callbacks described
3778 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3779 * used to direct traffic to the network (although accessing some networks may be subject to
3780 * holding specific permissions). Callers will learn about the specific characteristics of the
3781 * network through
3782 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3783 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3784 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3785 * matching the request at any given time; therefore when a better network matching the request
3786 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3787 * with the new network after which no further updates are given about the previously-best
3788 * network, unless it becomes the best again at some later time. All callbacks are invoked
3789 * in order on the same thread, which by default is a thread created by the framework running
3790 * in the app.
3791 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3792 * callbacks are invoked.
3793 *
3794 * <p>This{@link NetworkRequest} will live until released via
3795 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3796 * which point the system may let go of the network at any time.
3797 *
3798 * <p>A version of this method which takes a timeout is
3799 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3800 * wait for a limited amount of time for the network to become unavailable.
3801 *
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003802 * <p>It is presently unsupported to request a network with mutable
3803 * {@link NetworkCapabilities} such as
3804 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3805 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3806 * as these {@code NetworkCapabilities} represent states that a particular
3807 * network may never attain, and whether a network will attain these states
3808 * is unknown prior to bringing up the network so the framework does not
Chalard Jean599ce752019-08-30 16:27:28 +09003809 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003810 *
3811 * <p>This method requires the caller to hold either the
3812 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3813 * or the ability to modify system settings as determined by
3814 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003815 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003816 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003817 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3818 * the callback must not be shared - it uniquely specifies this request.
3819 * The callback is invoked on the default internal Handler.
Chalard Jean92c8b672019-05-13 15:13:58 +09003820 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3821 * @throws SecurityException if missing the appropriate permissions.
3822 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003823 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003824 public void requestNetwork(@NonNull NetworkRequest request,
3825 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003826 requestNetwork(request, networkCallback, getDefaultHandler());
3827 }
3828
3829 /**
3830 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3831 *
Chalard Jean599ce752019-08-30 16:27:28 +09003832 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3833 * but runs all the callbacks on the passed Handler.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003834 *
Chalard Jean599ce752019-08-30 16:27:28 +09003835 * <p>This method has the same permission requirements as
3836 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3837 * the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003838 *
3839 * @param request {@link NetworkRequest} describing this request.
3840 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3841 * the callback must not be shared - it uniquely specifies this request.
3842 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003843 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003844 public void requestNetwork(@NonNull NetworkRequest request,
3845 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003846 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien97c029e2020-03-18 21:16:15 +08003847 NetworkCapabilities nc = request.networkCapabilities;
3848 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003849 }
3850
3851 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003852 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3853 * by a timeout.
3854 *
3855 * This function behaves identically to the non-timed-out version
3856 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3857 * is not found within the given time (in milliseconds) the
3858 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3859 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3860 * not have to be released if timed-out (it is automatically released). Unregistering a
3861 * request that timed out is not an error.
3862 *
3863 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3864 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3865 * for that purpose. Calling this method will attempt to bring up the requested network.
3866 *
Chalard Jean599ce752019-08-30 16:27:28 +09003867 * <p>This method has the same permission requirements as
3868 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3869 * the same conditions.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003870 *
3871 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003872 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3873 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003874 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3875 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3876 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003877 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003878 public void requestNetwork(@NonNull NetworkRequest request,
3879 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003880 checkTimeout(timeoutMs);
markchien97c029e2020-03-18 21:16:15 +08003881 NetworkCapabilities nc = request.networkCapabilities;
3882 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3883 getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003884 }
3885
Hugo Benichi2583ef02017-02-02 17:02:36 +09003886 /**
3887 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3888 * by a timeout.
3889 *
Chalard Jean599ce752019-08-30 16:27:28 +09003890 * This method behaves identically to
3891 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3892 * on the passed Handler.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003893 *
Chalard Jean599ce752019-08-30 16:27:28 +09003894 * <p>This method has the same permission requirements as
3895 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} and throws the same exceptions
3896 * in the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003897 *
3898 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003899 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3900 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003901 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003902 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3903 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003904 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003905 public void requestNetwork(@NonNull NetworkRequest request,
3906 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003907 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003908 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien97c029e2020-03-18 21:16:15 +08003909 NetworkCapabilities nc = request.networkCapabilities;
3910 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003911 }
3912
3913 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003914 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003915 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003916 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003917 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003918 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3919 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003920 */
Erik Kline90e93072014-11-19 12:12:24 +09003921 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003922
3923 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003924 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003925 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003926 * {@link android.content.Intent#getParcelableExtra(String)}.
3927 */
Erik Kline90e93072014-11-19 12:12:24 +09003928 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003929
3930
3931 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003932 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003933 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003934 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003935 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003936 * the request may outlive the calling application and get called back when a suitable
3937 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003938 * <p>
3939 * The operation is an Intent broadcast that goes to a broadcast receiver that
3940 * you registered with {@link Context#registerReceiver} or through the
3941 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3942 * <p>
3943 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003944 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3945 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003946 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003947 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003948 * Intent to reserve the network or it will be released shortly after the Intent
3949 * is processed.
3950 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003951 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003952 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003953 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003954 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003955 * The request may be released normally by calling
3956 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003957 * <p>It is presently unsupported to request a network with either
3958 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3959 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3960 * as these {@code NetworkCapabilities} represent states that a particular
3961 * network may never attain, and whether a network will attain these states
3962 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003963 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003964 *
3965 * <p>This method requires the caller to hold either the
3966 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3967 * or the ability to modify system settings as determined by
3968 * {@link android.provider.Settings.System#canWrite}.</p>
3969 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003970 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003971 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003972 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003973 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean92c8b672019-05-13 15:13:58 +09003974 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3975 * @throws SecurityException if missing the appropriate permissions.
3976 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003977 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003978 public void requestNetwork(@NonNull NetworkRequest request,
3979 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003980 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003981 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003982 try {
Roshan Piuse38acab2020-01-16 12:17:17 -08003983 mService.pendingRequestForNetwork(
Qingxi Li9c5d8b92020-01-08 12:51:49 -08003984 request.networkCapabilities, operation, mContext.getOpPackageName());
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003985 } catch (RemoteException e) {
3986 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003987 } catch (ServiceSpecificException e) {
3988 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003989 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003990 }
3991
3992 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003993 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3994 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003995 * This method has the same behavior as
3996 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003997 * releasing network resources and disconnecting.
3998 *
3999 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4000 * PendingIntent passed to
4001 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4002 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4003 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004004 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004005 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004006 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004007 try {
4008 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004009 } catch (RemoteException e) {
4010 throw e.rethrowFromSystemServer();
4011 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004012 }
4013
Hugo Benichie7678512017-05-09 15:19:01 +09004014 private static void checkPendingIntentNotNull(PendingIntent intent) {
4015 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4016 }
4017
4018 private static void checkCallbackNotNull(NetworkCallback callback) {
4019 Preconditions.checkNotNull(callback, "null NetworkCallback");
4020 }
4021
4022 private static void checkTimeout(int timeoutMs) {
4023 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004024 }
4025
4026 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07004027 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07004028 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08004029 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4030 * called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004031 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07004032 * @param request {@link NetworkRequest} describing this request.
4033 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4034 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004035 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004036 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004037 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004038 public void registerNetworkCallback(@NonNull NetworkRequest request,
4039 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004040 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4041 }
4042
4043 /**
4044 * Registers to receive notifications about all networks which satisfy the given
4045 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08004046 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4047 * called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004048 *
4049 * @param request {@link NetworkRequest} describing this request.
4050 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4051 * networks change state.
4052 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004053 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004054 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004055 public void registerNetworkCallback(@NonNull NetworkRequest request,
4056 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004057 CallbackHandler cbHandler = new CallbackHandler(handler);
4058 NetworkCapabilities nc = request.networkCapabilities;
4059 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060 }
4061
4062 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04004063 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4064 * {@link NetworkRequest}.
4065 *
4066 * This function behaves identically to the version that takes a NetworkCallback, but instead
4067 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4068 * the request may outlive the calling application and get called back when a suitable
4069 * network is found.
4070 * <p>
4071 * The operation is an Intent broadcast that goes to a broadcast receiver that
4072 * you registered with {@link Context#registerReceiver} or through the
4073 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4074 * <p>
4075 * The operation Intent is delivered with two extras, a {@link Network} typed
4076 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4077 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4078 * the original requests parameters.
4079 * <p>
4080 * If there is already a request for this Intent registered (with the equality of
4081 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4082 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4083 * <p>
4084 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004085 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04004086 * @param request {@link NetworkRequest} describing this request.
4087 * @param operation Action to perform when the network is available (corresponds
4088 * to the {@link NetworkCallback#onAvailable} call. Typically
4089 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4090 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004091 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004092 public void registerNetworkCallback(@NonNull NetworkRequest request,
4093 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004094 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004095 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04004096 try {
Roshan Piuse38acab2020-01-16 12:17:17 -08004097 mService.pendingListenForNetwork(
Qingxi Li9c5d8b92020-01-08 12:51:49 -08004098 request.networkCapabilities, operation, mContext.getOpPackageName());
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004099 } catch (RemoteException e) {
4100 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09004101 } catch (ServiceSpecificException e) {
4102 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004103 }
Paul Jensen694f2b82015-06-17 14:15:39 -04004104 }
4105
4106 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004107 * Registers to receive notifications about changes in the system default network. The callbacks
4108 * will continue to be called until either the application exits or
4109 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09004110 *
4111 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4112 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004113 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09004114 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004115 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004116 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004117 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4118 }
4119
4120 /**
4121 * Registers to receive notifications about changes in the system default network. The callbacks
4122 * will continue to be called until either the application exits or
4123 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004124 *
4125 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4126 * system default network changes.
4127 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004128 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004129 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004130 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4131 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09004132 // This works because if the NetworkCapabilities are null,
4133 // ConnectivityService takes them from the default request.
4134 //
4135 // Since the capabilities are exactly the same as the default request's
4136 // capabilities, this request is guaranteed, at all times, to be
4137 // satisfied by the same network, if any, that satisfies the default
4138 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004139 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09004140 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4141 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09004142 }
4143
4144 /**
fengludb571472015-04-21 17:12:05 -07004145 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4146 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4147 * network connection for updated bandwidth information. The caller will be notified via
4148 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004149 * method assumes that the caller has previously called
4150 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4151 * changes.
fenglub15e72b2015-03-20 11:29:56 -07004152 *
fengluae519192015-04-27 14:28:04 -07004153 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07004154 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07004155 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004156 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004157 try {
fengludb571472015-04-21 17:12:05 -07004158 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07004159 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004160 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07004161 }
4162 }
4163
4164 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09004165 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004166 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4167 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4168 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09004169 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4170 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09004172 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4173 * triggering it as soon as this call returns.
4174 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07004175 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004176 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004177 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004178 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004179 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09004180 final List<NetworkRequest> reqs = new ArrayList<>();
4181 // Find all requests associated to this callback and stop callback triggers immediately.
4182 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4183 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09004184 Preconditions.checkArgument(networkCallback.networkRequest != null,
4185 "NetworkCallback was not registered");
Etan Cohen9b09a162019-04-16 15:07:55 -07004186 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4187 Log.d(TAG, "NetworkCallback was already unregistered");
4188 return;
4189 }
Hugo Benichidafed3d2017-03-06 09:17:06 +09004190 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4191 if (e.getValue() == networkCallback) {
4192 reqs.add(e.getKey());
4193 }
4194 }
4195 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4196 for (NetworkRequest r : reqs) {
4197 try {
4198 mService.releaseNetworkRequest(r);
4199 } catch (RemoteException e) {
4200 throw e.rethrowFromSystemServer();
4201 }
4202 // Only remove mapping if rpc was successful.
4203 sCallbacks.remove(r);
4204 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09004205 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004206 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004207 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004208
4209 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004210 * Unregisters a callback previously registered via
4211 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4212 *
4213 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4214 * PendingIntent passed to
4215 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4216 * Cannot be null.
4217 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004218 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09004219 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004220 releaseNetworkRequest(operation);
4221 }
4222
4223 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004224 * Informs the system whether it should switch to {@code network} regardless of whether it is
4225 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4226 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4227 * the system default network regardless of any other network that's currently connected. If
4228 * {@code always} is true, then the choice is remembered, so that the next time the user
4229 * connects to this network, the system will switch to it.
4230 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004231 * @param network The network to accept.
4232 * @param accept Whether to accept the network even if unvalidated.
4233 * @param always Whether to remember this choice in the future.
4234 *
4235 * @hide
4236 */
lucasline252a742019-03-12 13:08:03 +08004237 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004238 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4239 try {
4240 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004241 } catch (RemoteException e) {
4242 throw e.rethrowFromSystemServer();
4243 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004244 }
4245
4246 /**
lucasline252a742019-03-12 13:08:03 +08004247 * Informs the system whether it should consider the network as validated even if it only has
4248 * partial connectivity. If {@code accept} is true, then the network will be considered as
4249 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4250 * is remembered, so that the next time the user connects to this network, the system will
4251 * switch to it.
4252 *
4253 * @param network The network to accept.
4254 * @param accept Whether to consider the network as validated even if it has partial
4255 * connectivity.
4256 * @param always Whether to remember this choice in the future.
4257 *
4258 * @hide
4259 */
4260 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4261 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4262 try {
4263 mService.setAcceptPartialConnectivity(network, accept, always);
4264 } catch (RemoteException e) {
4265 throw e.rethrowFromSystemServer();
4266 }
4267 }
4268
4269 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004270 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4271 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4272 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4273 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4274 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004275 * @param network The network to accept.
4276 *
4277 * @hide
4278 */
lucasline252a742019-03-12 13:08:03 +08004279 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004280 public void setAvoidUnvalidated(Network network) {
4281 try {
4282 mService.setAvoidUnvalidated(network);
4283 } catch (RemoteException e) {
4284 throw e.rethrowFromSystemServer();
4285 }
4286 }
4287
4288 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004289 * Requests that the system open the captive portal app on the specified network.
4290 *
4291 * @param network The network to log into.
4292 *
4293 * @hide
4294 */
paulhua6af6b62019-08-12 16:25:11 +08004295 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004296 public void startCaptivePortalApp(Network network) {
4297 try {
4298 mService.startCaptivePortalApp(network);
4299 } catch (RemoteException e) {
4300 throw e.rethrowFromSystemServer();
4301 }
4302 }
4303
4304 /**
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004305 * Requests that the system open the captive portal app with the specified extras.
4306 *
4307 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4308 * corresponding permission.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004309 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004310 * @param appExtras Extras to include in the app start intent.
4311 * @hide
4312 */
4313 @SystemApi
4314 @TestApi
4315 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhud9736de2019-03-08 16:35:20 +08004316 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004317 try {
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004318 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004319 } catch (RemoteException e) {
4320 throw e.rethrowFromSystemServer();
4321 }
4322 }
4323
4324 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004325 * Determine whether the device is configured to avoid bad wifi.
4326 * @hide
4327 */
4328 @SystemApi
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004329 @RequiresPermission(anyOf = {
4330 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4331 android.Manifest.permission.NETWORK_STACK})
4332 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004333 try {
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004334 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004335 } catch (RemoteException e) {
4336 throw e.rethrowFromSystemServer();
4337 }
4338 }
4339
4340 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004341 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4342 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09004343 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4344 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004345 *
4346 * An example of such an operation might be a time-sensitive foreground activity, such as a
4347 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4348 */
4349 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4350
4351 /**
4352 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4353 * a backup channel for traffic that is primarily going over another network.
4354 *
4355 * An example might be maintaining backup connections to peers or servers for the purpose of
4356 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4357 * on backup paths should be negligible compared to the traffic on the main path.
4358 */
4359 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4360
4361 /**
4362 * It is acceptable to use metered data to improve network latency and performance.
4363 */
4364 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4365
4366 /**
4367 * Return value to use for unmetered networks. On such networks we currently set all the flags
4368 * to true.
4369 * @hide
4370 */
4371 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4372 MULTIPATH_PREFERENCE_HANDOVER |
4373 MULTIPATH_PREFERENCE_RELIABILITY |
4374 MULTIPATH_PREFERENCE_PERFORMANCE;
4375
4376 /** @hide */
4377 @Retention(RetentionPolicy.SOURCE)
4378 @IntDef(flag = true, value = {
4379 MULTIPATH_PREFERENCE_HANDOVER,
4380 MULTIPATH_PREFERENCE_RELIABILITY,
4381 MULTIPATH_PREFERENCE_PERFORMANCE,
4382 })
4383 public @interface MultipathPreference {
4384 }
4385
4386 /**
4387 * Provides a hint to the calling application on whether it is desirable to use the
4388 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4389 * for multipath data transfer on this network when it is not the system default network.
4390 * Applications desiring to use multipath network protocols should call this method before
4391 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004392 *
4393 * @param network The network on which the application desires to use multipath data.
4394 * If {@code null}, this method will return the a preference that will generally
4395 * apply to metered networks.
4396 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4397 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004398 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004399 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004400 try {
4401 return mService.getMultipathPreference(network);
4402 } catch (RemoteException e) {
4403 throw e.rethrowFromSystemServer();
4404 }
4405 }
4406
4407 /**
Stuart Scott984dc852015-03-30 13:17:11 -07004408 * Resets all connectivity manager settings back to factory defaults.
4409 * @hide
4410 */
paulhua6af6b62019-08-12 16:25:11 +08004411 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott984dc852015-03-30 13:17:11 -07004412 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07004413 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07004414 mService.factoryReset();
Automerger Merge Worker6112c822020-03-06 00:38:43 +00004415 mTetheringManager.stopAllTethering();
Stuart Scott984dc852015-03-30 13:17:11 -07004416 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004417 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07004418 }
4419 }
4420
4421 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004422 * Binds the current process to {@code network}. All Sockets created in the future
4423 * (and not explicitly bound via a bound SocketFactory from
4424 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4425 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4426 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4427 * work and all host name resolutions will fail. This is by design so an application doesn't
4428 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4429 * To clear binding pass {@code null} for {@code network}. Using individually bound
4430 * Sockets created by Network.getSocketFactory().createSocket() and
4431 * performing network-specific host name resolutions via
4432 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04004433 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004434 *
4435 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4436 * the current binding.
4437 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4438 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004439 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09004440 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04004441 // instantiated.
4442 return setProcessDefaultNetwork(network);
4443 }
4444
4445 /**
4446 * Binds the current process to {@code network}. All Sockets created in the future
4447 * (and not explicitly bound via a bound SocketFactory from
4448 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4449 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4450 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4451 * work and all host name resolutions will fail. This is by design so an application doesn't
4452 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4453 * To clear binding pass {@code null} for {@code network}. Using individually bound
4454 * Sockets created by Network.getSocketFactory().createSocket() and
4455 * performing network-specific host name resolutions via
4456 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4457 * {@code setProcessDefaultNetwork}.
4458 *
4459 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4460 * the current binding.
4461 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4462 * @deprecated This function can throw {@link IllegalStateException}. Use
4463 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4464 * is a direct replacement.
4465 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004466 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004467 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04004468 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004469 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4470
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09004471 if (netId != NETID_UNSET) {
4472 netId = network.getNetIdForResolv();
Paul Jensenc91b5342014-08-27 12:38:45 -04004473 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004474
4475 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4476 return false;
4477 }
4478
4479 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05004480 // Set HTTP proxy system properties to match network.
4481 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09004482 try {
4483 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4484 } catch (SecurityException e) {
4485 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4486 Log.e(TAG, "Can't set proxy properties", e);
4487 }
Paul Jensenc91b5342014-08-27 12:38:45 -04004488 // Must flush DNS cache as new network may have different DNS resolutions.
4489 InetAddress.clearDnsCache();
4490 // Must flush socket pool as idle sockets will be bound to previous network and may
4491 // cause subsequent fetches to be performed on old network.
4492 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04004493 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004494
4495 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004496 }
4497
4498 /**
4499 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004500 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004501 *
4502 * @return {@code Network} to which this process is bound, or {@code null}.
4503 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004504 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004505 public Network getBoundNetworkForProcess() {
4506 // Forcing callers to call thru non-static function ensures ConnectivityManager
4507 // instantiated.
4508 return getProcessDefaultNetwork();
4509 }
4510
4511 /**
4512 * Returns the {@link Network} currently bound to this process via
4513 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4514 *
4515 * @return {@code Network} to which this process is bound, or {@code null}.
4516 * @deprecated Using this function can lead to other functions throwing
4517 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4518 * {@code getBoundNetworkForProcess} is a direct replacement.
4519 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004520 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004521 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004522 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004523 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004524 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004525 return new Network(netId);
4526 }
4527
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004528 private void unsupportedStartingFrom(int version) {
4529 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004530 // The getApplicationInfo() call we make below is not supported in system context. Let
4531 // the call through here, and rely on the fact that ConnectivityService will refuse to
4532 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004533 return;
4534 }
4535
4536 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4537 throw new UnsupportedOperationException(
4538 "This method is not supported in target SDK version " + version + " and above");
4539 }
4540 }
4541
4542 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4543 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004544 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004545 // remove these exemptions. Note that this check is not secure, and apps can still access these
4546 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4547 // so is unsupported and may break in the future. http://b/22728205
4548 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004549 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004550 }
4551
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004552 /**
4553 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004554 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004555 *
4556 * @param network The {@link Network} to bind host resolutions from the current process to, or
4557 * {@code null} to clear the current binding.
4558 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4559 * @hide
4560 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4561 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004562 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004563 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004564 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004565 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004566 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004567 }
Felipe Leme1b103232016-01-22 09:44:57 -08004568
4569 /**
4570 * Device is not restricting metered network activity while application is running on
4571 * background.
4572 */
4573 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4574
4575 /**
4576 * Device is restricting metered network activity while application is running on background,
4577 * but application is allowed to bypass it.
4578 * <p>
4579 * In this state, application should take action to mitigate metered network access.
4580 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4581 */
4582 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4583
4584 /**
4585 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004586 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004587 * In this state, application should not try to use the network while running on background,
4588 * because it would be denied.
4589 */
4590 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4591
Felipe Leme9778f762016-01-27 14:46:39 -08004592 /**
4593 * A change in the background metered network activity restriction has occurred.
4594 * <p>
4595 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4596 * applies to them.
4597 * <p>
4598 * This is only sent to registered receivers, not manifest receivers.
4599 */
4600 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4601 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4602 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4603
Felipe Lemeecfccea2016-01-25 11:48:04 -08004604 /** @hide */
4605 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004606 @IntDef(flag = false, value = {
4607 RESTRICT_BACKGROUND_STATUS_DISABLED,
4608 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4609 RESTRICT_BACKGROUND_STATUS_ENABLED,
4610 })
Felipe Leme1b103232016-01-22 09:44:57 -08004611 public @interface RestrictBackgroundStatus {
4612 }
4613
4614 private INetworkPolicyManager getNetworkPolicyManager() {
4615 synchronized (this) {
4616 if (mNPManager != null) {
4617 return mNPManager;
4618 }
4619 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4620 .getService(Context.NETWORK_POLICY_SERVICE));
4621 return mNPManager;
4622 }
4623 }
4624
4625 /**
4626 * Determines if the calling application is subject to metered network restrictions while
4627 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004628 *
4629 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4630 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4631 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004632 */
4633 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4634 try {
4635 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4636 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004637 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004638 }
4639 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004640
4641 /**
4642 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004643 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4644 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004645 *
4646 * @return Hash of network watchlist config file. Null if config does not exist.
4647 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004648 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004649 public byte[] getNetworkWatchlistConfigHash() {
4650 try {
4651 return mService.getNetworkWatchlistConfigHash();
4652 } catch (RemoteException e) {
4653 Log.e(TAG, "Unable to get watchlist config hash");
4654 throw e.rethrowFromSystemServer();
4655 }
4656 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004657
4658 /**
4659 * Returns the {@code uid} of the owner of a network connection.
4660 *
Benedict Wong5d50ce82020-01-20 22:14:59 -08004661 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4662 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004663 * @param local The local {@link InetSocketAddress} of a connection.
4664 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004665 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong5d50ce82020-01-20 22:14:59 -08004666 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4667 * android.os.Process#INVALID_UID} if the connection is not found.
4668 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4669 * user.
4670 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004671 */
Benedict Wong5d50ce82020-01-20 22:14:59 -08004672 public int getConnectionOwnerUid(
4673 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004674 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4675 try {
4676 return mService.getConnectionOwnerUid(connectionInfo);
4677 } catch (RemoteException e) {
4678 throw e.rethrowFromSystemServer();
4679 }
4680 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004681
4682 private void printStackTrace() {
4683 if (DEBUG) {
4684 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4685 final StringBuffer sb = new StringBuffer();
4686 for (int i = 3; i < callStack.length; i++) {
4687 final String stackTrace = callStack[i].toString();
4688 if (stackTrace == null || stackTrace.contains("android.os")) {
4689 break;
4690 }
4691 sb.append(" [").append(stackTrace).append("]");
4692 }
4693 Log.d(TAG, "StackLog:" + sb.toString());
4694 }
4695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696}