blob: de85833c56d0f629dbf875c0b60af4a5f4c21c39 [file] [log] [blame]
The Android Open Source Project28527d22009-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 Project28527d22009-03-03 19:31:44 -080016package android.net;
17
Junyu Laia62493f2021-01-19 11:10:56 +000018import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
paulhu56e09df2021-03-17 20:30:33 +080019import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_DEFAULT_MODE;
20import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE;
Junyu Laia62493f2021-01-19 11:10:56 +000021import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaiad010792021-01-11 16:53:38 +080022import static android.net.NetworkRequest.Type.LISTEN;
junyulai1b1c8742021-03-12 20:05:08 +080023import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
junyulaiad010792021-01-11 16:53:38 +080024import static android.net.NetworkRequest.Type.REQUEST;
25import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +090026import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Brightf9e945b2020-06-15 16:10:01 -070027import static android.net.QosCallback.QosCallbackRegistrationException;
junyulaid05a1922019-01-15 11:32:44 +080028
junyulai4c95b082018-12-27 17:25:29 +080029import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080030import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090031import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000032import android.annotation.Nullable;
Jeff Sharkey656584a2017-04-24 11:18:03 -060033import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080034import android.annotation.SdkConstant;
35import android.annotation.SdkConstant.SdkConstantType;
lucaslin705c3332021-03-12 17:56:09 +080036import android.annotation.StringDef;
Junyu Laia62493f2021-01-19 11:10:56 +000037import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080038import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060039import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070040import android.app.PendingIntent;
Artur Satayev9c2add62019-12-10 17:47:52 +000041import android.compat.annotation.UnsupportedAppUsage;
lucaslin705c3332021-03-12 17:56:09 +080042import android.content.ContentResolver;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070043import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070044import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080045import android.net.IpSecManager.UdpEncapsulationSocket;
46import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080047import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080048import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080049import android.net.TetheringManager.TetheringRequest;
Roshan Pius951c0032020-12-22 15:10:42 -080050import android.net.wifi.WifiNetworkSuggestion;
Robert Greenwalt2034b912009-08-12 16:08:25 -070051import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000052import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070053import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080054import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070055import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080056import android.os.IBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070057import android.os.Looper;
58import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070059import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080060import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070061import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090062import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080064import android.os.ResultReceiver;
Hugo Benichia590ab82017-05-11 13:16:17 +090065import android.os.ServiceSpecificException;
Chalard Jeanfa45a682021-02-25 17:23:40 +090066import android.os.UserHandle;
Jeff Sharkey971cd162011-08-29 16:02:57 -070067import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080068import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080069import android.telephony.TelephonyManager;
lucaslin705c3332021-03-12 17:56:09 +080070import android.text.TextUtils;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080071import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070072import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090073import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090074import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080075
markchien6ae63e52020-01-21 13:11:06 +080076import com.android.internal.annotations.GuardedBy;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070077
Paul Jensen3e2917c2014-08-27 12:38:45 -040078import libcore.net.event.NetworkEventDispatcher;
79
junyulai7e06ad42019-03-04 22:45:36 +080080import java.io.IOException;
81import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080082import java.lang.annotation.Retention;
83import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090084import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080085import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070086import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080087import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090088import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090089import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080090import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090091import java.util.List;
92import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080093import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080094import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080095import java.util.concurrent.ExecutorService;
96import java.util.concurrent.Executors;
97import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -080098
The Android Open Source Project28527d22009-03-03 19:31:44 -080099/**
100 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600101 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800102 * <p>
103 * The primary responsibilities of this class are to:
104 * <ol>
105 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
106 * <li>Send broadcast intents when network connectivity changes</li>
107 * <li>Attempt to "fail over" to another network when connectivity to a network
108 * is lost</li>
109 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
110 * state of the available networks</li>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700111 * <li>Provide an API that allows applications to request and select networks for their data
112 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800113 * </ol>
114 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600115@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700116public class ConnectivityManager {
117 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900118 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700119
The Android Open Source Project28527d22009-03-03 19:31:44 -0800120 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700121 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122 * been established or lost. The NetworkInfo for the affected network is
123 * sent as an extra; it should be consulted to see what kind of
124 * connectivity event occurred.
125 * <p/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800126 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
127 * broadcast if they declare the broadcast receiver in their manifest. Apps
128 * will still receive broadcasts if they register their
129 * {@link android.content.BroadcastReceiver} with
130 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
131 * and that context is still valid.
132 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133 * If this is a connection that was the result of failing over from a
134 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
135 * set to true.
136 * <p/>
137 * For a loss of connectivity, if the connectivity manager is attempting
138 * to connect (or has already connected) to another network, the
139 * NetworkInfo for the new network is also passed as an extra. This lets
140 * any receivers of the broadcast know that they should not necessarily
141 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800142 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800143 * the failover attempt succeeded (and so there is still overall data
144 * connectivity), or that the failover attempt failed, meaning that all
145 * connectivity has been lost.
146 * <p/>
147 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
148 * is set to {@code true} if there are no connected networks at all.
Chalard Jean52e23962018-02-10 05:33:50 +0900149 *
150 * @deprecated apps should use the more versatile {@link #requestNetwork},
151 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
152 * functions instead for faster and more detailed updates about the network
153 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800154 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800155 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900156 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700158
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500160 * The device has connected to a network that has presented a captive
161 * portal, which is blocking Internet connectivity. The user was presented
162 * with a notification that network sign in is required,
163 * and the user invoked the notification's action indicating they
Paul Jensen75e0adb2015-05-22 10:50:39 -0400164 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500165 * facilitate signing in to the network. This action includes a
166 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
167 * the network presenting the captive portal; all communication with the
168 * captive portal must be done using this {@code Network} object.
169 * <p/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400170 * This activity includes a {@link CaptivePortal} extra named
171 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
172 * outcomes of the captive portal sign in to the system:
173 * <ul>
174 * <li> When the app handling this action believes the user has signed in to
175 * the network and the captive portal has been dismissed, the app should
176 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
177 * reevaluate the network. If reevaluation finds the network no longer
178 * subject to a captive portal, the network may become the default active
Chalard Jean9dd11612018-06-04 16:52:49 +0900179 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400180 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500181 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400182 * {@link CaptivePortal#ignoreNetwork}. </li>
183 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500184 */
185 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
186 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
187
188 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800189 * The lookup key for a {@link NetworkInfo} object. Retrieve with
190 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700191 *
Chalard Jean97021a12019-01-11 16:47:53 +0900192 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
193 * can't accurately represent modern network characteristics.
194 * Please obtain information about networks from the {@link NetworkCapabilities}
195 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800196 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700197 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700199
The Android Open Source Project28527d22009-03-03 19:31:44 -0800200 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700201 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700202 *
203 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900204 * @deprecated The network type is not rich enough to represent the characteristics
205 * of modern networks. Please use {@link NetworkCapabilities} instead,
206 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700207 */
Chalard Jean97021a12019-01-11 16:47:53 +0900208 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700209 public static final String EXTRA_NETWORK_TYPE = "networkType";
210
211 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800212 * The lookup key for a boolean that indicates whether a connect event
213 * is for a network to which the connectivity manager was failing over
214 * following a disconnect on another network.
215 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai9826e7f2018-12-13 12:47:51 +0800216 *
217 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800218 */
junyulai9826e7f2018-12-13 12:47:51 +0800219 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220 public static final String EXTRA_IS_FAILOVER = "isFailover";
221 /**
222 * The lookup key for a {@link NetworkInfo} object. This is supplied when
223 * there is another network that it may be possible to connect to. Retrieve with
224 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800225 *
226 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800227 */
junyulai9826e7f2018-12-13 12:47:51 +0800228 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
230 /**
231 * The lookup key for a boolean that indicates whether there is a
232 * complete lack of connectivity, i.e., no network is available.
233 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
234 */
235 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
236 /**
237 * The lookup key for a string that indicates why an attempt to connect
238 * to a network failed. The string has no particular structure. It is
239 * intended to be used in notifications presented to users. Retrieve
240 * it with {@link android.content.Intent#getStringExtra(String)}.
241 */
242 public static final String EXTRA_REASON = "reason";
243 /**
244 * The lookup key for a string that provides optionally supplied
245 * extra information about the network state. The information
246 * may be passed up from the lower networking layers, and its
247 * meaning may be specific to a particular network type. Retrieve
248 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800249 *
250 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800251 */
junyulai9826e7f2018-12-13 12:47:51 +0800252 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800253 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700254 /**
255 * The lookup key for an int that provides information about
256 * our connection to the internet at large. 0 indicates no connection,
257 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700258 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700259 * {@hide}
260 */
261 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800262 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400263 * The lookup key for a {@link CaptivePortal} object included with the
264 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
265 * object can be used to either indicate to the system that the captive
266 * portal has been dismissed or that the user does not want to pursue
267 * signing in to captive portal. Retrieve it with
268 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500269 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400270 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700271
272 /**
273 * Key for passing a URL to the captive portal login activity.
274 */
275 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
276
Paul Jensen60df4aa2015-02-27 22:55:47 -0500277 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900278 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
279 * portal login activity.
280 * {@hide}
281 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900282 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900283 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
284 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
285
286 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900287 * Key for passing a user agent string to the captive portal login activity.
288 * {@hide}
289 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900290 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900291 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
292 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
293
294 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700295 * Broadcast action to indicate the change of data activity status
296 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800297 * The network becomes active when data transmission is started, or
298 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700299 * {@hide}
300 */
301 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900302 public static final String ACTION_DATA_ACTIVITY_CHANGE =
303 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700304 /**
305 * The lookup key for an enum that indicates the network device type on which this data activity
306 * change happens.
307 * {@hide}
308 */
309 public static final String EXTRA_DEVICE_TYPE = "deviceType";
310 /**
311 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
312 * it is actively sending or receiving data and {@code false} means it is idle.
313 * {@hide}
314 */
315 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700316 /**
317 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
318 * {@hide}
319 */
320 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700321
322 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800323 * Broadcast Action: The setting for background data usage has changed
324 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
325 * <p>
326 * If an application uses the network in the background, it should listen
327 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700328 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800329 * <p>
330 *
331 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
332 * of background data depends on several combined factors, and
333 * this broadcast is no longer sent. Instead, when background
334 * data is unavailable, {@link #getActiveNetworkInfo()} will now
335 * appear disconnected. During first boot after a platform
336 * upgrade, this broadcast will be sent once if
337 * {@link #getBackgroundDataSetting()} was {@code false} before
338 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800339 */
340 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800341 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800342 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
343 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
344
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700345 /**
346 * Broadcast Action: The network connection may not be good
347 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
348 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
349 * the network and it's condition.
350 * @hide
351 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800352 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100353 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700354 public static final String INET_CONDITION_ACTION =
355 "android.net.conn.INET_CONDITION_ACTION";
356
Robert Greenwalt2034b912009-08-12 16:08:25 -0700357 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800358 * Broadcast Action: A tetherable connection has come or gone.
359 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900360 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
361 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800362 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
363 * the current state of tethering. Each include a list of
364 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800365 * @hide
366 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800367 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000368 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800369 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800370 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800371
372 /**
373 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800374 * gives a String[] listing all the interfaces configured for
375 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800376 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000377 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800378 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800379
380 /**
381 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900382 * gives a String[] listing all the interfaces currently in local-only
383 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800384 */
markchiena0f8fd92019-12-25 19:40:32 +0800385 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900386
387 /**
388 * @hide
389 * gives a String[] listing all the interfaces currently tethered
390 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
391 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000392 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800393 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800394
395 /**
396 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800397 * gives a String[] listing all the interfaces we tried to tether and
398 * failed. Use {@link #getLastTetherError} to find the error code
399 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800400 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000401 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800402 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800403
404 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800405 * Broadcast Action: The captive portal tracker has finished its test.
406 * Sent only while running Setup Wizard, in lieu of showing a user
407 * notification.
408 * @hide
409 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800410 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800411 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
412 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
413 /**
414 * The lookup key for a boolean that indicates whether a captive portal was detected.
415 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
416 * @hide
417 */
418 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
419
420 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900421 * Action used to display a dialog that asks the user whether to connect to a network that is
422 * not validated. This intent is used to start the dialog in settings via startActivity.
423 *
424 * @hide
425 */
426 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
427
428 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900429 * Action used to display a dialog that asks the user whether to avoid a network that is no
430 * longer validated. This intent is used to start the dialog in settings via startActivity.
431 *
432 * @hide
433 */
434 public static final String ACTION_PROMPT_LOST_VALIDATION =
435 "android.net.conn.PROMPT_LOST_VALIDATION";
436
437 /**
lucaslin2240ef62019-03-12 13:08:03 +0800438 * Action used to display a dialog that asks the user whether to stay connected to a network
439 * that has not validated. This intent is used to start the dialog in settings via
440 * startActivity.
441 *
442 * @hide
443 */
444 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
445 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
446
447 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800448 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900449 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800450 * @hide
451 */
markchiena0f8fd92019-12-25 19:40:32 +0800452 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800453
454 /**
455 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900456 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800457 * @hide
458 */
459 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900460 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800461
462 /**
463 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900464 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800465 * @hide
466 */
467 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900468 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800469
470 /**
471 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900472 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800473 * @hide
474 */
475 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900476 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800477
478 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800479 * Wifi P2p tethering type.
480 * Wifi P2p tethering is set through events automatically, and don't
481 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
482 * @hide
483 */
markchiena0f8fd92019-12-25 19:40:32 +0800484 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800485
486 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800487 * Extra used for communicating with the TetherService. Includes the type of tethering to
488 * enable if any.
489 * @hide
490 */
markchien6ae63e52020-01-21 13:11:06 +0800491 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800492
493 /**
494 * Extra used for communicating with the TetherService. Includes the type of tethering for
495 * which to cancel provisioning.
496 * @hide
497 */
markchien6ae63e52020-01-21 13:11:06 +0800498 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800499
500 /**
501 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
502 * provisioning.
503 * @hide
504 */
markchien6ae63e52020-01-21 13:11:06 +0800505 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800506
507 /**
508 * Tells the TetherService to run a provision check now.
509 * @hide
510 */
markchien6ae63e52020-01-21 13:11:06 +0800511 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800512
513 /**
514 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
515 * which will receive provisioning results. Can be left empty.
516 * @hide
517 */
markchien6ae63e52020-01-21 13:11:06 +0800518 public static final String EXTRA_PROVISION_CALLBACK =
519 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800520
521 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800522 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700523 * @hide
524 */
paulhu74357e72020-01-13 16:46:45 +0800525 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700526 public static final int TYPE_NONE = -1;
527
528 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900529 * A Mobile 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 Greenwalt2034b912009-08-12 16:08:25 -0700534 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900535 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700536 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900537
Robert Greenwalt2034b912009-08-12 16:08:25 -0700538 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900539 * A WIFI data connection. Devices may support more than one.
540 *
541 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
542 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
543 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700544 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900545 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700546 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900547
Robert Greenwalt2034b912009-08-12 16:08:25 -0700548 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800549 * An MMS-specific Mobile data connection. This network type may use the
550 * same network interface as {@link #TYPE_MOBILE} or it may use a different
551 * one. This is used by applications needing to talk to the carrier's
552 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900553 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900554 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900555 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900556 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700557 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700558 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700559 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900560
Robert Greenwalt2034b912009-08-12 16:08:25 -0700561 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800562 * A SUPL-specific Mobile data connection. This network type may use the
563 * same network interface as {@link #TYPE_MOBILE} or it may use a different
564 * one. This is used by applications needing to talk to the carrier's
565 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900566 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900567 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900568 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900569 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700570 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700571 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700572 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900573
Robert Greenwalt2034b912009-08-12 16:08:25 -0700574 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800575 * A DUN-specific Mobile data connection. This network type may use the
576 * same network interface as {@link #TYPE_MOBILE} or it may use a different
577 * one. This is sometimes by the system when setting up an upstream connection
578 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900579 *
580 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
581 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
582 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700583 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900584 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700585 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900586
Robert Greenwalt2034b912009-08-12 16:08:25 -0700587 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800588 * A High Priority Mobile data connection. This network type uses the
589 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900590 * is different.
591 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900592 * @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.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700595 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700596 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700597 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900598
jshbfa81722010-03-11 15:04:43 -0800599 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900600 * A WiMAX 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.
jshbfa81722010-03-11 15:04:43 -0800605 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900606 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800607 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800608
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800609 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900610 * A Bluetooth data connection.
611 *
612 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
613 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
614 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800615 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900616 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800617 public static final int TYPE_BLUETOOTH = 7;
618
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700619 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800620 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900621 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700622 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900623 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800624 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800625
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700626 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900627 * An Ethernet data connection.
628 *
629 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
630 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
631 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700632 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900633 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800634 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700635
Wink Savilleb7c92c72011-03-12 14:52:01 -0800636 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800637 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900638 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800639 * {@hide}
640 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900641 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900642 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800643 public static final int TYPE_MOBILE_FOTA = 10;
644
645 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800646 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900647 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800648 * {@hide}
649 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900650 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100651 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800652 public static final int TYPE_MOBILE_IMS = 11;
653
654 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800655 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900656 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800657 * {@hide}
658 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900659 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900660 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800661 public static final int TYPE_MOBILE_CBS = 12;
662
repo syncf5de5572011-07-29 23:55:49 -0700663 /**
664 * A Wi-Fi p2p connection. Only requesting processes will have access to
665 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900666 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700667 * {@hide}
668 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900669 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800670 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700671 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800672
Wink Saville512c2202013-07-29 15:00:57 -0700673 /**
674 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900675 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700676 * {@hide}
677 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900678 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100679 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700680 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700681
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900682 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700683 * Emergency PDN connection for emergency services. This
684 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900685 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700686 * {@hide}
687 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900688 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900689 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700690 public static final int TYPE_MOBILE_EMERGENCY = 15;
691
Hui Lu865b70d2014-01-15 11:05:36 -0500692 /**
693 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900694 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500695 * {@hide}
696 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900697 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900698 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500699 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700700
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700701 /**
702 * A virtual network using one or more native bearers.
703 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900704 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700705 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900706 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700707 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500708
Benedict Wongbdfaa482018-11-14 17:40:55 -0800709 /**
710 * A network that is exclusively meant to be used for testing
711 *
712 * @deprecated Use {@link NetworkCapabilities} instead.
713 * @hide
714 */
715 @Deprecated
716 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700717
Chalard Jeanaea539a2020-03-25 01:24:04 +0900718 /**
719 * @deprecated Use {@link NetworkCapabilities} instead.
720 * @hide
721 */
722 @Deprecated
723 @Retention(RetentionPolicy.SOURCE)
724 @IntDef(prefix = { "TYPE_" }, value = {
725 TYPE_NONE,
726 TYPE_MOBILE,
727 TYPE_WIFI,
728 TYPE_MOBILE_MMS,
729 TYPE_MOBILE_SUPL,
730 TYPE_MOBILE_DUN,
731 TYPE_MOBILE_HIPRI,
732 TYPE_WIMAX,
733 TYPE_BLUETOOTH,
734 TYPE_DUMMY,
735 TYPE_ETHERNET,
736 TYPE_MOBILE_FOTA,
737 TYPE_MOBILE_IMS,
738 TYPE_MOBILE_CBS,
739 TYPE_WIFI_P2P,
740 TYPE_MOBILE_IA,
741 TYPE_MOBILE_EMERGENCY,
742 TYPE_PROXY,
743 TYPE_VPN,
744 TYPE_TEST
745 })
746 public @interface LegacyNetworkType {}
747
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900748 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
749 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
750 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
751 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
752 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
753
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700754 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800755 public static final int MAX_RADIO_TYPE = TYPE_TEST;
756
757 /** {@hide} */
758 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800759
Hugo Benichiad353f42017-06-20 14:07:59 +0900760 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
761
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800762 /**
763 * If you want to set the default network preference,you can directly
764 * change the networkAttributes array in framework's config.xml.
765 *
766 * @deprecated Since we support so many more networks now, the single
767 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800768 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800769 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800770 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800771 * from an App.
772 */
773 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800774 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
775
Jeff Sharkey8c870452012-09-26 22:03:49 -0700776 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700777 * @hide
778 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900779 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700780
Paul Jensen5dea4352014-07-11 12:28:19 -0400781 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900782 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
783 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900784 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900785 * @hide
786 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900787 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900788 new NetworkRequest.Builder().clearCapabilities().build();
789
790 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400791 * A NetID indicating no Network is selected.
792 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
793 * @hide
794 */
795 public static final int NETID_UNSET = 0;
796
Erik Klineb0be3e62017-10-30 15:29:44 +0900797 /**
798 * Private DNS Mode values.
799 *
800 * The "private_dns_mode" global setting stores a String value which is
801 * expected to be one of the following.
802 */
803
804 /**
805 * @hide
806 */
lucaslin705c3332021-03-12 17:56:09 +0800807 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900808 public static final String PRIVATE_DNS_MODE_OFF = "off";
809 /**
810 * @hide
811 */
lucaslin705c3332021-03-12 17:56:09 +0800812 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900813 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
814 /**
815 * @hide
816 */
lucaslin705c3332021-03-12 17:56:09 +0800817 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900818 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin705c3332021-03-12 17:56:09 +0800819
820 /** @hide */
821 @Retention(RetentionPolicy.SOURCE)
822 @StringDef(value = {
823 PRIVATE_DNS_MODE_OFF,
824 PRIVATE_DNS_MODE_OPPORTUNISTIC,
825 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
826 })
827 public @interface PrivateDnsMode {}
Erik Klineb0be3e62017-10-30 15:29:44 +0900828
Chalard Jeana3b77512019-04-09 15:46:21 +0900829 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700830 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900831
Paul Jensenc0618a62014-12-10 15:12:18 -0500832 /**
833 * A kludge to facilitate static access where a Context pointer isn't available, like in the
834 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
835 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
836 * methods that take a Context argument.
837 */
838 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800839
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900840 private final Context mContext;
841
Amos Bianchia9b415a2020-03-04 11:07:38 -0800842 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800843
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800844 /**
845 * Tests if a given integer represents a valid network type.
846 * @param networkType the type to be tested
847 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400848 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
849 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800850 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700851 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700852 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900853 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800854 }
855
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800856 /**
857 * Returns a non-localized string representing a given network type.
858 * ONLY used for debugging output.
859 * @param type the type needing naming
860 * @return a String for the given type, or a string version of the type ("87")
861 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900862 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800863 * {@hide}
864 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900865 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000866 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700867 public static String getNetworkTypeName(int type) {
868 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900869 case TYPE_NONE:
870 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700871 case TYPE_MOBILE:
872 return "MOBILE";
873 case TYPE_WIFI:
874 return "WIFI";
875 case TYPE_MOBILE_MMS:
876 return "MOBILE_MMS";
877 case TYPE_MOBILE_SUPL:
878 return "MOBILE_SUPL";
879 case TYPE_MOBILE_DUN:
880 return "MOBILE_DUN";
881 case TYPE_MOBILE_HIPRI:
882 return "MOBILE_HIPRI";
883 case TYPE_WIMAX:
884 return "WIMAX";
885 case TYPE_BLUETOOTH:
886 return "BLUETOOTH";
887 case TYPE_DUMMY:
888 return "DUMMY";
889 case TYPE_ETHERNET:
890 return "ETHERNET";
891 case TYPE_MOBILE_FOTA:
892 return "MOBILE_FOTA";
893 case TYPE_MOBILE_IMS:
894 return "MOBILE_IMS";
895 case TYPE_MOBILE_CBS:
896 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700897 case TYPE_WIFI_P2P:
898 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700899 case TYPE_MOBILE_IA:
900 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700901 case TYPE_MOBILE_EMERGENCY:
902 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500903 case TYPE_PROXY:
904 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900905 case TYPE_VPN:
906 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700907 default:
908 return Integer.toString(type);
909 }
910 }
911
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800912 /**
Aaron Huang96011892020-06-27 07:18:23 +0800913 * @hide
Aaron Huang96011892020-06-27 07:18:23 +0800914 */
lucaslin7fc930b2021-03-17 14:16:01 +0800915 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huang96011892020-06-27 07:18:23 +0800916 public void systemReady() {
917 try {
918 mService.systemReady();
919 } catch (RemoteException e) {
920 throw e.rethrowFromSystemServer();
921 }
922 }
923
924 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800925 * Checks if a given type uses the cellular data connection.
926 * This should be replaced in the future by a network property.
927 * @param networkType the type to check
928 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900929 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800930 * {@hide}
931 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900932 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900933 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700934 public static boolean isNetworkTypeMobile(int networkType) {
935 switch (networkType) {
936 case TYPE_MOBILE:
937 case TYPE_MOBILE_MMS:
938 case TYPE_MOBILE_SUPL:
939 case TYPE_MOBILE_DUN:
940 case TYPE_MOBILE_HIPRI:
941 case TYPE_MOBILE_FOTA:
942 case TYPE_MOBILE_IMS:
943 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -0700944 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -0700945 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700946 return true;
947 default:
948 return false;
949 }
950 }
951
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800952 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700953 * Checks if the given network type is backed by a Wi-Fi radio.
954 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900955 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700956 * @hide
957 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900958 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700959 public static boolean isNetworkTypeWifi(int networkType) {
960 switch (networkType) {
961 case TYPE_WIFI:
962 case TYPE_WIFI_P2P:
963 return true;
964 default:
965 return false;
966 }
967 }
968
969 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +0900970 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
971 * Specify that the traffic for this user should by follow the default rules.
972 * @hide
973 */
Chalard Jeanb43f3962021-03-17 14:33:24 +0900974 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +0900975 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
976
977 /**
978 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
979 * Specify that the traffic for this user should by default go on a network with
980 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
981 * if no such network is available.
982 * @hide
983 */
Chalard Jeanb43f3962021-03-17 14:33:24 +0900984 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +0900985 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
986
987 /** @hide */
988 @Retention(RetentionPolicy.SOURCE)
989 @IntDef(value = {
990 PROFILE_NETWORK_PREFERENCE_DEFAULT,
991 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
992 })
993 public @interface ProfileNetworkPreference {
994 }
995
996 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800997 * Specifies the preferred network type. When the device has more
998 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800999 *
1000 * @param preference the network type to prefer over all others. It is
1001 * unspecified what happens to the old preferred network in the
1002 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001003 * @deprecated Functionality has been removed as it no longer makes sense,
1004 * with many more than two networks - we'd need an array to express
1005 * preference. Instead we use dynamic network properties of
1006 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001007 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001008 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001009 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001010 }
1011
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001012 /**
1013 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001014 *
1015 * @return an integer representing the preferred network type
1016 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001017 * @deprecated Functionality has been removed as it no longer makes sense,
1018 * with many more than two networks - we'd need an array to express
1019 * preference. Instead we use dynamic network properties of
1020 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001021 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001022 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001023 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001024 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001025 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001026 }
1027
Scott Mainf58b7d82011-10-06 19:02:28 -07001028 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001029 * Returns details about the currently active default data network. When
1030 * connected, this network is the default route for outgoing connections.
1031 * You should always check {@link NetworkInfo#isConnected()} before initiating
1032 * network traffic. This may return {@code null} when there is no default
1033 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001034 * Note that if the default network is a VPN, this method will return the
1035 * NetworkInfo for one of its underlying networks instead, or null if the
1036 * VPN agent did not specify any. Apps interested in learning about VPNs
1037 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001038 *
1039 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001040 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001041 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001042 */
junyulai9826e7f2018-12-13 12:47:51 +08001043 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001044 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001045 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001046 public NetworkInfo getActiveNetworkInfo() {
1047 try {
1048 return mService.getActiveNetworkInfo();
1049 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001050 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001051 }
1052 }
1053
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001054 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001055 * Returns a {@link Network} object corresponding to the currently active
1056 * default data network. In the event that the current active default data
1057 * network disconnects, the returned {@code Network} object will no longer
1058 * be usable. This will return {@code null} when there is no default
1059 * network.
1060 *
1061 * @return a {@link Network} object for the current default network or
1062 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001063 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001064 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001065 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001066 public Network getActiveNetwork() {
1067 try {
1068 return mService.getActiveNetwork();
1069 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001070 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001071 }
1072 }
1073
1074 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001075 * Returns a {@link Network} object corresponding to the currently active
1076 * default data network for a specific UID. In the event that the default data
1077 * network disconnects, the returned {@code Network} object will no longer
1078 * be usable. This will return {@code null} when there is no default
1079 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001080 *
1081 * @return a {@link Network} object for the current default network for the
1082 * given UID or {@code null} if no default network is currently active
1083 *
1084 * @hide
1085 */
paulhu8e96a752019-08-12 16:25:11 +08001086 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001087 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001088 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001089 return getActiveNetworkForUid(uid, false);
1090 }
1091
1092 /** {@hide} */
1093 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001094 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001095 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001096 } catch (RemoteException e) {
1097 throw e.rethrowFromSystemServer();
1098 }
1099 }
1100
1101 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001102 * Adds or removes a requirement for given UID ranges to use the VPN.
1103 *
1104 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1105 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1106 * otherwise have permission to bypass the VPN (e.g., because they have the
1107 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1108 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1109 * set to {@code false}, a previously-added restriction is removed.
1110 * <p>
1111 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1112 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1113 * remove a previously-added range, the exact range must be removed as is.
1114 * <p>
1115 * The changes are applied asynchronously and may not have been applied by the time the method
1116 * returns. Apps will be notified about any changes that apply to them via
1117 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1118 * effect.
1119 * <p>
1120 * This method should be called only by the VPN code.
1121 *
1122 * @param ranges the UID ranges to restrict
1123 * @param requireVpn whether the specified UID ranges must use a VPN
1124 *
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001125 * @hide
1126 */
1127 @RequiresPermission(anyOf = {
1128 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucasline257bce2021-03-22 11:51:27 +08001129 android.Manifest.permission.NETWORK_STACK,
1130 android.Manifest.permission.NETWORK_SETTINGS})
1131 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001132 public void setRequireVpnForUids(boolean requireVpn,
1133 @NonNull Collection<Range<Integer>> ranges) {
1134 Objects.requireNonNull(ranges);
1135 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1136 // This method is not necessarily expected to be used outside the system server, so
1137 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1138 // stack process, or by tests.
1139 UidRange[] rangesArray = new UidRange[ranges.size()];
1140 int index = 0;
1141 for (Range<Integer> range : ranges) {
1142 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1143 }
1144 try {
1145 mService.setRequireVpnForUids(requireVpn, rangesArray);
1146 } catch (RemoteException e) {
1147 throw e.rethrowFromSystemServer();
1148 }
1149 }
1150
1151 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001152 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1153 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1154 * but is still supported for backwards compatibility.
1155 * <p>
1156 * This type of VPN is assumed always to use the system default network, and must always declare
1157 * exactly one underlying network, which is the network that was the default when the VPN
1158 * connected.
1159 * <p>
1160 * Calling this method with {@code true} enables legacy behaviour, specifically:
1161 * <ul>
1162 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1163 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1164 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1165 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1166 * underlying the VPN.</li>
1167 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1168 * similarly replaced by the VPN network state.</li>
1169 * <li>Information on current network interfaces passed to NetworkStatsService will not
1170 * include any VPN interfaces.</li>
1171 * </ul>
1172 *
1173 * @param enabled whether legacy lockdown VPN is enabled or disabled
1174 *
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001175 * @hide
1176 */
1177 @RequiresPermission(anyOf = {
1178 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucasline257bce2021-03-22 11:51:27 +08001179 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001180 android.Manifest.permission.NETWORK_SETTINGS})
lucasline257bce2021-03-22 11:51:27 +08001181 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001182 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1183 try {
1184 mService.setLegacyLockdownVpnEnabled(enabled);
1185 } catch (RemoteException e) {
1186 throw e.rethrowFromSystemServer();
1187 }
1188 }
1189
1190 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001191 * Returns details about the currently active default data network
1192 * for a given uid. This is for internal use only to avoid spying
1193 * other apps.
1194 *
1195 * @return a {@link NetworkInfo} object for the current default network
1196 * for the given uid or {@code null} if no default network is
1197 * available for the specified uid.
1198 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001199 * {@hide}
1200 */
paulhu8e96a752019-08-12 16:25:11 +08001201 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001202 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001203 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001204 return getActiveNetworkInfoForUid(uid, false);
1205 }
1206
1207 /** {@hide} */
1208 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001209 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001210 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001211 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001212 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001213 }
1214 }
1215
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001216 /**
1217 * Returns connection status information about a particular
1218 * network type.
1219 *
1220 * @param networkType integer specifying which networkType in
1221 * which you're interested.
1222 * @return a {@link NetworkInfo} object for the requested
1223 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001224 * supported by the device. If {@code networkType} is
1225 * TYPE_VPN and a VPN is active for the calling app,
1226 * then this method will try to return one of the
1227 * underlying networks for the VPN or null if the
1228 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001229 *
Paul Jensendda8e592015-03-18 12:23:02 -04001230 * @deprecated This method does not support multiple connected networks
1231 * of the same type. Use {@link #getAllNetworks} and
1232 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001233 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001234 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001235 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001236 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001237 public NetworkInfo getNetworkInfo(int networkType) {
1238 try {
1239 return mService.getNetworkInfo(networkType);
1240 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001241 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001242 }
1243 }
1244
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001245 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001246 * Returns connection status information about a particular
1247 * Network.
1248 *
1249 * @param network {@link Network} specifying which network
1250 * in which you're interested.
1251 * @return a {@link NetworkInfo} object for the requested
1252 * network or {@code null} if the {@code Network}
1253 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001254 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001255 */
junyulai9826e7f2018-12-13 12:47:51 +08001256 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001257 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001258 @Nullable
1259 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001260 return getNetworkInfoForUid(network, Process.myUid(), false);
1261 }
1262
1263 /** {@hide} */
1264 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001265 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001266 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001267 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001268 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001269 }
1270 }
1271
1272 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001273 * Returns connection status information about all network
1274 * types supported by the device.
1275 *
1276 * @return an array of {@link NetworkInfo} objects. Check each
1277 * {@link NetworkInfo#getType} for which type each applies.
1278 *
Paul Jensendda8e592015-03-18 12:23:02 -04001279 * @deprecated This method does not support multiple connected networks
1280 * of the same type. Use {@link #getAllNetworks} and
1281 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001282 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001283 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001284 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001285 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001286 public NetworkInfo[] getAllNetworkInfo() {
1287 try {
1288 return mService.getAllNetworkInfo();
1289 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001290 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001291 }
1292 }
1293
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001294 /**
junyulaiebd15162021-03-03 12:09:05 +08001295 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1296 * connected.
1297 * @hide
1298 */
1299 @SystemApi(client = MODULE_LIBRARIES)
1300 @RequiresPermission(anyOf = {
1301 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1302 android.Manifest.permission.NETWORK_STACK,
1303 android.Manifest.permission.NETWORK_SETTINGS})
1304 @NonNull
1305 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1306 try {
1307 return mService.getAllNetworkStateSnapshot();
1308 } catch (RemoteException e) {
1309 throw e.rethrowFromSystemServer();
1310 }
1311 }
1312
1313 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001314 * Returns the {@link Network} object currently serving a given type, or
1315 * null if the given type is not connected.
1316 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001317 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001318 * @deprecated This method does not support multiple connected networks
1319 * of the same type. Use {@link #getAllNetworks} and
1320 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001321 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001322 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001323 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001324 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001325 public Network getNetworkForType(int networkType) {
1326 try {
1327 return mService.getNetworkForType(networkType);
1328 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001329 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001330 }
1331 }
1332
1333 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001334 * Returns an array of all {@link Network} currently tracked by the
1335 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001336 *
1337 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001338 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001339 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001340 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001341 public Network[] getAllNetworks() {
1342 try {
1343 return mService.getAllNetworks();
1344 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001345 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001346 }
1347 }
1348
1349 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001350 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001351 * the Networks that applications run by the given user will use by default.
1352 * @hide
1353 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001354 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001355 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1356 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001357 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001358 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001359 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001360 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001361 }
1362 }
1363
1364 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001365 * Returns the IP information for the current default network.
1366 *
1367 * @return a {@link LinkProperties} object describing the IP info
1368 * for the current default network, or {@code null} if there
1369 * is no current default network.
1370 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001371 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001372 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1373 * value of {@link #getActiveNetwork()} instead. In particular,
1374 * this method will return non-null LinkProperties even if the
1375 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001376 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001377 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001378 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001379 public LinkProperties getActiveLinkProperties() {
1380 try {
1381 return mService.getActiveLinkProperties();
1382 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001383 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001384 }
1385 }
1386
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001387 /**
1388 * Returns the IP information for a given network type.
1389 *
1390 * @param networkType the network type of interest.
1391 * @return a {@link LinkProperties} object describing the IP info
1392 * for the given networkType, or {@code null} if there is
1393 * no current default network.
1394 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001395 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001396 * @deprecated This method does not support multiple connected networks
1397 * of the same type. Use {@link #getAllNetworks},
1398 * {@link #getNetworkInfo(android.net.Network)}, and
1399 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001400 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001401 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001402 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001403 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001404 public LinkProperties getLinkProperties(int networkType) {
1405 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001406 return mService.getLinkPropertiesForType(networkType);
1407 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001408 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001409 }
1410 }
1411
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001412 /**
1413 * Get the {@link LinkProperties} for the given {@link Network}. This
1414 * will return {@code null} if the network is unknown.
1415 *
1416 * @param network The {@link Network} object identifying the network in question.
1417 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001418 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001419 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001420 @Nullable
1421 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001422 try {
1423 return mService.getLinkProperties(network);
1424 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001425 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001426 }
1427 }
1428
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001429 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001430 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001431 * will return {@code null} if the network is unknown.
1432 *
Roshan Pius951c0032020-12-22 15:10:42 -08001433 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1434 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1435 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1436 * this location sensitive information (subject to app's location permissions) will be
1437 * noted by system. To include any location sensitive data in {@link TransportInfo},
1438 * use a {@link NetworkCallback} with
1439 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1440 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001441 * @param network The {@link Network} object identifying the network in question.
Roshan Pius951c0032020-12-22 15:10:42 -08001442 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001443 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001444 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001445 @Nullable
1446 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001447 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001448 return mService.getNetworkCapabilities(
1449 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001450 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001451 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001452 }
1453 }
1454
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001455 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001456 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001457 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1458 * portal is present.
1459 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1460 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1461 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001462 * The system network validation may be using different strategies to detect captive portals,
1463 * so this method does not necessarily return a URL used by the system. It only returns a URL
1464 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001465 *
Udam Sainicd645462016-01-04 12:16:14 -08001466 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001467 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1468 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001469 */
paulhu8e96a752019-08-12 16:25:11 +08001470 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001471 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001472 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001473 public String getCaptivePortalServerUrl() {
1474 try {
1475 return mService.getCaptivePortalServerUrl();
1476 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001477 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001478 }
1479 }
1480
1481 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001482 * Tells the underlying networking system that the caller wants to
1483 * begin using the named feature. The interpretation of {@code feature}
1484 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001485 *
1486 * <p>This method requires the caller to hold either the
1487 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1488 * or the ability to modify system settings as determined by
1489 * {@link android.provider.Settings.System#canWrite}.</p>
1490 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001491 * @param networkType specifies which network the request pertains to
1492 * @param feature the name of the feature to be used
1493 * @return an integer value representing the outcome of the request.
1494 * The interpretation of this value is specific to each networking
1495 * implementation+feature combination, except that the value {@code -1}
1496 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001497 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001498 * @deprecated Deprecated in favor of the cleaner
1499 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001500 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001501 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001502 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001503 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001504 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001505 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001506 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001507 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1508 if (netCap == null) {
1509 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1510 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001511 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001512 }
1513
1514 NetworkRequest request = null;
1515 synchronized (sLegacyRequests) {
1516 LegacyRequest l = sLegacyRequests.get(netCap);
1517 if (l != null) {
1518 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1519 renewRequestLocked(l);
1520 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001521 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001522 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001523 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001524 }
1525 }
1526
1527 request = requestNetworkForFeatureLocked(netCap);
1528 }
1529 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001530 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001531 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001532 } else {
1533 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001534 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001535 }
1536 }
1537
1538 /**
1539 * Tells the underlying networking system that the caller is finished
1540 * using the named feature. The interpretation of {@code feature}
1541 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001542 *
1543 * <p>This method requires the caller to hold either the
1544 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1545 * or the ability to modify system settings as determined by
1546 * {@link android.provider.Settings.System#canWrite}.</p>
1547 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001548 * @param networkType specifies which network the request pertains to
1549 * @param feature the name of the feature that is no longer needed
1550 * @return an integer value representing the outcome of the request.
1551 * The interpretation of this value is specific to each networking
1552 * implementation+feature combination, except that the value {@code -1}
1553 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001554 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001555 * @deprecated Deprecated in favor of the cleaner
1556 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001557 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001558 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001559 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001560 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001561 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001562 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001563 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001564 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1565 if (netCap == null) {
1566 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1567 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001568 return -1;
1569 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001570
Paul Jensen49f74a32014-12-17 10:39:34 -05001571 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001572 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001573 }
1574 return 1;
1575 }
1576
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001577 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001578 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1579 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001580 switch (feature) {
1581 case "enableCBS":
1582 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1583 case "enableDUN":
1584 case "enableDUNAlways":
1585 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1586 case "enableFOTA":
1587 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1588 case "enableHIPRI":
1589 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1590 case "enableIMS":
1591 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1592 case "enableMMS":
1593 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1594 case "enableSUPL":
1595 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1596 default:
1597 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001598 }
Erik Klinece55eb12017-01-26 18:08:28 +09001599 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1600 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001601 }
1602 return null;
1603 }
1604
Robert Greenwalt802c1102014-06-02 15:32:02 -07001605 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001606 if (netCap == null) return TYPE_NONE;
1607 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1608 return TYPE_MOBILE_CBS;
1609 }
1610 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1611 return TYPE_MOBILE_IMS;
1612 }
1613 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1614 return TYPE_MOBILE_FOTA;
1615 }
1616 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1617 return TYPE_MOBILE_DUN;
1618 }
1619 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1620 return TYPE_MOBILE_SUPL;
1621 }
1622 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1623 return TYPE_MOBILE_MMS;
1624 }
1625 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1626 return TYPE_MOBILE_HIPRI;
1627 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001628 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1629 return TYPE_WIFI_P2P;
1630 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001631 return TYPE_NONE;
1632 }
1633
1634 private static class LegacyRequest {
1635 NetworkCapabilities networkCapabilities;
1636 NetworkRequest networkRequest;
1637 int expireSequenceNumber;
1638 Network currentNetwork;
1639 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001640
1641 private void clearDnsBinding() {
1642 if (currentNetwork != null) {
1643 currentNetwork = null;
1644 setProcessDefaultNetworkForHostResolution(null);
1645 }
1646 }
1647
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001648 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001649 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001650 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001651 currentNetwork = network;
1652 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001653 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001654 }
1655 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001656 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001657 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001658 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1659 }
1660 };
1661 }
1662
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001663 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001664 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1665 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001666
1667 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1668 synchronized (sLegacyRequests) {
1669 LegacyRequest l = sLegacyRequests.get(netCap);
1670 if (l != null) return l.networkRequest;
1671 }
1672 return null;
1673 }
1674
1675 private void renewRequestLocked(LegacyRequest l) {
1676 l.expireSequenceNumber++;
1677 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1678 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1679 }
1680
1681 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1682 int ourSeqNum = -1;
1683 synchronized (sLegacyRequests) {
1684 LegacyRequest l = sLegacyRequests.get(netCap);
1685 if (l == null) return;
1686 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001687 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001688 }
1689 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1690 }
1691
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001692 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001693 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1694 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001695 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001696 try {
1697 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001698 } catch (RemoteException e) {
1699 throw e.rethrowFromSystemServer();
1700 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001701 LegacyRequest l = new LegacyRequest();
1702 l.networkCapabilities = netCap;
1703 l.delay = delay;
1704 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001705 l.networkRequest = sendRequestForNetwork(
1706 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001707 if (l.networkRequest == null) return null;
1708 sLegacyRequests.put(netCap, l);
1709 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1710 return l.networkRequest;
1711 }
1712
1713 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1714 if (delay >= 0) {
1715 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001716 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001717 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1718 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001719 }
1720 }
1721
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001722 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001723 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1724 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001725 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001726 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001727 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001728 if (l == null) return false;
1729 unregisterNetworkCallback(l.networkCallback);
1730 l.clearDnsBinding();
1731 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001732 }
1733
Erik Klinece55eb12017-01-26 18:08:28 +09001734 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1735 static {
1736 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1737 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1738 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1739 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1740 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1741 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1742 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1743 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1744 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1745 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1746 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1747 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1748 }
1749
1750 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1751 static {
1752 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1753 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1754 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1755 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1756 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1757 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1758 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1759 }
1760
1761 /**
1762 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1763 * instance suitable for registering a request or callback. Throws an
1764 * IllegalArgumentException if no mapping from the legacy type to
1765 * NetworkCapabilities is known.
1766 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001767 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1768 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001769 * @hide
1770 */
1771 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1772 final NetworkCapabilities nc = new NetworkCapabilities();
1773
1774 // Map from type to transports.
1775 final int NOT_FOUND = -1;
1776 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00001777 if (transport == NOT_FOUND) {
1778 throw new IllegalArgumentException("unknown legacy type: " + type);
1779 }
Erik Klinece55eb12017-01-26 18:08:28 +09001780 nc.addTransportType(transport);
1781
1782 // Map from type to capabilities.
1783 nc.addCapability(sLegacyTypeToCapability.get(
1784 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1785 nc.maybeMarkCapabilitiesRestricted();
1786 return nc;
1787 }
1788
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001789 /** @hide */
1790 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001791 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001792 public PacketKeepaliveCallback() {
1793 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001794 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001795 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001796 public void onStarted() {}
1797 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001798 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001799 public void onStopped() {}
1800 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001801 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001802 public void onError(int error) {}
1803 }
1804
1805 /**
1806 * Allows applications to request that the system periodically send specific packets on their
1807 * behalf, using hardware offload to save battery power.
1808 *
1809 * To request that the system send keepalives, call one of the methods that return a
1810 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1811 * passing in a non-null callback. If the callback is successfully started, the callback's
1812 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1813 * specifying one of the {@code ERROR_*} constants in this class.
1814 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001815 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1816 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1817 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001818 *
junyulai4c95b082018-12-27 17:25:29 +08001819 * @deprecated Use {@link SocketKeepalive} instead.
1820 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001821 * @hide
1822 */
1823 public class PacketKeepalive {
1824
1825 private static final String TAG = "PacketKeepalive";
1826
1827 /** @hide */
1828 public static final int SUCCESS = 0;
1829
1830 /** @hide */
1831 public static final int NO_KEEPALIVE = -1;
1832
1833 /** @hide */
1834 public static final int BINDER_DIED = -10;
1835
1836 /** The specified {@code Network} is not connected. */
1837 public static final int ERROR_INVALID_NETWORK = -20;
1838 /** The specified IP addresses are invalid. For example, the specified source IP address is
1839 * not configured on the specified {@code Network}. */
1840 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1841 /** The requested port is invalid. */
1842 public static final int ERROR_INVALID_PORT = -22;
1843 /** The packet length is invalid (e.g., too long). */
1844 public static final int ERROR_INVALID_LENGTH = -23;
1845 /** The packet transmission interval is invalid (e.g., too short). */
1846 public static final int ERROR_INVALID_INTERVAL = -24;
1847
1848 /** The hardware does not support this request. */
1849 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001850 /** The hardware returned an error. */
1851 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001852
Nathan Harold0990bc82018-02-14 13:09:45 -08001853 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001854 public static final int NATT_PORT = 4500;
1855
Nathan Harold0990bc82018-02-14 13:09:45 -08001856 /** The minimum interval in seconds between keepalive packet transmissions */
1857 public static final int MIN_INTERVAL = 10;
1858
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001859 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001860 private final ISocketKeepaliveCallback mCallback;
1861 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001862
1863 private volatile Integer mSlot;
1864
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001865 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001866 public void stop() {
1867 try {
junyulai070f9ff2019-01-16 20:23:34 +08001868 mExecutor.execute(() -> {
1869 try {
1870 if (mSlot != null) {
1871 mService.stopKeepalive(mNetwork, mSlot);
1872 }
1873 } catch (RemoteException e) {
1874 Log.e(TAG, "Error stopping packet keepalive: ", e);
1875 throw e.rethrowFromSystemServer();
1876 }
1877 });
1878 } catch (RejectedExecutionException e) {
1879 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001880 }
1881 }
1882
1883 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00001884 Objects.requireNonNull(network, "network cannot be null");
1885 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001886 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001887 mExecutor = Executors.newSingleThreadExecutor();
1888 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001889 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001890 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001891 final long token = Binder.clearCallingIdentity();
1892 try {
1893 mExecutor.execute(() -> {
1894 mSlot = slot;
1895 callback.onStarted();
1896 });
1897 } finally {
1898 Binder.restoreCallingIdentity(token);
1899 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001900 }
junyulai070f9ff2019-01-16 20:23:34 +08001901
1902 @Override
1903 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001904 final long token = Binder.clearCallingIdentity();
1905 try {
1906 mExecutor.execute(() -> {
1907 mSlot = null;
1908 callback.onStopped();
1909 });
1910 } finally {
1911 Binder.restoreCallingIdentity(token);
1912 }
junyulai070f9ff2019-01-16 20:23:34 +08001913 mExecutor.shutdown();
1914 }
1915
1916 @Override
1917 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001918 final long token = Binder.clearCallingIdentity();
1919 try {
1920 mExecutor.execute(() -> {
1921 mSlot = null;
1922 callback.onError(error);
1923 });
1924 } finally {
1925 Binder.restoreCallingIdentity(token);
1926 }
junyulai070f9ff2019-01-16 20:23:34 +08001927 mExecutor.shutdown();
1928 }
1929
1930 @Override
1931 public void onDataReceived() {
1932 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1933 // this callback when data is received.
1934 }
1935 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001936 }
1937 }
1938
1939 /**
1940 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1941 *
junyulai4c95b082018-12-27 17:25:29 +08001942 * @deprecated Use {@link #createSocketKeepalive} instead.
1943 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001944 * @hide
1945 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001946 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001947 public PacketKeepalive startNattKeepalive(
1948 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1949 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1950 final PacketKeepalive k = new PacketKeepalive(network, callback);
1951 try {
junyulai070f9ff2019-01-16 20:23:34 +08001952 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001953 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1954 } catch (RemoteException e) {
1955 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001956 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001957 }
1958 return k;
1959 }
1960
Chiachang Wang619319a2021-01-15 11:06:21 +08001961 // Construct an invalid fd.
1962 private ParcelFileDescriptor createInvalidFd() {
1963 final int invalidFd = -1;
1964 return ParcelFileDescriptor.adoptFd(invalidFd);
1965 }
1966
The Android Open Source Project28527d22009-03-03 19:31:44 -08001967 /**
junyulai4c95b082018-12-27 17:25:29 +08001968 * Request that keepalives be started on a IPsec NAT-T socket.
1969 *
1970 * @param network The {@link Network} the socket is on.
1971 * @param socket The socket that needs to be kept alive.
1972 * @param source The source address of the {@link UdpEncapsulationSocket}.
1973 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1974 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1975 * must run callback sequentially, otherwise the order of callbacks cannot be
1976 * guaranteed.
1977 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1978 * changes. Must be extended by applications that use this API.
1979 *
junyulai0835a1e2019-01-08 20:04:33 +08001980 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1981 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001982 **/
junyulai7e06ad42019-03-04 22:45:36 +08001983 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001984 @NonNull UdpEncapsulationSocket socket,
1985 @NonNull InetAddress source,
1986 @NonNull InetAddress destination,
1987 @NonNull @CallbackExecutor Executor executor,
1988 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001989 ParcelFileDescriptor dup;
1990 try {
junyulai828dad12019-03-27 11:00:37 +08001991 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1992 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001993 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1994 } catch (IOException ignored) {
1995 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1996 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001997 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001998 }
1999 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2000 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002001 }
2002
2003 /**
2004 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2005 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2006 *
2007 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002008 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2009 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2010 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002011 * @param source The source address of the {@link UdpEncapsulationSocket}.
2012 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2013 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2014 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2015 * must run callback sequentially, otherwise the order of callbacks cannot be
2016 * guaranteed.
2017 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2018 * changes. Must be extended by applications that use this API.
2019 *
junyulai0835a1e2019-01-08 20:04:33 +08002020 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2021 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002022 * @hide
2023 */
2024 @SystemApi
2025 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002026 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2027 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002028 @NonNull InetAddress source,
2029 @NonNull InetAddress destination,
2030 @NonNull @CallbackExecutor Executor executor,
2031 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002032 ParcelFileDescriptor dup;
2033 try {
junyulai828dad12019-03-27 11:00:37 +08002034 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002035 dup = pfd.dup();
2036 } catch (IOException ignored) {
2037 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2038 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002039 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002040 }
2041 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANce355502021-03-11 10:56:49 +00002042 -1 /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002043 }
2044
2045 /**
junyulai0835a1e2019-01-08 20:04:33 +08002046 * Request that keepalives be started on a TCP socket.
2047 * The socket must be established.
2048 *
2049 * @param network The {@link Network} the socket is on.
2050 * @param socket The socket that needs to be kept alive.
2051 * @param executor The executor on which callback will be invoked. This implementation assumes
2052 * the provided {@link Executor} runs the callbacks in sequence with no
2053 * concurrency. Failing this, no guarantee of correctness can be made. It is
2054 * the responsibility of the caller to ensure the executor provides this
2055 * guarantee. A simple way of creating such an executor is with the standard
2056 * tool {@code Executors.newSingleThreadExecutor}.
2057 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2058 * changes. Must be extended by applications that use this API.
2059 *
2060 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2061 * given socket.
2062 * @hide
2063 */
2064 @SystemApi
2065 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002066 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002067 @NonNull Socket socket,
2068 @NonNull Executor executor,
2069 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002070 ParcelFileDescriptor dup;
2071 try {
2072 dup = ParcelFileDescriptor.fromSocket(socket);
2073 } catch (UncheckedIOException ignored) {
2074 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2075 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002076 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002077 }
2078 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002079 }
2080
2081 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002082 * Ensure that a network route exists to deliver traffic to the specified
2083 * host via the specified network interface. An attempt to add a route that
2084 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002085 *
2086 * <p>This method requires the caller to hold either the
2087 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2088 * or the ability to modify system settings as determined by
2089 * {@link android.provider.Settings.System#canWrite}.</p>
2090 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002091 * @param networkType the type of the network over which traffic to the specified
2092 * host is to be routed
2093 * @param hostAddress the IP address of the host to which the route is desired
2094 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002095 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002096 * @deprecated Deprecated in favor of the
2097 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2098 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002099 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002100 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002101 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002102 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002103 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002104 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002105 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002106 }
2107
2108 /**
2109 * Ensure that a network route exists to deliver traffic to the specified
2110 * host via the specified network interface. An attempt to add a route that
2111 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002112 *
2113 * <p>This method requires the caller to hold either the
2114 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2115 * or the ability to modify system settings as determined by
2116 * {@link android.provider.Settings.System#canWrite}.</p>
2117 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002118 * @param networkType the type of the network over which traffic to the specified
2119 * host is to be routed
2120 * @param hostAddress the IP address of the host to which the route is desired
2121 * @return {@code true} on success, {@code false} on failure
2122 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002123 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002124 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002125 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002126 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002127 @UnsupportedAppUsage
lucasline257bce2021-03-22 11:51:27 +08002128 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002129 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002130 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002131 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002132 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2133 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002135 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002136 }
2137 }
2138
2139 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002140 * @return the context's attribution tag
2141 */
2142 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2143 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002144 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002145 }
2146
2147 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002148 * Returns the value of the setting for background data usage. If false,
2149 * applications should not use the network if the application is not in the
2150 * foreground. Developers should respect this setting, and check the value
2151 * of this before performing any background data operations.
2152 * <p>
2153 * All applications that have background services that use the network
2154 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002155 * <p>
Scott Main50589142011-10-06 18:32:43 -07002156 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002157 * background data depends on several combined factors, and this method will
2158 * always return {@code true}. Instead, when background data is unavailable,
2159 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002160 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002161 * @return Whether background data usage is allowed.
2162 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002163 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002164 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002165 // assume that background data is allowed; final authority is
2166 // NetworkInfo which may be blocked.
2167 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002168 }
2169
2170 /**
2171 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002172 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002173 * @param allowBackgroundData Whether an application should use data while
2174 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002175 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002176 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2177 * @see #getBackgroundDataSetting()
2178 * @hide
2179 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002180 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002181 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002182 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002183 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002184 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002185
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002186 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002187 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002188 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002189 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002190 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002191 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002192 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002193 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2194 if (tm != null) {
2195 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2196 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2197 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2198 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2199 + " retVal=" + retVal);
2200 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002201 }
Wink Saville689f7042014-12-05 11:10:30 -08002202 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002203 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002204 }
2205
The Android Open Source Project28527d22009-03-03 19:31:44 -08002206 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002207 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002208 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002209 */
2210 public interface OnNetworkActiveListener {
2211 /**
2212 * Called on the main thread of the process to report that the current data network
2213 * has become active, and it is now a good time to perform any pending network
2214 * operations. Note that this listener only tells you when the network becomes
2215 * active; if at any other time you want to know whether it is active (and thus okay
2216 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002217 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002218 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002219 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002220 }
2221
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002222 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002223 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002224
2225 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002226 * Start listening to reports when the system's default data network is active, meaning it is
2227 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2228 * to determine the current state of the system's default network after registering the
2229 * listener.
2230 * <p>
2231 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002232 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002233 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002234 *
2235 * @param l The listener to be told when the network is active.
2236 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002237 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002238 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2239 @Override
2240 public void onNetworkActive() throws RemoteException {
2241 l.onNetworkActive();
2242 }
2243 };
2244
2245 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002246 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002247 mNetworkActivityListeners.put(l, rl);
2248 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002249 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002250 }
2251 }
2252
2253 /**
2254 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002255 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002256 *
2257 * @param l Previously registered listener.
2258 */
Chalard Jean158702d2019-01-07 19:26:34 +09002259 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002260 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002261 if (rl == null) {
2262 throw new IllegalArgumentException("Listener was not registered.");
2263 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002264 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002265 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002266 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002267 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002268 }
2269 }
2270
2271 /**
2272 * Return whether the data network is currently active. An active network means that
2273 * it is currently in a high power state for performing data transmission. On some
2274 * types of networks, it may be expensive to move and stay in such a state, so it is
2275 * more power efficient to batch network traffic together when the radio is already in
2276 * this state. This method tells you whether right now is currently a good time to
2277 * initiate network traffic, as the network is already active.
2278 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002279 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002280 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002281 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002282 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002283 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002284 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002285 }
2286
2287 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002288 * {@hide}
2289 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002290 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002291 mContext = Objects.requireNonNull(context, "missing context");
2292 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002293 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002294 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002295 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002296
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002297 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002298 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002299 public static ConnectivityManager from(Context context) {
2300 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2301 }
2302
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002303 /** @hide */
2304 public NetworkRequest getDefaultRequest() {
2305 try {
2306 // This is not racy as the default request is final in ConnectivityService.
2307 return mService.getDefaultRequest();
2308 } catch (RemoteException e) {
2309 throw e.rethrowFromSystemServer();
2310 }
2311 }
2312
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002313 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002314 * Check if the package is a allowed to write settings. This also accounts that such an access
2315 * happened.
2316 *
2317 * @return {@code true} iff the package is allowed to write settings.
2318 */
2319 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2320 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2321 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2322 boolean throwException) {
2323 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2324 throwException);
2325 }
2326
2327 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002328 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2329 * situations where a Context pointer is unavailable.
2330 * @hide
2331 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002332 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002333 static ConnectivityManager getInstanceOrNull() {
2334 return sInstance;
2335 }
2336
2337 /**
2338 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2339 * situations where a Context pointer is unavailable.
2340 * @hide
2341 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002342 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002343 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002344 private static ConnectivityManager getInstance() {
2345 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002346 throw new IllegalStateException("No ConnectivityManager yet constructed");
2347 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002348 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002349 }
2350
2351 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002352 * Get the set of tetherable, available interfaces. This list is limited by
2353 * device configuration and current interface existence.
2354 *
2355 * @return an array of 0 or more Strings of tetherable interface names.
2356 *
markchien6ae63e52020-01-21 13:11:06 +08002357 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002358 * {@hide}
2359 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002360 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002361 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002362 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002363 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002364 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002365 }
2366
2367 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002368 * Get the set of tethered interfaces.
2369 *
2370 * @return an array of 0 or more String of currently tethered interface names.
2371 *
markchien6ae63e52020-01-21 13:11:06 +08002372 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002373 * {@hide}
2374 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002375 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002376 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002377 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002378 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002379 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002380 }
2381
2382 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002383 * Get the set of interface names which attempted to tether but
2384 * failed. Re-attempting to tether may cause them to reset to the Tethered
2385 * state. Alternatively, causing the interface to be destroyed and recreated
2386 * may cause them to reset to the available state.
2387 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2388 * information on the cause of the errors.
2389 *
2390 * @return an array of 0 or more String indicating the interface names
2391 * which failed to tether.
2392 *
markchien6ae63e52020-01-21 13:11:06 +08002393 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002394 * {@hide}
2395 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002396 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002397 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002398 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002399 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002400 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002401 }
2402
2403 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002404 * Get the set of tethered dhcp ranges.
2405 *
markchien2e6ba522020-02-14 11:55:48 +08002406 * @deprecated This method is not supported.
2407 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002408 * {@hide}
2409 */
paulhu8e96a752019-08-12 16:25:11 +08002410 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002411 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002412 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002413 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002414 }
2415
2416 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002417 * Attempt to tether the named interface. This will setup a dhcp server
2418 * on the interface, forward and NAT IP packets and forward DNS requests
2419 * to the best active upstream network interface. Note that if no upstream
2420 * IP network interface is available, dhcp will still run and traffic will be
2421 * allowed between the tethered devices and this device, though upstream net
2422 * access will of course fail until an upstream network interface becomes
2423 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002424 *
2425 * <p>This method requires the caller to hold either the
2426 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2427 * or the ability to modify system settings as determined by
2428 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002429 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002430 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2431 * and WifiStateMachine which need direct access. All other clients should use
2432 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2433 * logic.</p>
2434 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002435 * @param iface the interface name to tether.
2436 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002437 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002438 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002439 * {@hide}
2440 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002441 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002442 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002443 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002444 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002445 }
2446
2447 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002448 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002449 *
2450 * <p>This method requires the caller to hold either the
2451 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2452 * or the ability to modify system settings as determined by
2453 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002454 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002455 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2456 * and WifiStateMachine which need direct access. All other clients should use
2457 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2458 * logic.</p>
2459 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002460 * @param iface the interface name to untether.
2461 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2462 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002463 * {@hide}
2464 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002465 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002466 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002467 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002468 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002469 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002470
2471 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002472 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002473 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002474 * due to device configuration.
2475 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002476 * <p>If this app does not have permission to use this API, it will always
2477 * return false rather than throw an exception.</p>
2478 *
2479 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2480 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2481 *
2482 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2483 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2484 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002485 * @return a boolean - {@code true} indicating Tethering is supported.
2486 *
markchien6ae63e52020-01-21 13:11:06 +08002487 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002488 * {@hide}
2489 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002490 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002491 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2492 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002493 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002494 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002495 }
2496
2497 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002498 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002499 *
2500 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002501 * @hide
2502 */
2503 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002504 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002505 public static abstract class OnStartTetheringCallback {
2506 /**
2507 * Called when tethering has been successfully started.
2508 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002509 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002510
2511 /**
2512 * Called when starting tethering failed.
2513 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002514 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002515 }
2516
2517 /**
2518 * Convenient overload for
2519 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2520 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002521 *
2522 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002523 * @hide
2524 */
2525 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002526 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002527 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002528 public void startTethering(int type, boolean showProvisioningUi,
2529 final OnStartTetheringCallback callback) {
2530 startTethering(type, showProvisioningUi, callback, null);
2531 }
2532
2533 /**
2534 * Runs tether provisioning for the given type if needed and then starts tethering if
2535 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2536 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2537 * schedules tether provisioning re-checks if appropriate.
2538 *
2539 * @param type The type of tethering to start. Must be one of
2540 * {@link ConnectivityManager.TETHERING_WIFI},
2541 * {@link ConnectivityManager.TETHERING_USB}, or
2542 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2543 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2544 * is one. This should be true the first time this function is called and also any time
2545 * the user can see this UI. It gives users information from their carrier about the
2546 * check failing and how they can sign up for tethering if possible.
2547 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2548 * of the result of trying to tether.
2549 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002550 *
2551 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002552 * @hide
2553 */
2554 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002555 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002556 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002557 public void startTethering(int type, boolean showProvisioningUi,
2558 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002559 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002560
markchien91c78e52020-01-20 19:31:56 +08002561 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002562 @Override
markchien91c78e52020-01-20 19:31:56 +08002563 public void execute(Runnable command) {
2564 if (handler == null) {
2565 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002566 } else {
markchien91c78e52020-01-20 19:31:56 +08002567 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002568 }
2569 }
2570 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002571
markchien91c78e52020-01-20 19:31:56 +08002572 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2573 @Override
2574 public void onTetheringStarted() {
2575 callback.onTetheringStarted();
2576 }
2577
2578 @Override
markchienf47d8342020-03-19 13:37:43 +08002579 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002580 callback.onTetheringFailed();
2581 }
2582 };
2583
2584 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002585 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002586
Amos Bianchia9b415a2020-03-04 11:07:38 -08002587 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002588 }
2589
2590 /**
2591 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2592 * applicable.
2593 *
2594 * @param type The type of tethering to stop. Must be one of
2595 * {@link ConnectivityManager.TETHERING_WIFI},
2596 * {@link ConnectivityManager.TETHERING_USB}, or
2597 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002598 *
2599 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002600 * @hide
2601 */
2602 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002603 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002604 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002605 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002606 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002607 }
2608
2609 /**
markchien4ef53e82019-02-27 14:56:11 +08002610 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2611 * upstream status.
2612 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002613 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002614 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002615 */
2616 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002617 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002618 public abstract static class OnTetheringEventCallback {
2619
2620 /**
2621 * Called when tethering upstream changed. This can be called multiple times and can be
2622 * called any time.
2623 *
2624 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2625 * have any upstream.
2626 */
2627 public void onUpstreamChanged(@Nullable Network network) {}
2628 }
2629
markchien6ae63e52020-01-21 13:11:06 +08002630 @GuardedBy("mTetheringEventCallbacks")
2631 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2632 mTetheringEventCallbacks = new ArrayMap<>();
2633
markchien4ef53e82019-02-27 14:56:11 +08002634 /**
2635 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002636 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002637 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2638 * with a null argument. The same callback object cannot be registered twice.
2639 *
2640 * @param executor the executor on which callback will be invoked.
2641 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002642 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002643 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002644 * @hide
2645 */
2646 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002647 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002648 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2649 public void registerTetheringEventCallback(
2650 @NonNull @CallbackExecutor Executor executor,
2651 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002652 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchien4ef53e82019-02-27 14:56:11 +08002653
markchien6ae63e52020-01-21 13:11:06 +08002654 final TetheringEventCallback tetherCallback =
2655 new TetheringEventCallback() {
2656 @Override
2657 public void onUpstreamChanged(@Nullable Network network) {
2658 callback.onUpstreamChanged(network);
2659 }
2660 };
2661
2662 synchronized (mTetheringEventCallbacks) {
2663 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002664 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002665 }
markchien4ef53e82019-02-27 14:56:11 +08002666 }
2667
2668 /**
2669 * Remove tethering event callback previously registered with
2670 * {@link #registerTetheringEventCallback}.
2671 *
2672 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002673 *
2674 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002675 * @hide
2676 */
2677 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002678 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002679 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2680 public void unregisterTetheringEventCallback(
2681 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002682 Objects.requireNonNull(callback, "The callback must be non-null");
2683 synchronized (mTetheringEventCallbacks) {
2684 final TetheringEventCallback tetherCallback =
2685 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002686 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002687 }
markchien4ef53e82019-02-27 14:56:11 +08002688 }
2689
2690
2691 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002692 * Get the list of regular expressions that define any tetherable
2693 * USB network interfaces. If USB tethering is not supported by the
2694 * device, this list should be empty.
2695 *
2696 * @return an array of 0 or more regular expression Strings defining
2697 * what interfaces are considered tetherable usb interfaces.
2698 *
markchien6ae63e52020-01-21 13:11:06 +08002699 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002700 * {@hide}
2701 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002702 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002703 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002704 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002705 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002706 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002707 }
2708
2709 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002710 * Get the list of regular expressions that define any tetherable
2711 * Wifi network interfaces. If Wifi tethering is not supported by the
2712 * device, this list should be empty.
2713 *
2714 * @return an array of 0 or more regular expression Strings defining
2715 * what interfaces are considered tetherable wifi interfaces.
2716 *
markchien6ae63e52020-01-21 13:11:06 +08002717 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002718 * {@hide}
2719 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002720 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002721 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002722 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002723 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002724 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002725 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002726
Danica Chang96567052010-08-11 14:54:43 -07002727 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002728 * Get the list of regular expressions that define any tetherable
2729 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2730 * device, this list should be empty.
2731 *
2732 * @return an array of 0 or more regular expression Strings defining
2733 * what interfaces are considered tetherable bluetooth interfaces.
2734 *
markchien6ae63e52020-01-21 13:11:06 +08002735 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2736 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002737 * {@hide}
2738 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002739 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002740 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002741 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002742 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002743 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002744 }
2745
Mike Lockwooded4a1742011-07-19 13:04:47 -07002746 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002747 * Attempt to both alter the mode of USB and Tethering of USB. A
2748 * utility method to deal with some of the complexity of USB - will
2749 * attempt to switch to Rndis and subsequently tether the resulting
2750 * interface on {@code true} or turn off tethering and switch off
2751 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002752 *
2753 * <p>This method requires the caller to hold either the
2754 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2755 * or the ability to modify system settings as determined by
2756 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002757 *
2758 * @param enable a boolean - {@code true} to enable tethering
2759 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002760 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002761 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002762 * {@hide}
2763 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002764 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002765 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002766 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002767 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002768 }
2769
markchien6ae63e52020-01-21 13:11:06 +08002770 /**
2771 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2772 * {@hide}
2773 */
markchien0f45bb92019-01-16 17:44:13 +08002774 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002775 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002776 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002777 /**
2778 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2779 * {@hide}
2780 */
2781 @Deprecated
2782 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2783 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2784 /**
2785 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2786 * {@hide}
2787 */
2788 @Deprecated
2789 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2790 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2791 /**
2792 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2793 * {@hide}
2794 */
2795 @Deprecated
2796 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2797 /**
2798 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2799 * {@hide}
2800 */
2801 @Deprecated
2802 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2803 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2804 /**
markchienf47d8342020-03-19 13:37:43 +08002805 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002806 * {@hide}
2807 */
2808 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002809 public static final int TETHER_ERROR_MASTER_ERROR =
2810 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002811 /**
2812 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2813 * {@hide}
2814 */
2815 @Deprecated
2816 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2817 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2818 /**
2819 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2820 * {@hide}
2821 */
2822 @Deprecated
2823 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2824 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2825 /**
markchienf47d8342020-03-19 13:37:43 +08002826 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002827 * {@hide}
2828 */
2829 @Deprecated
2830 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002831 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002832 /**
markchienf47d8342020-03-19 13:37:43 +08002833 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002834 * {@hide}
2835 */
2836 @Deprecated
2837 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002838 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002839 /**
2840 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2841 * {@hide}
2842 */
2843 @Deprecated
2844 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2845 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2846 /**
markchienf47d8342020-03-19 13:37:43 +08002847 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002848 * {@hide}
2849 */
markchien0f45bb92019-01-16 17:44:13 +08002850 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002851 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002852 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002853 /**
2854 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2855 * {@hide}
2856 */
2857 @Deprecated
2858 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2859 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2860 /**
2861 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2862 * {@hide}
2863 */
markchien0f45bb92019-01-16 17:44:13 +08002864 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002865 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002866 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002867
2868 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002869 * Get a more detailed error code after a Tethering or Untethering
2870 * request asynchronously failed.
2871 *
2872 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002873 * @return error The error code of the last error tethering or untethering the named
2874 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002875 *
markchien6ae63e52020-01-21 13:11:06 +08002876 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002877 * {@hide}
2878 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002879 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002880 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002881 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002882 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002883 int error = mTetheringManager.getLastTetherError(iface);
2884 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2885 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2886 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2887 // instead.
2888 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2889 }
2890 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002891 }
2892
markchienbf5ab012019-03-06 16:25:00 +08002893 /** @hide */
2894 @Retention(RetentionPolicy.SOURCE)
2895 @IntDef(value = {
2896 TETHER_ERROR_NO_ERROR,
2897 TETHER_ERROR_PROVISION_FAILED,
2898 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2899 })
2900 public @interface EntitlementResultCode {
2901 }
2902
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002903 /**
markchienbf5ab012019-03-06 16:25:00 +08002904 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002905 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002906 *
2907 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002908 * @hide
2909 */
2910 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002911 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002912 public interface OnTetheringEntitlementResultListener {
2913 /**
2914 * Called to notify entitlement result.
2915 *
2916 * @param resultCode an int value of entitlement result. It may be one of
2917 * {@link #TETHER_ERROR_NO_ERROR},
2918 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2919 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2920 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002921 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002922 }
2923
2924 /**
markchien0f45bb92019-01-16 17:44:13 +08002925 * Get the last value of the entitlement check on this downstream. If the cached value is
2926 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2927 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2928 * guaranteed that the UI-based entitlement check will complete in any specific time period
2929 * and may in fact never complete. Any successful entitlement check the platform performs for
2930 * any reason will update the cached value.
2931 *
2932 * @param type the downstream type of tethering. Must be one of
2933 * {@link #TETHERING_WIFI},
2934 * {@link #TETHERING_USB}, or
2935 * {@link #TETHERING_BLUETOOTH}.
2936 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002937 * @param executor the executor on which callback will be invoked.
2938 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2939 * notify the caller of the result of entitlement check. The listener may be called zero
2940 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002941 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002942 * {@hide}
2943 */
2944 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002945 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002946 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002947 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2948 @NonNull @CallbackExecutor Executor executor,
2949 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002950 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchienbf5ab012019-03-06 16:25:00 +08002951 ResultReceiver wrappedListener = new ResultReceiver(null) {
2952 @Override
2953 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08002954 final long token = Binder.clearCallingIdentity();
2955 try {
2956 executor.execute(() -> {
2957 listener.onTetheringEntitlementResult(resultCode);
2958 });
2959 } finally {
2960 Binder.restoreCallingIdentity(token);
2961 }
markchienbf5ab012019-03-06 16:25:00 +08002962 }
2963 };
2964
Amos Bianchia9b415a2020-03-04 11:07:38 -08002965 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002966 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002967 }
2968
2969 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002970 * Report network connectivity status. This is currently used only
2971 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002972 * <p>This method requires the caller to hold the permission
2973 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002974 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002975 * @param networkType The type of network you want to report on
2976 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002977 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002978 * {@hide}
2979 */
2980 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002981 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002982 try {
2983 mService.reportInetCondition(networkType, percentage);
2984 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002985 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002986 }
2987 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002988
2989 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002990 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07002991 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002992 * the framework to re-evaluate network connectivity and/or switch to another
2993 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002994 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002995 * @param network The {@link Network} the application was attempting to use
2996 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04002997 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2998 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002999 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003000 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003001 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003002 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003003 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003004 // One of these will be ignored because it matches system's current state.
3005 // The other will trigger the necessary reevaluation.
3006 mService.reportNetworkConnectivity(network, true);
3007 mService.reportNetworkConnectivity(network, false);
3008 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003009 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003010 }
3011 }
3012
3013 /**
3014 * Report to the framework whether a network has working connectivity.
3015 * This provides a hint to the system that a particular network is providing
3016 * working connectivity or not. In response the framework may re-evaluate
3017 * the network's connectivity and might take further action thereafter.
3018 *
3019 * @param network The {@link Network} the application was attempting to use
3020 * or {@code null} to indicate the current default network.
3021 * @param hasConnectivity {@code true} if the application was able to successfully access the
3022 * Internet using {@code network} or {@code false} if not.
3023 */
Chalard Jean158702d2019-01-07 19:26:34 +09003024 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003025 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003026 try {
3027 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003028 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003029 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003030 }
3031 }
3032
3033 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003034 * Set a network-independent global http proxy. This is not normally what you want
3035 * for typical HTTP proxies - they are general network dependent. However if you're
3036 * doing something unusual like general internal filtering this may be useful. On
3037 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003038 *
3039 * @param p A {@link ProxyInfo} object defining the new global
3040 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003041 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003042 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003043 @SystemApi(client = MODULE_LIBRARIES)
paulhu8e96a752019-08-12 16:25:11 +08003044 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang4d513572021-03-18 09:44:34 +08003045 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003046 try {
3047 mService.setGlobalProxy(p);
3048 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003049 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003050 }
3051 }
3052
3053 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003054 * Retrieve any network-independent global HTTP proxy.
3055 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003056 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003057 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003058 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003059 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003060 @SystemApi(client = MODULE_LIBRARIES)
3061 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04003062 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003063 try {
3064 return mService.getGlobalProxy();
3065 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003066 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003067 }
3068 }
3069
3070 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003071 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3072 * network-specific HTTP proxy. If {@code network} is null, the
3073 * network-specific proxy returned is the proxy of the default active
3074 * network.
3075 *
3076 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3077 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3078 * or when {@code network} is {@code null},
3079 * the {@code ProxyInfo} for the default active network. Returns
3080 * {@code null} when no proxy applies or the caller doesn't have
3081 * permission to use {@code network}.
3082 * @hide
3083 */
3084 public ProxyInfo getProxyForNetwork(Network network) {
3085 try {
3086 return mService.getProxyForNetwork(network);
3087 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003088 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003089 }
3090 }
3091
3092 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003093 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3094 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003095 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003096 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003097 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003098 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003099 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003100 */
Chalard Jean158702d2019-01-07 19:26:34 +09003101 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003102 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003103 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003104 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003105
3106 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003107 * Returns true if the hardware supports the given network type
3108 * else it returns false. This doesn't indicate we have coverage
3109 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003110 * hardware supports it. For example a GSM phone without a SIM
3111 * should still return {@code true} for mobile data, but a wifi only
3112 * tablet would return {@code false}.
3113 *
3114 * @param networkType The network type we'd like to check
3115 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003116 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003117 * @hide
3118 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003119 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003120 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003121 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003122 public boolean isNetworkSupported(int networkType) {
3123 try {
3124 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003125 } catch (RemoteException e) {
3126 throw e.rethrowFromSystemServer();
3127 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003128 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003129
3130 /**
3131 * Returns if the currently active data network is metered. A network is
3132 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003133 * that connection due to monetary costs, data limitations or
3134 * battery/performance issues. You should check this before doing large
3135 * data transfers, and warn the user or delay the operation until another
3136 * network is available.
3137 *
3138 * @return {@code true} if large transfers should be avoided, otherwise
3139 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003140 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003141 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003142 public boolean isActiveNetworkMetered() {
3143 try {
3144 return mService.isActiveNetworkMetered();
3145 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003146 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003147 }
3148 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003149
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003150 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003151 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003152 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003153 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003154 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003155 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003156 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003157 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003158 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003159 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003160 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003161 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003162 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003163 }
3164 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003165
3166 /**
3167 * Set the value for enabling/disabling airplane mode
3168 *
3169 * @param enable whether to enable airplane mode or not
3170 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003171 * @hide
3172 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003173 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003174 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003175 android.Manifest.permission.NETWORK_SETTINGS,
3176 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3177 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003178 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003179 public void setAirplaneMode(boolean enable) {
3180 try {
3181 mService.setAirplaneMode(enable);
3182 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003183 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003184 }
3185 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003186
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003187 /**
3188 * Registers the specified {@link NetworkProvider}.
3189 * Each listener must only be registered once. The listener can be unregistered with
3190 * {@link #unregisterNetworkProvider}.
3191 *
3192 * @param provider the provider to register
3193 * @return the ID of the provider. This ID must be used by the provider when registering
3194 * {@link android.net.NetworkAgent}s.
3195 * @hide
3196 */
3197 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003198 @RequiresPermission(anyOf = {
3199 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3200 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003201 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3202 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003203 throw new IllegalStateException("NetworkProviders can only be registered once");
3204 }
3205
3206 try {
3207 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3208 provider.getName());
3209 provider.setProviderId(providerId);
3210 } catch (RemoteException e) {
3211 throw e.rethrowFromSystemServer();
3212 }
3213 return provider.getProviderId();
3214 }
3215
3216 /**
3217 * Unregisters the specified NetworkProvider.
3218 *
3219 * @param provider the provider to unregister
3220 * @hide
3221 */
3222 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003223 @RequiresPermission(anyOf = {
3224 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3225 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003226 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3227 try {
3228 mService.unregisterNetworkProvider(provider.getMessenger());
3229 } catch (RemoteException e) {
3230 throw e.rethrowFromSystemServer();
3231 }
3232 provider.setProviderId(NetworkProvider.ID_NONE);
3233 }
3234
3235
3236 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003237 @RequiresPermission(anyOf = {
3238 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3239 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003240 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3241 try {
3242 mService.declareNetworkRequestUnfulfillable(request);
3243 } catch (RemoteException e) {
3244 throw e.rethrowFromSystemServer();
3245 }
3246 }
3247
Paul Jensen1f567382015-02-13 14:18:39 -05003248 /**
3249 * @hide
3250 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003251 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003252 */
paulhub6ba8e82020-03-04 09:43:41 +08003253 @RequiresPermission(anyOf = {
3254 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3255 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003256 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jean28018572020-12-21 18:36:52 +09003257 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3258 int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003259 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003260 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003261 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003262 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003263 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003264 }
3265
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003266 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003267 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3268 * changes. Should be extended by applications wanting notifications.
3269 *
3270 * A {@code NetworkCallback} is registered by calling
3271 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3272 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003273 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003274 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3275 * A {@code NetworkCallback} should be registered at most once at any time.
3276 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003277 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003278 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003279 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003280 * No flags associated with this callback.
3281 * @hide
3282 */
3283 public static final int FLAG_NONE = 0;
3284 /**
3285 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3286 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3287 * <p>
3288 * These include:
3289 * <li> Some transport info instances (retrieved via
3290 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3291 * contain location sensitive information.
3292 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3293 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3294 * </p>
3295 * <p>
3296 * Note:
3297 * <li> Retrieving this location sensitive information (subject to app's location
3298 * permissions) will be noted by system. </li>
3299 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3300 * not include location sensitive info.
3301 * </p>
3302 */
3303 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3304
3305 /** @hide */
3306 @Retention(RetentionPolicy.SOURCE)
3307 @IntDef(flag = true, prefix = "FLAG_", value = {
3308 FLAG_NONE,
3309 FLAG_INCLUDE_LOCATION_INFO
3310 })
3311 public @interface Flag { }
3312
3313 /**
3314 * All the valid flags for error checking.
3315 */
3316 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3317
3318 public NetworkCallback() {
3319 this(FLAG_NONE);
3320 }
3321
3322 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003323 if ((flags & VALID_FLAGS) != flags) {
3324 throw new IllegalArgumentException("Invalid flags");
3325 }
Roshan Pius951c0032020-12-22 15:10:42 -08003326 mFlags = flags;
3327 }
3328
3329 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003330 * Called when the framework connects to a new network to evaluate whether it satisfies this
3331 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3332 * callback. There is no guarantee that this new network will satisfy any requests, or that
3333 * the network will stay connected for longer than the time necessary to evaluate it.
3334 * <p>
3335 * Most applications <b>should not</b> act on this callback, and should instead use
3336 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3337 * the framework in properly evaluating the network &mdash; for example, an application that
3338 * can automatically log in to a captive portal without user intervention.
3339 *
3340 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003341 *
3342 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003343 */
paulhu1a407652019-03-22 16:35:06 +08003344 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003345
3346 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003347 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003348 * This callback may be called more than once if the {@link Network} that is
3349 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003350 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003351 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003352 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3353 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003354 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003355 * @hide
3356 */
paulhu1a407652019-03-22 16:35:06 +08003357 public void onAvailable(@NonNull Network network,
3358 @NonNull NetworkCapabilities networkCapabilities,
3359 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003360 // Internally only this method is called when a new network is available, and
3361 // it calls the callback in the same way and order that older versions used
3362 // to call so as not to change the behavior.
3363 onAvailable(network);
3364 if (!networkCapabilities.hasCapability(
3365 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3366 onNetworkSuspended(network);
3367 }
3368 onCapabilitiesChanged(network, networkCapabilities);
3369 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003370 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003371 }
3372
3373 /**
3374 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003375 *
3376 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3377 * be available at the same time, and onAvailable will be called for each of these as they
3378 * appear.
3379 *
3380 * <p>For callbacks registered with {@link #requestNetwork} and
3381 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3382 * is the new best network for this request and is now tracked by this callback ; this
3383 * callback will no longer receive method calls about other networks that may have been
3384 * passed to this method previously. The previously-best network may have disconnected, or
3385 * it may still be around and the newly-best network may simply be better.
3386 *
3387 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3388 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3389 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3390 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3391 *
3392 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3393 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3394 * this callback as this is prone to race conditions (there is no guarantee the objects
3395 * returned by these methods will be current). Instead, wait for a call to
3396 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3397 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3398 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003399 *
3400 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003401 */
paulhu1a407652019-03-22 16:35:06 +08003402 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003403
3404 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003405 * Called when the network is about to be lost, typically because there are no outstanding
3406 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3407 * with the new replacement network for graceful handover. This method is not guaranteed
3408 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3409 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003410 *
Chalard Jean01378b62019-08-30 16:27:28 +09003411 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3412 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3413 * this callback as this is prone to race conditions ; calling these methods while in a
3414 * callback may return an outdated or even a null object.
3415 *
3416 * @param network The {@link Network} that is about to be lost.
3417 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3418 * connected for graceful handover; note that the network may still
3419 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003420 */
paulhu1a407652019-03-22 16:35:06 +08003421 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003422
3423 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003424 * Called when a network disconnects or otherwise no longer satisfies this request or
3425 * callback.
3426 *
3427 * <p>If the callback was registered with requestNetwork() or
3428 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3429 * returned by onAvailable() when that network is lost and no other network satisfies
3430 * the criteria of the request.
3431 *
3432 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3433 * each network which no longer satisfies the criteria of the callback.
3434 *
3435 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3436 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3437 * this callback as this is prone to race conditions ; calling these methods while in a
3438 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003439 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003440 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003441 */
paulhu1a407652019-03-22 16:35:06 +08003442 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003443
3444 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003445 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003446 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3447 * requested network request cannot be fulfilled (whether or not a timeout was
3448 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003449 * {@link NetworkRequest} will have already been removed and released, as if
3450 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003451 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003452 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003453
3454 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003455 * Called when the network corresponding to this request changes capabilities but still
3456 * satisfies the requested criteria.
3457 *
3458 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3459 * to be called immediately after {@link #onAvailable}.
3460 *
3461 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3462 * ConnectivityManager methods in this callback as this is prone to race conditions :
3463 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003464 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003465 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius951c0032020-12-22 15:10:42 -08003466 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003467 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003468 */
paulhu1a407652019-03-22 16:35:06 +08003469 public void onCapabilitiesChanged(@NonNull Network network,
3470 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003471
3472 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003473 * Called when the network corresponding to this request changes {@link LinkProperties}.
3474 *
3475 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3476 * to be called immediately after {@link #onAvailable}.
3477 *
3478 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3479 * ConnectivityManager methods in this callback as this is prone to race conditions :
3480 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003481 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003482 * @param network The {@link Network} whose link properties have changed.
3483 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003484 */
paulhu1a407652019-03-22 16:35:06 +08003485 public void onLinkPropertiesChanged(@NonNull Network network,
3486 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003487
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003488 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003489 * Called when the network the framework connected to for this request suspends data
3490 * transmission temporarily.
3491 *
3492 * <p>This generally means that while the TCP connections are still live temporarily
3493 * network data fails to transfer. To give a specific example, this is used on cellular
3494 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3495 * means read operations on sockets on this network will block once the buffers are
3496 * drained, and write operations will block once the buffers are full.
3497 *
3498 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3499 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3500 * this callback as this is prone to race conditions (there is no guarantee the objects
3501 * returned by these methods will be current).
3502 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003503 * @hide
3504 */
paulhu1a407652019-03-22 16:35:06 +08003505 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003506
3507 /**
3508 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003509 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3510 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003511
3512 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3513 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3514 * this callback as this is prone to race conditions : calling these methods while in a
3515 * callback may return an outdated or even a null object.
3516 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003517 * @hide
3518 */
paulhu1a407652019-03-22 16:35:06 +08003519 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003520
junyulaif2c67e42018-08-07 19:50:45 +08003521 /**
3522 * Called when access to the specified network is blocked or unblocked.
3523 *
Chalard Jean01378b62019-08-30 16:27:28 +09003524 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3525 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3526 * this callback as this is prone to race conditions : calling these methods while in a
3527 * callback may return an outdated or even a null object.
3528 *
junyulaif2c67e42018-08-07 19:50:45 +08003529 * @param network The {@link Network} whose blocked status has changed.
3530 * @param blocked The blocked status of this {@link Network}.
3531 */
junyulai7e06ad42019-03-04 22:45:36 +08003532 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003533
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003534 private NetworkRequest networkRequest;
Roshan Pius951c0032020-12-22 15:10:42 -08003535 private final int mFlags;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003536 }
3537
Hugo Benichia590ab82017-05-11 13:16:17 +09003538 /**
3539 * Constant error codes used by ConnectivityService to communicate about failures and errors
3540 * across a Binder boundary.
3541 * @hide
3542 */
3543 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003544 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003545 }
3546
3547 /** @hide */
3548 public static class TooManyRequestsException extends RuntimeException {}
3549
3550 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3551 switch (e.errorCode) {
3552 case Errors.TOO_MANY_REQUESTS:
3553 return new TooManyRequestsException();
3554 default:
3555 Log.w(TAG, "Unknown service error code " + e.errorCode);
3556 return new RuntimeException(e);
3557 }
3558 }
3559
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003560 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003561 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003562 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003563 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003564 /** @hide arg1 = TTL */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003565 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003566 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003567 public static final int CALLBACK_LOST = 4;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003568 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003569 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003570 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003571 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003572 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003573 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003574 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003575 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003576 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003577 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003578 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003579 public static final int CALLBACK_RESUMED = 10;
junyulaif2c67e42018-08-07 19:50:45 +08003580 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003581 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003582
Erik Kline155a59a2015-11-25 12:49:38 +09003583 /** @hide */
3584 public static String getCallbackName(int whichCallback) {
3585 switch (whichCallback) {
3586 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3587 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3588 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3589 case CALLBACK_LOST: return "CALLBACK_LOST";
3590 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3591 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3592 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003593 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3594 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3595 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003596 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003597 default:
3598 return Integer.toString(whichCallback);
3599 }
3600 }
3601
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003602 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003603 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003604 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003605
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003606 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003607 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003608 }
3609
Hugo Benichifd44e912017-02-02 17:02:36 +09003610 CallbackHandler(Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003611 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003612 }
3613
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003614 @Override
3615 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003616 if (message.what == EXPIRE_LEGACY_REQUEST) {
3617 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3618 return;
3619 }
3620
3621 final NetworkRequest request = getObject(message, NetworkRequest.class);
3622 final Network network = getObject(message, Network.class);
3623 final NetworkCallback callback;
3624 synchronized (sCallbacks) {
3625 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003626 if (callback == null) {
3627 Log.w(TAG,
3628 "callback not found for " + getCallbackName(message.what) + " message");
3629 return;
3630 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003631 if (message.what == CALLBACK_UNAVAIL) {
3632 sCallbacks.remove(request);
3633 callback.networkRequest = ALREADY_UNREGISTERED;
3634 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003635 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003636 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003637 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003638 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003639
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003640 switch (message.what) {
3641 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003642 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003643 break;
3644 }
3645 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003646 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3647 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003648 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003649 break;
3650 }
3651 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003652 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003653 break;
3654 }
3655 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003656 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003657 break;
3658 }
3659 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003660 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003661 break;
3662 }
3663 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003664 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3665 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003666 break;
3667 }
3668 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003669 LinkProperties lp = getObject(message, LinkProperties.class);
3670 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003671 break;
3672 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003673 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003674 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003675 break;
3676 }
3677 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003678 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003679 break;
3680 }
junyulaif2c67e42018-08-07 19:50:45 +08003681 case CALLBACK_BLK_CHANGED: {
3682 boolean blocked = message.arg1 != 0;
3683 callback.onBlockedStatusChanged(network, blocked);
3684 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003685 }
3686 }
3687
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003688 private <T> T getObject(Message msg, Class<T> c) {
3689 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003690 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003691 }
3692
Hugo Benichifd44e912017-02-02 17:02:36 +09003693 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003694 synchronized (sCallbacks) {
3695 if (sCallbackHandler == null) {
3696 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003697 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003698 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003699 }
3700 }
3701
Hugo Benichibc4ac972017-02-03 14:18:44 +09003702 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3703 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003704
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003705 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3706 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3707 CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003708 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003709 checkCallbackNotNull(callback);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003710 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3711 throw new IllegalArgumentException("null NetworkCapabilities");
3712 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003713 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003714 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003715 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003716 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003717 if (callback.networkRequest != null
3718 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003719 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3720 // and requests (http://b/20701525).
3721 Log.e(TAG, "NetworkCallback was already registered");
3722 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003723 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003724 Binder binder = new Binder();
Roshan Pius951c0032020-12-22 15:10:42 -08003725 final int callbackFlags = callback.mFlags;
junyulaiad010792021-01-11 16:53:38 +08003726 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003727 request = mService.listenForNetwork(
Roshan Pius951c0032020-12-22 15:10:42 -08003728 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003729 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003730 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003731 request = mService.requestNetwork(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003732 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3733 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003734 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003735 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003736 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003737 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003738 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003739 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003740 } catch (RemoteException e) {
3741 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003742 } catch (ServiceSpecificException e) {
3743 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003744 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003745 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003746 }
3747
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003748 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3749 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3750 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3751 legacyType, handler);
3752 }
3753
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003754 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003755 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003756 *
markchienfac84a22020-03-18 21:16:15 +08003757 * This API is only for use in internal system code that requests networks with legacy type and
3758 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003759 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003760 *
markchiend6eeffd2020-01-14 00:55:21 +08003761 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003762 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3763 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3764 * be a positive value (i.e. >0).
3765 * @param legacyType to specify the network type(#TYPE_*).
3766 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003767 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3768 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003769 *
3770 * @hide
3771 */
markchiend6eeffd2020-01-14 00:55:21 +08003772 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003773 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003774 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003775 int timeoutMs, int legacyType, @NonNull Handler handler,
3776 @NonNull NetworkCallback networkCallback) {
3777 if (legacyType == TYPE_NONE) {
3778 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3779 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003780 CallbackHandler cbHandler = new CallbackHandler(handler);
3781 NetworkCapabilities nc = request.networkCapabilities;
3782 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003783 }
3784
3785 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003786 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003787 *
Chalard Jean01378b62019-08-30 16:27:28 +09003788 * <p>This method will attempt to find the best network that matches the passed
3789 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3790 * criteria. The platform will evaluate which network is the best at its own discretion.
3791 * Throughput, latency, cost per byte, policy, user preference and other considerations
3792 * may be factored in the decision of what is considered the best network.
3793 *
3794 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3795 * matching this request, while always attempting to match the request to a better network if
3796 * possible. If a better match is found, the platform will switch this request to the now-best
3797 * network and inform the app of the newly best network by invoking
3798 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3799 * will not try to maintain any other network than the best one currently matching the request:
3800 * a network not matching any network request may be disconnected at any time.
3801 *
3802 * <p>For example, an application could use this method to obtain a connected cellular network
3803 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3804 * radio to consume additional power. Or, an application could inform the system that it wants
3805 * a network supporting sending MMSes and have the system let it know about the currently best
3806 * MMS-supporting network through the provided {@link NetworkCallback}.
3807 *
3808 * <p>The status of the request can be followed by listening to the various callbacks described
3809 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3810 * used to direct traffic to the network (although accessing some networks may be subject to
3811 * holding specific permissions). Callers will learn about the specific characteristics of the
3812 * network through
3813 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3814 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3815 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3816 * matching the request at any given time; therefore when a better network matching the request
3817 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3818 * with the new network after which no further updates are given about the previously-best
3819 * network, unless it becomes the best again at some later time. All callbacks are invoked
3820 * in order on the same thread, which by default is a thread created by the framework running
3821 * in the app.
3822 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3823 * callbacks are invoked.
3824 *
3825 * <p>This{@link NetworkRequest} will live until released via
3826 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3827 * which point the system may let go of the network at any time.
3828 *
3829 * <p>A version of this method which takes a timeout is
3830 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3831 * wait for a limited amount of time for the network to become unavailable.
3832 *
Paul Jensenee52d232015-06-16 15:11:58 -04003833 * <p>It is presently unsupported to request a network with mutable
3834 * {@link NetworkCapabilities} such as
3835 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3836 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3837 * as these {@code NetworkCapabilities} represent states that a particular
3838 * network may never attain, and whether a network will attain these states
3839 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003840 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003841 *
3842 * <p>This method requires the caller to hold either the
3843 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3844 * or the ability to modify system settings as determined by
3845 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003846 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003847 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3848 * number of outstanding requests to 100 per app (identified by their UID), shared with
3849 * all variants of this method, of {@link #registerNetworkCallback} as well as
3850 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3851 * Requesting a network with this method will count toward this limit. If this limit is
3852 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3853 * make sure to unregister the callbacks with
3854 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3855 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003856 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003857 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3858 * the callback must not be shared - it uniquely specifies this request.
3859 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003860 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3861 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003862 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003863 */
Chalard Jean158702d2019-01-07 19:26:34 +09003864 public void requestNetwork(@NonNull NetworkRequest request,
3865 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003866 requestNetwork(request, networkCallback, getDefaultHandler());
3867 }
3868
3869 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003870 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichifd44e912017-02-02 17:02:36 +09003871 *
Chalard Jean01378b62019-08-30 16:27:28 +09003872 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3873 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003874 *
Chalard Jean01378b62019-08-30 16:27:28 +09003875 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003876 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3877 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003878 *
3879 * @param request {@link NetworkRequest} describing this request.
3880 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3881 * the callback must not be shared - it uniquely specifies this request.
3882 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003883 */
Chalard Jean158702d2019-01-07 19:26:34 +09003884 public void requestNetwork(@NonNull NetworkRequest request,
3885 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003886 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003887 NetworkCapabilities nc = request.networkCapabilities;
3888 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003889 }
3890
3891 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003892 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohenf67bde92017-03-01 12:47:28 -08003893 * by a timeout.
3894 *
3895 * This function behaves identically to the non-timed-out version
3896 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3897 * is not found within the given time (in milliseconds) the
3898 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3899 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3900 * not have to be released if timed-out (it is automatically released). Unregistering a
3901 * request that timed out is not an error.
3902 *
3903 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3904 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3905 * for that purpose. Calling this method will attempt to bring up the requested network.
3906 *
Chalard Jean01378b62019-08-30 16:27:28 +09003907 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003908 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3909 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003910 *
3911 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003912 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3913 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003914 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3915 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3916 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003917 */
Chalard Jean158702d2019-01-07 19:26:34 +09003918 public void requestNetwork(@NonNull NetworkRequest request,
3919 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003920 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003921 NetworkCapabilities nc = request.networkCapabilities;
3922 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3923 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003924 }
3925
Hugo Benichifd44e912017-02-02 17:02:36 +09003926 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003927 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichifd44e912017-02-02 17:02:36 +09003928 * by a timeout.
3929 *
Chalard Jean01378b62019-08-30 16:27:28 +09003930 * This method behaves identically to
3931 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3932 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003933 *
Chalard Jean01378b62019-08-30 16:27:28 +09003934 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003935 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3936 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003937 *
3938 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003939 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3940 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003941 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003942 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3943 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003944 */
Chalard Jean158702d2019-01-07 19:26:34 +09003945 public void requestNetwork(@NonNull NetworkRequest request,
3946 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003947 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003948 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003949 NetworkCapabilities nc = request.networkCapabilities;
3950 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003951 }
3952
3953 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003954 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003955 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003956 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003957 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003958 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3959 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003960 */
Erik Kline8a826212014-11-19 12:12:24 +09003961 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003962
3963 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003964 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003965 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003966 * {@link android.content.Intent#getParcelableExtra(String)}.
3967 */
Erik Kline8a826212014-11-19 12:12:24 +09003968 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003969
3970
3971 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003972 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003973 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003974 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003975 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003976 * the request may outlive the calling application and get called back when a suitable
3977 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003978 * <p>
3979 * The operation is an Intent broadcast that goes to a broadcast receiver that
3980 * you registered with {@link Context#registerReceiver} or through the
3981 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3982 * <p>
3983 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003984 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3985 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003986 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003987 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003988 * Intent to reserve the network or it will be released shortly after the Intent
3989 * is processed.
3990 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003991 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003992 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003993 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003994 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003995 * The request may be released normally by calling
3996 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003997 * <p>It is presently unsupported to request a network with either
3998 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3999 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4000 * as these {@code NetworkCapabilities} represent states that a particular
4001 * network may never attain, and whether a network will attain these states
4002 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09004003 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004004 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004005 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4006 * number of outstanding requests to 100 per app (identified by their UID), shared with
4007 * all variants of this method, of {@link #registerNetworkCallback} as well as
4008 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4009 * Requesting a network with this method will count toward this limit. If this limit is
4010 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4011 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4012 * or {@link #releaseNetworkRequest(PendingIntent)}.
4013 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004014 * <p>This method requires the caller to hold either the
4015 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4016 * or the ability to modify system settings as determined by
4017 * {@link android.provider.Settings.System#canWrite}.</p>
4018 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004019 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004020 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004021 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004022 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004023 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4024 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004025 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004026 */
Chalard Jean158702d2019-01-07 19:26:34 +09004027 public void requestNetwork(@NonNull NetworkRequest request,
4028 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004029 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004030 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004031 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004032 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004033 request.networkCapabilities, operation, mContext.getOpPackageName(),
4034 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004035 } catch (RemoteException e) {
4036 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004037 } catch (ServiceSpecificException e) {
4038 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004039 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004040 }
4041
4042 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004043 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4044 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004045 * This method has the same behavior as
4046 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004047 * releasing network resources and disconnecting.
4048 *
4049 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4050 * PendingIntent passed to
4051 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4052 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4053 */
Chalard Jean158702d2019-01-07 19:26:34 +09004054 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004055 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004056 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004057 try {
4058 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004059 } catch (RemoteException e) {
4060 throw e.rethrowFromSystemServer();
4061 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004062 }
4063
Hugo Benichibc1104b2017-05-09 15:19:01 +09004064 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004065 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004066 }
4067
4068 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004069 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004070 }
4071
4072 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004073 if (timeoutMs <= 0) {
4074 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4075 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004076 }
4077
4078 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004079 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004080 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004081 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4082 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004083 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004084 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4085 * number of outstanding requests to 100 per app (identified by their UID), shared with
4086 * all variants of this method, of {@link #requestNetwork} as well as
4087 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4088 * Requesting a network with this method will count toward this limit. If this limit is
4089 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4090 * make sure to unregister the callbacks with
4091 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4092 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004093 * @param request {@link NetworkRequest} describing this request.
4094 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4095 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004096 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004097 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004098 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004099 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004100 public void registerNetworkCallback(@NonNull NetworkRequest request,
4101 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004102 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4103 }
4104
4105 /**
4106 * Registers to receive notifications about all networks which satisfy the given
4107 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004108 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4109 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004110 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004111 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4112 * number of outstanding requests to 100 per app (identified by their UID), shared with
4113 * all variants of this method, of {@link #requestNetwork} as well as
4114 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4115 * Requesting a network with this method will count toward this limit. If this limit is
4116 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4117 * make sure to unregister the callbacks with
4118 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4119 *
4120 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004121 * @param request {@link NetworkRequest} describing this request.
4122 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4123 * networks change state.
4124 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004125 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004126 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004127 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004128 public void registerNetworkCallback(@NonNull NetworkRequest request,
4129 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004130 CallbackHandler cbHandler = new CallbackHandler(handler);
4131 NetworkCapabilities nc = request.networkCapabilities;
4132 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004133 }
4134
4135 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004136 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4137 * {@link NetworkRequest}.
4138 *
4139 * This function behaves identically to the version that takes a NetworkCallback, but instead
4140 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4141 * the request may outlive the calling application and get called back when a suitable
4142 * network is found.
4143 * <p>
4144 * The operation is an Intent broadcast that goes to a broadcast receiver that
4145 * you registered with {@link Context#registerReceiver} or through the
4146 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4147 * <p>
4148 * The operation Intent is delivered with two extras, a {@link Network} typed
4149 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4150 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4151 * the original requests parameters.
4152 * <p>
4153 * If there is already a request for this Intent registered (with the equality of
4154 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4155 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4156 * <p>
4157 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004158 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004159 *
4160 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4161 * number of outstanding requests to 100 per app (identified by their UID), shared with
4162 * all variants of this method, of {@link #requestNetwork} as well as
4163 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4164 * Requesting a network with this method will count toward this limit. If this limit is
4165 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4166 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4167 * or {@link #releaseNetworkRequest(PendingIntent)}.
4168 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004169 * @param request {@link NetworkRequest} describing this request.
4170 * @param operation Action to perform when the network is available (corresponds
4171 * to the {@link NetworkCallback#onAvailable} call. Typically
4172 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004173 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004174 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004175 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004176 public void registerNetworkCallback(@NonNull NetworkRequest request,
4177 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004178 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004179 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004180 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004181 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004182 request.networkCapabilities, operation, mContext.getOpPackageName(),
4183 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004184 } catch (RemoteException e) {
4185 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004186 } catch (ServiceSpecificException e) {
4187 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004188 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004189 }
4190
4191 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004192 * Registers to receive notifications about changes in the application's default network. This
4193 * may be a physical network or a virtual network, such as a VPN that applies to the
4194 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004195 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004196 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004197 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4198 * number of outstanding requests to 100 per app (identified by their UID), shared with
4199 * all variants of this method, of {@link #requestNetwork} as well as
4200 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4201 * Requesting a network with this method will count toward this limit. If this limit is
4202 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4203 * make sure to unregister the callbacks with
4204 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4205 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004206 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004207 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004208 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004209 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004210 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004211 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004212 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004213 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4214 }
4215
4216 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004217 * Registers to receive notifications about changes in the application's default network. This
4218 * may be a physical network or a virtual network, such as a VPN that applies to the
4219 * application. The callbacks will continue to be called until either the application exits or
4220 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4221 *
4222 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4223 * number of outstanding requests to 100 per app (identified by their UID), shared with
4224 * all variants of this method, of {@link #requestNetwork} as well as
4225 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4226 * Requesting a network with this method will count toward this limit. If this limit is
4227 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4228 * make sure to unregister the callbacks with
4229 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4230 *
4231 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4232 * application's default network changes.
4233 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4234 * @throws RuntimeException if the app already has too many callbacks registered.
4235 */
4236 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4237 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4238 @NonNull Handler handler) {
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004239 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4240 }
4241
4242 /**
4243 * Registers to receive notifications about changes in the default network for the specified
4244 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4245 * UID. The callbacks will continue to be called until either the application exits or
4246 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4247 *
4248 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4249 * number of outstanding requests to 100 per app (identified by their UID), shared with
4250 * all variants of this method, of {@link #requestNetwork} as well as
4251 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4252 * Requesting a network with this method will count toward this limit. If this limit is
4253 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4254 * make sure to unregister the callbacks with
4255 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4256 *
4257 * @param uid the UID for which to track default network changes.
4258 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4259 * UID's default network changes.
4260 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4261 * @throws RuntimeException if the app already has too many callbacks registered.
4262 * @hide
4263 */
Lorenzo Colitti92ed8b92021-03-22 18:23:21 +09004264 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004265 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4266 @RequiresPermission(anyOf = {
4267 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4268 android.Manifest.permission.NETWORK_SETTINGS})
4269 public void registerDefaultNetworkCallbackAsUid(int uid,
4270 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004271 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004272 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004273 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4274 }
4275
4276 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004277 * Registers to receive notifications about changes in the system default network. The callbacks
4278 * will continue to be called until either the application exits or
4279 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004280 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004281 * This method should not be used to determine networking state seen by applications, because in
4282 * many cases, most or even all application traffic may not use the default network directly,
4283 * and traffic from different applications may go on different networks by default. As an
4284 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4285 * and not onto the system default network. Applications or system components desiring to do
4286 * determine network state as seen by applications should use other methods such as
4287 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4288 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004289 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4290 * number of outstanding requests to 100 per app (identified by their UID), shared with
4291 * all variants of this method, of {@link #requestNetwork} as well as
4292 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4293 * Requesting a network with this method will count toward this limit. If this limit is
4294 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4295 * make sure to unregister the callbacks with
4296 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4297 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004298 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4299 * system default network changes.
4300 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004301 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004302 *
4303 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004304 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004305 @SystemApi(client = MODULE_LIBRARIES)
4306 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4307 @RequiresPermission(anyOf = {
4308 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4309 android.Manifest.permission.NETWORK_SETTINGS})
4310 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004311 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004312 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004313 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004314 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004315 }
4316
4317 /**
junyulai8eb13a22021-03-15 11:48:48 +08004318 * Registers to receive notifications about the best matching network which satisfy the given
4319 * {@link NetworkRequest}. The callbacks will continue to be called until
4320 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4321 * called.
4322 *
4323 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4324 * number of outstanding requests to 100 per app (identified by their UID), shared with
4325 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4326 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4327 * Requesting a network with this method will count toward this limit. If this limit is
4328 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4329 * make sure to unregister the callbacks with
4330 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4331 *
4332 *
4333 * @param request {@link NetworkRequest} describing this request.
4334 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4335 * networks change state.
4336 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4337 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai7514e312021-03-05 15:51:17 +08004338 */
junyulai7514e312021-03-05 15:51:17 +08004339 @SuppressLint("ExecutorRegistration")
4340 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4341 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4342 final NetworkCapabilities nc = request.networkCapabilities;
4343 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai1b1c8742021-03-12 20:05:08 +08004344 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai7514e312021-03-05 15:51:17 +08004345 }
4346
4347 /**
fenglub00f4882015-04-21 17:12:05 -07004348 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4349 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4350 * network connection for updated bandwidth information. The caller will be notified via
4351 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004352 * method assumes that the caller has previously called
4353 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4354 * changes.
fenglu3f357402015-03-20 11:29:56 -07004355 *
fengluea2d9282015-04-27 14:28:04 -07004356 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004357 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004358 */
Chalard Jean158702d2019-01-07 19:26:34 +09004359 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004360 try {
fenglub00f4882015-04-21 17:12:05 -07004361 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004362 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004363 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004364 }
4365 }
4366
4367 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004368 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004369 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4370 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4371 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004372 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4373 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004374 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004375 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4376 * triggering it as soon as this call returns.
4377 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004378 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004379 */
Chalard Jean158702d2019-01-07 19:26:34 +09004380 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004381 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004382 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004383 final List<NetworkRequest> reqs = new ArrayList<>();
4384 // Find all requests associated to this callback and stop callback triggers immediately.
4385 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4386 synchronized (sCallbacks) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004387 if (networkCallback.networkRequest == null) {
4388 throw new IllegalArgumentException("NetworkCallback was not registered");
4389 }
Etan Cohen6cb65992019-04-16 15:07:55 -07004390 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4391 Log.d(TAG, "NetworkCallback was already unregistered");
4392 return;
4393 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004394 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4395 if (e.getValue() == networkCallback) {
4396 reqs.add(e.getKey());
4397 }
4398 }
4399 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4400 for (NetworkRequest r : reqs) {
4401 try {
4402 mService.releaseNetworkRequest(r);
4403 } catch (RemoteException e) {
4404 throw e.rethrowFromSystemServer();
4405 }
4406 // Only remove mapping if rpc was successful.
4407 sCallbacks.remove(r);
4408 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004409 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004410 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004411 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004412
4413 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004414 * Unregisters a callback previously registered via
4415 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4416 *
4417 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4418 * PendingIntent passed to
4419 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4420 * Cannot be null.
4421 */
Chalard Jean158702d2019-01-07 19:26:34 +09004422 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004423 releaseNetworkRequest(operation);
4424 }
4425
4426 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004427 * Informs the system whether it should switch to {@code network} regardless of whether it is
4428 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4429 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4430 * the system default network regardless of any other network that's currently connected. If
4431 * {@code always} is true, then the choice is remembered, so that the next time the user
4432 * connects to this network, the system will switch to it.
4433 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004434 * @param network The network to accept.
4435 * @param accept Whether to accept the network even if unvalidated.
4436 * @param always Whether to remember this choice in the future.
4437 *
4438 * @hide
4439 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004440 @SystemApi(client = MODULE_LIBRARIES)
4441 @RequiresPermission(anyOf = {
4442 android.Manifest.permission.NETWORK_SETTINGS,
4443 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4444 android.Manifest.permission.NETWORK_STACK,
4445 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4446 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004447 try {
4448 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004449 } catch (RemoteException e) {
4450 throw e.rethrowFromSystemServer();
4451 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004452 }
4453
4454 /**
lucaslin2240ef62019-03-12 13:08:03 +08004455 * Informs the system whether it should consider the network as validated even if it only has
4456 * partial connectivity. If {@code accept} is true, then the network will be considered as
4457 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4458 * is remembered, so that the next time the user connects to this network, the system will
4459 * switch to it.
4460 *
4461 * @param network The network to accept.
4462 * @param accept Whether to consider the network as validated even if it has partial
4463 * connectivity.
4464 * @param always Whether to remember this choice in the future.
4465 *
4466 * @hide
4467 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004468 @SystemApi(client = MODULE_LIBRARIES)
4469 @RequiresPermission(anyOf = {
4470 android.Manifest.permission.NETWORK_SETTINGS,
4471 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4472 android.Manifest.permission.NETWORK_STACK,
4473 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4474 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4475 boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004476 try {
4477 mService.setAcceptPartialConnectivity(network, accept, always);
4478 } catch (RemoteException e) {
4479 throw e.rethrowFromSystemServer();
4480 }
4481 }
4482
4483 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004484 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4485 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4486 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4487 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4488 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004489 * @param network The network to accept.
4490 *
4491 * @hide
4492 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004493 @SystemApi(client = MODULE_LIBRARIES)
4494 @RequiresPermission(anyOf = {
4495 android.Manifest.permission.NETWORK_SETTINGS,
4496 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4497 android.Manifest.permission.NETWORK_STACK,
4498 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4499 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004500 try {
4501 mService.setAvoidUnvalidated(network);
4502 } catch (RemoteException e) {
4503 throw e.rethrowFromSystemServer();
4504 }
4505 }
4506
4507 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004508 * Requests that the system open the captive portal app on the specified network.
4509 *
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004510 * <p>This is to be used on networks where a captive portal was detected, as per
4511 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4512 *
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004513 * @param network The network to log into.
4514 *
4515 * @hide
4516 */
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004517 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4518 @RequiresPermission(anyOf = {
4519 android.Manifest.permission.NETWORK_SETTINGS,
4520 android.Manifest.permission.NETWORK_STACK,
4521 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4522 })
4523 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004524 try {
4525 mService.startCaptivePortalApp(network);
4526 } catch (RemoteException e) {
4527 throw e.rethrowFromSystemServer();
4528 }
4529 }
4530
4531 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004532 * Requests that the system open the captive portal app with the specified extras.
4533 *
4534 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4535 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004536 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004537 * @param appExtras Extras to include in the app start intent.
4538 * @hide
4539 */
4540 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004541 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004542 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004543 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004544 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004545 } catch (RemoteException e) {
4546 throw e.rethrowFromSystemServer();
4547 }
4548 }
4549
4550 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004551 * Determine whether the device is configured to avoid bad wifi.
4552 * @hide
4553 */
4554 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004555 @RequiresPermission(anyOf = {
4556 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4557 android.Manifest.permission.NETWORK_STACK})
4558 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004559 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004560 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004561 } catch (RemoteException e) {
4562 throw e.rethrowFromSystemServer();
4563 }
4564 }
4565
4566 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004567 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4568 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004569 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4570 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004571 *
4572 * An example of such an operation might be a time-sensitive foreground activity, such as a
4573 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4574 */
4575 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4576
4577 /**
4578 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4579 * a backup channel for traffic that is primarily going over another network.
4580 *
4581 * An example might be maintaining backup connections to peers or servers for the purpose of
4582 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4583 * on backup paths should be negligible compared to the traffic on the main path.
4584 */
4585 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4586
4587 /**
4588 * It is acceptable to use metered data to improve network latency and performance.
4589 */
4590 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4591
4592 /**
4593 * Return value to use for unmetered networks. On such networks we currently set all the flags
4594 * to true.
4595 * @hide
4596 */
4597 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4598 MULTIPATH_PREFERENCE_HANDOVER |
4599 MULTIPATH_PREFERENCE_RELIABILITY |
4600 MULTIPATH_PREFERENCE_PERFORMANCE;
4601
4602 /** @hide */
4603 @Retention(RetentionPolicy.SOURCE)
4604 @IntDef(flag = true, value = {
4605 MULTIPATH_PREFERENCE_HANDOVER,
4606 MULTIPATH_PREFERENCE_RELIABILITY,
4607 MULTIPATH_PREFERENCE_PERFORMANCE,
4608 })
4609 public @interface MultipathPreference {
4610 }
4611
4612 /**
4613 * Provides a hint to the calling application on whether it is desirable to use the
4614 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4615 * for multipath data transfer on this network when it is not the system default network.
4616 * Applications desiring to use multipath network protocols should call this method before
4617 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004618 *
4619 * @param network The network on which the application desires to use multipath data.
4620 * If {@code null}, this method will return the a preference that will generally
4621 * apply to metered networks.
4622 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4623 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004624 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004625 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004626 try {
4627 return mService.getMultipathPreference(network);
4628 } catch (RemoteException e) {
4629 throw e.rethrowFromSystemServer();
4630 }
4631 }
4632
4633 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004634 * Resets all connectivity manager settings back to factory defaults.
4635 * @hide
4636 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004637 @SystemApi(client = MODULE_LIBRARIES)
4638 @RequiresPermission(anyOf = {
4639 android.Manifest.permission.NETWORK_SETTINGS,
4640 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scott0f835ac2015-03-30 13:17:11 -07004641 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004642 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004643 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004644 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004645 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004646 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004647 }
4648 }
4649
4650 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004651 * Binds the current process to {@code network}. All Sockets created in the future
4652 * (and not explicitly bound via a bound SocketFactory from
4653 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4654 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4655 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4656 * work and all host name resolutions will fail. This is by design so an application doesn't
4657 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4658 * To clear binding pass {@code null} for {@code network}. Using individually bound
4659 * Sockets created by Network.getSocketFactory().createSocket() and
4660 * performing network-specific host name resolutions via
4661 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004662 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004663 *
4664 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4665 * the current binding.
4666 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4667 */
Chalard Jean158702d2019-01-07 19:26:34 +09004668 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004669 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004670 // instantiated.
4671 return setProcessDefaultNetwork(network);
4672 }
4673
4674 /**
4675 * Binds the current process to {@code network}. All Sockets created in the future
4676 * (and not explicitly bound via a bound SocketFactory from
4677 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4678 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4679 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4680 * work and all host name resolutions will fail. This is by design so an application doesn't
4681 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4682 * To clear binding pass {@code null} for {@code network}. Using individually bound
4683 * Sockets created by Network.getSocketFactory().createSocket() and
4684 * performing network-specific host name resolutions via
4685 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4686 * {@code setProcessDefaultNetwork}.
4687 *
4688 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4689 * the current binding.
4690 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4691 * @deprecated This function can throw {@link IllegalStateException}. Use
4692 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4693 * is a direct replacement.
4694 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004695 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004696 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004697 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004698 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4699
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004700 if (netId != NETID_UNSET) {
4701 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004702 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004703
4704 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4705 return false;
4706 }
4707
4708 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004709 // Set HTTP proxy system properties to match network.
4710 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004711 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004712 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004713 } catch (SecurityException e) {
4714 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4715 Log.e(TAG, "Can't set proxy properties", e);
4716 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004717 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANe1b04f62021-03-18 23:27:19 +09004718 InetAddressCompat.clearDnsCache();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004719 // Must flush socket pool as idle sockets will be bound to previous network and may
4720 // cause subsequent fetches to be performed on old network.
4721 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004722 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004723
4724 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004725 }
4726
4727 /**
4728 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004729 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004730 *
4731 * @return {@code Network} to which this process is bound, or {@code null}.
4732 */
Chalard Jean158702d2019-01-07 19:26:34 +09004733 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004734 public Network getBoundNetworkForProcess() {
4735 // Forcing callers to call thru non-static function ensures ConnectivityManager
4736 // instantiated.
4737 return getProcessDefaultNetwork();
4738 }
4739
4740 /**
4741 * Returns the {@link Network} currently bound to this process via
4742 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4743 *
4744 * @return {@code Network} to which this process is bound, or {@code null}.
4745 * @deprecated Using this function can lead to other functions throwing
4746 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4747 * {@code getBoundNetworkForProcess} is a direct replacement.
4748 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004749 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004750 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004751 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004752 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004753 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004754 return new Network(netId);
4755 }
4756
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004757 private void unsupportedStartingFrom(int version) {
4758 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004759 // The getApplicationInfo() call we make below is not supported in system context. Let
4760 // the call through here, and rely on the fact that ConnectivityService will refuse to
4761 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004762 return;
4763 }
4764
4765 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4766 throw new UnsupportedOperationException(
4767 "This method is not supported in target SDK version " + version + " and above");
4768 }
4769 }
4770
4771 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4772 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004773 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004774 // remove these exemptions. Note that this check is not secure, and apps can still access these
4775 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4776 // so is unsupported and may break in the future. http://b/22728205
4777 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004778 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004779 }
4780
Paul Jensen8cdda642014-05-29 10:12:39 -04004781 /**
4782 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004783 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004784 *
4785 * @param network The {@link Network} to bind host resolutions from the current process to, or
4786 * {@code null} to clear the current binding.
4787 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4788 * @hide
4789 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4790 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004791 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004792 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004793 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004794 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004795 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004796 }
Felipe Leme30511352016-01-22 09:44:57 -08004797
4798 /**
4799 * Device is not restricting metered network activity while application is running on
4800 * background.
4801 */
4802 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4803
4804 /**
4805 * Device is restricting metered network activity while application is running on background,
4806 * but application is allowed to bypass it.
4807 * <p>
4808 * In this state, application should take action to mitigate metered network access.
4809 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4810 */
4811 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4812
4813 /**
4814 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004815 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004816 * In this state, application should not try to use the network while running on background,
4817 * because it would be denied.
4818 */
4819 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4820
Felipe Lemed34c9af2016-01-27 14:46:39 -08004821 /**
4822 * A change in the background metered network activity restriction has occurred.
4823 * <p>
4824 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4825 * applies to them.
4826 * <p>
4827 * This is only sent to registered receivers, not manifest receivers.
4828 */
4829 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4830 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4831 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4832
Felipe Leme7e4c1852016-01-25 11:48:04 -08004833 /** @hide */
4834 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004835 @IntDef(flag = false, value = {
4836 RESTRICT_BACKGROUND_STATUS_DISABLED,
4837 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4838 RESTRICT_BACKGROUND_STATUS_ENABLED,
4839 })
Felipe Leme30511352016-01-22 09:44:57 -08004840 public @interface RestrictBackgroundStatus {
4841 }
4842
Felipe Leme30511352016-01-22 09:44:57 -08004843 /**
4844 * Determines if the calling application is subject to metered network restrictions while
4845 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004846 *
4847 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4848 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4849 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004850 */
4851 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4852 try {
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004853 return mService.getRestrictBackgroundStatusByCaller();
Felipe Leme30511352016-01-22 09:44:57 -08004854 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004855 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004856 }
4857 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004858
4859 /**
4860 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004861 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4862 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004863 *
4864 * @return Hash of network watchlist config file. Null if config does not exist.
4865 */
Chalard Jean158702d2019-01-07 19:26:34 +09004866 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004867 public byte[] getNetworkWatchlistConfigHash() {
4868 try {
4869 return mService.getNetworkWatchlistConfigHash();
4870 } catch (RemoteException e) {
4871 Log.e(TAG, "Unable to get watchlist config hash");
4872 throw e.rethrowFromSystemServer();
4873 }
4874 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004875
4876 /**
4877 * Returns the {@code uid} of the owner of a network connection.
4878 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004879 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4880 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004881 * @param local The local {@link InetSocketAddress} of a connection.
4882 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004883 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004884 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4885 * android.os.Process#INVALID_UID} if the connection is not found.
4886 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4887 * user.
4888 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004889 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004890 public int getConnectionOwnerUid(
4891 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004892 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4893 try {
4894 return mService.getConnectionOwnerUid(connectionInfo);
4895 } catch (RemoteException e) {
4896 throw e.rethrowFromSystemServer();
4897 }
4898 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004899
4900 private void printStackTrace() {
4901 if (DEBUG) {
4902 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4903 final StringBuffer sb = new StringBuffer();
4904 for (int i = 3; i < callStack.length; i++) {
4905 final String stackTrace = callStack[i].toString();
4906 if (stackTrace == null || stackTrace.contains("android.os")) {
4907 break;
4908 }
4909 sb.append(" [").append(stackTrace).append("]");
4910 }
4911 Log.d(TAG, "StackLog:" + sb.toString());
4912 }
4913 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004914
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004915 /** @hide */
4916 public TestNetworkManager startOrGetTestNetworkManager() {
4917 final IBinder tnBinder;
4918 try {
4919 tnBinder = mService.startOrGetTestNetworkService();
4920 } catch (RemoteException e) {
4921 throw e.rethrowFromSystemServer();
4922 }
4923
4924 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4925 }
4926
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004927 /** @hide */
4928 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4929 return new ConnectivityDiagnosticsManager(mContext, mService);
4930 }
4931
Cody Kestingf53a0752020-04-15 12:33:28 -07004932 /**
4933 * Simulates a Data Stall for the specified Network.
4934 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004935 * <p>This method should only be used for tests.
4936 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004937 * <p>The caller must be the owner of the specified Network.
4938 *
4939 * @param detectionMethod The detection method used to identify the Data Stall.
4940 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4941 * @param network The Network for which a Data Stall is being simluated.
4942 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4943 * @throws SecurityException if the caller is not the owner of the given network.
4944 * @hide
4945 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004946 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004947 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4948 android.Manifest.permission.NETWORK_STACK})
4949 public void simulateDataStall(int detectionMethod, long timestampMillis,
4950 @NonNull Network network, @NonNull PersistableBundle extras) {
4951 try {
4952 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4953 } catch (RemoteException e) {
4954 e.rethrowFromSystemServer();
4955 }
4956 }
James Mattis356a8792020-10-28 21:48:54 -07004957
Daniel Brightf9e945b2020-06-15 16:10:01 -07004958 @NonNull
4959 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4960
4961 /**
4962 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4963 * receive available QoS events related to the {@link Network} and local ip + port
4964 * specified within socketInfo.
4965 * <p/>
4966 * The same {@link QosCallback} must be unregistered before being registered a second time,
4967 * otherwise {@link QosCallbackRegistrationException} is thrown.
4968 * <p/>
4969 * This API does not, in itself, require any permission if called with a network that is not
4970 * restricted. However, the underlying implementation currently only supports the IMS network,
4971 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4972 * useful, because they'd never be called back on networks that they would have access to.
4973 *
4974 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4975 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4976 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4977 * @throws RuntimeException if the app already has too many callbacks registered.
4978 *
4979 * Exceptions after the time of registration is passed through
4980 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4981 *
4982 * @param socketInfo the socket information used to match QoS events
Daniel Brightf9e945b2020-06-15 16:10:01 -07004983 * @param executor The executor on which the callback will be invoked. The provided
4984 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright7ee5f522021-03-10 11:51:50 -08004985 * callbacks cannot be guaranteed.onQosCallbackRegistered
4986 * @param callback receives qos events that satisfy socketInfo
Daniel Brightf9e945b2020-06-15 16:10:01 -07004987 *
4988 * @hide
4989 */
4990 @SystemApi
4991 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright7ee5f522021-03-10 11:51:50 -08004992 @CallbackExecutor @NonNull final Executor executor,
4993 @NonNull final QosCallback callback) {
Daniel Brightf9e945b2020-06-15 16:10:01 -07004994 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07004995 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright7ee5f522021-03-10 11:51:50 -08004996 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07004997
4998 try {
4999 synchronized (mQosCallbackConnections) {
5000 if (getQosCallbackConnection(callback) == null) {
5001 final QosCallbackConnection connection =
5002 new QosCallbackConnection(this, callback, executor);
5003 mQosCallbackConnections.add(connection);
5004 mService.registerQosSocketCallback(socketInfo, connection);
5005 } else {
5006 Log.e(TAG, "registerQosCallback: Callback already registered");
5007 throw new QosCallbackRegistrationException();
5008 }
5009 }
5010 } catch (final RemoteException e) {
5011 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5012
5013 // The same unregister method method is called for consistency even though nothing
5014 // will be sent to the ConnectivityService since the callback was never successfully
5015 // registered.
5016 unregisterQosCallback(callback);
5017 e.rethrowFromSystemServer();
5018 } catch (final ServiceSpecificException e) {
5019 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5020 unregisterQosCallback(callback);
5021 throw convertServiceException(e);
5022 }
5023 }
5024
5025 /**
5026 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5027 * events once unregistered and can be registered a second time.
5028 * <p/>
5029 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5030 *
5031 * @param callback the callback being unregistered
5032 *
5033 * @hide
5034 */
5035 @SystemApi
5036 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5037 Objects.requireNonNull(callback, "The callback must be non-null");
5038 try {
5039 synchronized (mQosCallbackConnections) {
5040 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5041 if (connection != null) {
5042 connection.stopReceivingMessages();
5043 mService.unregisterQosCallback(connection);
5044 mQosCallbackConnections.remove(connection);
5045 } else {
5046 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5047 }
5048 }
5049 } catch (final RemoteException e) {
5050 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5051 e.rethrowFromSystemServer();
5052 }
5053 }
5054
5055 /**
5056 * Gets the connection related to the callback.
5057 *
5058 * @param callback the callback to look up
5059 * @return the related connection
5060 */
5061 @Nullable
5062 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5063 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5064 // Checking by reference here is intentional
5065 if (connection.getCallback() == callback) {
5066 return connection;
5067 }
5068 }
5069 return null;
5070 }
Junyu Laia62493f2021-01-19 11:10:56 +00005071
5072 /**
Roshan Pius951c0032020-12-22 15:10:42 -08005073 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Laia62493f2021-01-19 11:10:56 +00005074 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5075 * be used to request that the system provide a network without causing the network to be
5076 * in the foreground.
5077 *
5078 * <p>This method will attempt to find the best network that matches the passed
5079 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5080 * criteria. The platform will evaluate which network is the best at its own discretion.
5081 * Throughput, latency, cost per byte, policy, user preference and other considerations
5082 * may be factored in the decision of what is considered the best network.
5083 *
5084 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5085 * matching this request, while always attempting to match the request to a better network if
5086 * possible. If a better match is found, the platform will switch this request to the now-best
5087 * network and inform the app of the newly best network by invoking
5088 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5089 * will not try to maintain any other network than the best one currently matching the request:
5090 * a network not matching any network request may be disconnected at any time.
5091 *
5092 * <p>For example, an application could use this method to obtain a connected cellular network
5093 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5094 * radio to consume additional power. Or, an application could inform the system that it wants
5095 * a network supporting sending MMSes and have the system let it know about the currently best
5096 * MMS-supporting network through the provided {@link NetworkCallback}.
5097 *
5098 * <p>The status of the request can be followed by listening to the various callbacks described
5099 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5100 * used to direct traffic to the network (although accessing some networks may be subject to
5101 * holding specific permissions). Callers will learn about the specific characteristics of the
5102 * network through
5103 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5104 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5105 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5106 * matching the request at any given time; therefore when a better network matching the request
5107 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5108 * with the new network after which no further updates are given about the previously-best
5109 * network, unless it becomes the best again at some later time. All callbacks are invoked
5110 * in order on the same thread, which by default is a thread created by the framework running
5111 * in the app.
5112 *
5113 * <p>This{@link NetworkRequest} will live until released via
5114 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5115 * which point the system may let go of the network at any time.
5116 *
5117 * <p>It is presently unsupported to request a network with mutable
5118 * {@link NetworkCapabilities} such as
5119 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5120 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5121 * as these {@code NetworkCapabilities} represent states that a particular
5122 * network may never attain, and whether a network will attain these states
5123 * is unknown prior to bringing up the network so the framework does not
5124 * know how to go about satisfying a request with these capabilities.
5125 *
5126 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5127 * number of outstanding requests to 100 per app (identified by their UID), shared with
5128 * all variants of this method, of {@link #registerNetworkCallback} as well as
5129 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5130 * Requesting a network with this method will count toward this limit. If this limit is
5131 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5132 * make sure to unregister the callbacks with
5133 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5134 *
5135 * @param request {@link NetworkRequest} describing this request.
5136 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5137 * If null, the callback is invoked on the default internal Handler.
5138 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5139 * the callback must not be shared - it uniquely specifies this request.
5140 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5141 * @throws SecurityException if missing the appropriate permissions.
5142 * @throws RuntimeException if the app already has too many callbacks registered.
5143 *
5144 * @hide
5145 */
5146 @SystemApi(client = MODULE_LIBRARIES)
5147 @SuppressLint("ExecutorRegistration")
5148 @RequiresPermission(anyOf = {
5149 android.Manifest.permission.NETWORK_SETTINGS,
5150 android.Manifest.permission.NETWORK_STACK,
5151 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5152 })
5153 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai962bdb82021-03-09 20:49:48 +08005154 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Laia62493f2021-01-19 11:10:56 +00005155 final NetworkCapabilities nc = request.networkCapabilities;
5156 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulai962bdb82021-03-09 20:49:48 +08005157 TYPE_NONE, new CallbackHandler(handler));
Junyu Laia62493f2021-01-19 11:10:56 +00005158 }
James Mattis45d81842021-01-10 14:24:24 -08005159
5160 /**
James Mattis45d81842021-01-10 14:24:24 -08005161 * Used by automotive devices to set the network preferences used to direct traffic at an
5162 * application level as per the given OemNetworkPreferences. An example use-case would be an
5163 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5164 * vehicle via a particular network.
5165 *
5166 * Calling this will overwrite the existing preference.
5167 *
5168 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5169 * @param executor the executor on which listener will be invoked.
5170 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5171 * communicate completion of setOemNetworkPreference(). This will only be
5172 * called once upon successful completion of setOemNetworkPreference().
5173 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5174 * @throws SecurityException if missing the appropriate permissions.
5175 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005176 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005177 */
James Mattisda32cfe2021-01-26 16:23:52 -08005178 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005179 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005180 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005181 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean6010c002021-03-03 16:37:13 +09005182 @Nullable final Runnable listener) {
James Mattis45d81842021-01-10 14:24:24 -08005183 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5184 if (null != listener) {
5185 Objects.requireNonNull(executor, "Executor must be non-null");
5186 }
Chalard Jean6010c002021-03-03 16:37:13 +09005187 final IOnCompleteListener listenerInternal = listener == null ? null :
5188 new IOnCompleteListener.Stub() {
James Mattis45d81842021-01-10 14:24:24 -08005189 @Override
5190 public void onComplete() {
Chalard Jean6010c002021-03-03 16:37:13 +09005191 executor.execute(listener::run);
James Mattis45d81842021-01-10 14:24:24 -08005192 }
5193 };
5194
5195 try {
5196 mService.setOemNetworkPreference(preference, listenerInternal);
5197 } catch (RemoteException e) {
5198 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5199 throw e.rethrowFromSystemServer();
5200 }
5201 }
lucaslin30e70a82021-03-12 00:46:33 +08005202
Chalard Jeanfa45a682021-02-25 17:23:40 +09005203 /**
5204 * Request that a user profile is put by default on a network matching a given preference.
5205 *
5206 * See the documentation for the individual preferences for a description of the supported
5207 * behaviors.
5208 *
5209 * @param profile the profile concerned.
5210 * @param preference the preference for this profile.
5211 * @param executor an executor to execute the listener on. Optional if listener is null.
5212 * @param listener an optional listener to listen for completion of the operation.
5213 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5214 * @throws SecurityException if missing the appropriate permissions.
5215 * @hide
5216 */
Chalard Jean6010c002021-03-03 16:37:13 +09005217 // This function is for establishing per-profile default networking and can only be called by
5218 // the device policy manager, running as the system server. It would make no sense to call it
5219 // on a context for a user because it does not establish a setting on behalf of a user, rather
5220 // it establishes a setting for a user on behalf of the DPM.
5221 @SuppressLint({"UserHandle"})
5222 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09005223 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5224 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5225 @ProfileNetworkPreference final int preference,
5226 @Nullable @CallbackExecutor final Executor executor,
5227 @Nullable final Runnable listener) {
5228 if (null != listener) {
5229 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5230 }
5231 final IOnCompleteListener proxy;
5232 if (null == listener) {
5233 proxy = null;
5234 } else {
5235 proxy = new IOnCompleteListener.Stub() {
5236 @Override
5237 public void onComplete() {
5238 executor.execute(listener::run);
5239 }
5240 };
5241 }
5242 try {
5243 mService.setProfileNetworkPreference(profile, preference, proxy);
5244 } catch (RemoteException e) {
5245 throw e.rethrowFromSystemServer();
5246 }
5247 }
5248
lucaslin30e70a82021-03-12 00:46:33 +08005249 // The first network ID of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005250 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin30e70a82021-03-12 00:46:33 +08005251 // The network ID range of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005252 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin30e70a82021-03-12 00:46:33 +08005253
5254 /**
5255 * Get the network ID range reserved for IPSec tunnel interfaces.
5256 *
5257 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5258 * @hide
5259 */
5260 @SystemApi(client = MODULE_LIBRARIES)
5261 @NonNull
5262 public static Range<Integer> getIpSecNetIdRange() {
5263 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5264 }
lucaslin705c3332021-03-12 17:56:09 +08005265
5266 /**
5267 * Get private DNS mode from settings.
5268 *
lucaslin7abe7e02021-03-17 14:53:35 +08005269 * @param context The Context to query the private DNS mode from settings.
lucaslin705c3332021-03-12 17:56:09 +08005270 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5271 *
5272 * @hide
5273 */
5274 @SystemApi(client = MODULE_LIBRARIES)
5275 @NonNull
5276 @PrivateDnsMode
lucaslin20f04882021-03-16 17:11:14 +08005277 public static String getPrivateDnsMode(@NonNull Context context) {
5278 final ContentResolver cr = context.getContentResolver();
lucaslin705c3332021-03-12 17:56:09 +08005279 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5280 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5281 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5282 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5283 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5284 return mode;
5285 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005286}