blob: effdf5b8110f4f4e09dbd35c1737403e6b66632b [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
Sudheer Shanka98215562021-03-23 08:12:28 +0000829 /**
830 * Flag to indicate that an app is not subject to any restrictions that could result in its
831 * network access blocked.
832 *
833 * @hide
834 */
835 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
836 public static final int BLOCKED_REASON_NONE = 0;
837
838 /**
839 * Flag to indicate that an app is subject to Battery saver restrictions that would
840 * result in its network access being blocked.
841 *
842 * @hide
843 */
844 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
845 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
846
847 /**
848 * Flag to indicate that an app is subject to Doze restrictions that would
849 * result in its network access being blocked.
850 *
851 * @hide
852 */
853 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
854 public static final int BLOCKED_REASON_DOZE = 1 << 1;
855
856 /**
857 * Flag to indicate that an app is subject to App Standby restrictions that would
858 * result in its network access being blocked.
859 *
860 * @hide
861 */
862 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
863 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
864
865 /**
866 * Flag to indicate that an app is subject to Restricted mode restrictions that would
867 * result in its network access being blocked.
868 *
869 * @hide
870 */
871 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
872 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
873
874 /**
875 * Flag to indicate that an app is subject to Data saver restrictions that would
876 * result in its metered network access being blocked.
877 *
878 * @hide
879 */
880 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
881 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
882
883 /**
884 * Flag to indicate that an app is subject to user restrictions that would
885 * result in its metered network access being blocked.
886 *
887 * @hide
888 */
889 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
890 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
891
892 /**
893 * Flag to indicate that an app is subject to Device admin restrictions that would
894 * result in its metered network access being blocked.
895 *
896 * @hide
897 */
898 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
899 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
900
901 /**
902 * @hide
903 */
904 @Retention(RetentionPolicy.SOURCE)
905 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
906 BLOCKED_REASON_NONE,
907 BLOCKED_REASON_BATTERY_SAVER,
908 BLOCKED_REASON_DOZE,
909 BLOCKED_REASON_APP_STANDBY,
910 BLOCKED_REASON_RESTRICTED_MODE,
911 BLOCKED_METERED_REASON_DATA_SAVER,
912 BLOCKED_METERED_REASON_USER_RESTRICTED,
913 BLOCKED_METERED_REASON_ADMIN_DISABLED,
914 })
915 public @interface BlockedReason {}
916
Chalard Jeana3b77512019-04-09 15:46:21 +0900917 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700918 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900919
Paul Jensenc0618a62014-12-10 15:12:18 -0500920 /**
921 * A kludge to facilitate static access where a Context pointer isn't available, like in the
922 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
923 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
924 * methods that take a Context argument.
925 */
926 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800927
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900928 private final Context mContext;
929
Amos Bianchia9b415a2020-03-04 11:07:38 -0800930 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800931
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800932 /**
933 * Tests if a given integer represents a valid network type.
934 * @param networkType the type to be tested
935 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400936 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
937 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800938 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700939 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700940 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900941 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800942 }
943
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800944 /**
945 * Returns a non-localized string representing a given network type.
946 * ONLY used for debugging output.
947 * @param type the type needing naming
948 * @return a String for the given type, or a string version of the type ("87")
949 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900950 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800951 * {@hide}
952 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900953 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000954 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700955 public static String getNetworkTypeName(int type) {
956 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900957 case TYPE_NONE:
958 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700959 case TYPE_MOBILE:
960 return "MOBILE";
961 case TYPE_WIFI:
962 return "WIFI";
963 case TYPE_MOBILE_MMS:
964 return "MOBILE_MMS";
965 case TYPE_MOBILE_SUPL:
966 return "MOBILE_SUPL";
967 case TYPE_MOBILE_DUN:
968 return "MOBILE_DUN";
969 case TYPE_MOBILE_HIPRI:
970 return "MOBILE_HIPRI";
971 case TYPE_WIMAX:
972 return "WIMAX";
973 case TYPE_BLUETOOTH:
974 return "BLUETOOTH";
975 case TYPE_DUMMY:
976 return "DUMMY";
977 case TYPE_ETHERNET:
978 return "ETHERNET";
979 case TYPE_MOBILE_FOTA:
980 return "MOBILE_FOTA";
981 case TYPE_MOBILE_IMS:
982 return "MOBILE_IMS";
983 case TYPE_MOBILE_CBS:
984 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700985 case TYPE_WIFI_P2P:
986 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700987 case TYPE_MOBILE_IA:
988 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700989 case TYPE_MOBILE_EMERGENCY:
990 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500991 case TYPE_PROXY:
992 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900993 case TYPE_VPN:
994 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700995 default:
996 return Integer.toString(type);
997 }
998 }
999
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001000 /**
Aaron Huang96011892020-06-27 07:18:23 +08001001 * @hide
Aaron Huang96011892020-06-27 07:18:23 +08001002 */
lucaslin7fc930b2021-03-17 14:16:01 +08001003 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huang96011892020-06-27 07:18:23 +08001004 public void systemReady() {
1005 try {
1006 mService.systemReady();
1007 } catch (RemoteException e) {
1008 throw e.rethrowFromSystemServer();
1009 }
1010 }
1011
1012 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001013 * Checks if a given type uses the cellular data connection.
1014 * This should be replaced in the future by a network property.
1015 * @param networkType the type to check
1016 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001017 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001018 * {@hide}
1019 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001020 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +09001021 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001022 public static boolean isNetworkTypeMobile(int networkType) {
1023 switch (networkType) {
1024 case TYPE_MOBILE:
1025 case TYPE_MOBILE_MMS:
1026 case TYPE_MOBILE_SUPL:
1027 case TYPE_MOBILE_DUN:
1028 case TYPE_MOBILE_HIPRI:
1029 case TYPE_MOBILE_FOTA:
1030 case TYPE_MOBILE_IMS:
1031 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -07001032 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -07001033 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -07001034 return true;
1035 default:
1036 return false;
1037 }
1038 }
1039
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001040 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001041 * Checks if the given network type is backed by a Wi-Fi radio.
1042 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001043 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001044 * @hide
1045 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001046 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001047 public static boolean isNetworkTypeWifi(int networkType) {
1048 switch (networkType) {
1049 case TYPE_WIFI:
1050 case TYPE_WIFI_P2P:
1051 return true;
1052 default:
1053 return false;
1054 }
1055 }
1056
1057 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +09001058 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1059 * Specify that the traffic for this user should by follow the default rules.
1060 * @hide
1061 */
Chalard Jeanb43f3962021-03-17 14:33:24 +09001062 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09001063 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1064
1065 /**
1066 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1067 * Specify that the traffic for this user should by default go on a network with
1068 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1069 * if no such network is available.
1070 * @hide
1071 */
Chalard Jeanb43f3962021-03-17 14:33:24 +09001072 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09001073 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1074
1075 /** @hide */
1076 @Retention(RetentionPolicy.SOURCE)
1077 @IntDef(value = {
1078 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1079 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1080 })
1081 public @interface ProfileNetworkPreference {
1082 }
1083
1084 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001085 * Specifies the preferred network type. When the device has more
1086 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001087 *
1088 * @param preference the network type to prefer over all others. It is
1089 * unspecified what happens to the old preferred network in the
1090 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001091 * @deprecated Functionality has been removed as it no longer makes sense,
1092 * with many more than two networks - we'd need an array to express
1093 * preference. Instead we use dynamic network properties of
1094 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001095 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001096 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001097 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001098 }
1099
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001100 /**
1101 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001102 *
1103 * @return an integer representing the preferred network type
1104 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001105 * @deprecated Functionality has been removed as it no longer makes sense,
1106 * with many more than two networks - we'd need an array to express
1107 * preference. Instead we use dynamic network properties of
1108 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001109 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001110 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001111 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001112 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001113 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001114 }
1115
Scott Mainf58b7d82011-10-06 19:02:28 -07001116 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001117 * Returns details about the currently active default data network. When
1118 * connected, this network is the default route for outgoing connections.
1119 * You should always check {@link NetworkInfo#isConnected()} before initiating
1120 * network traffic. This may return {@code null} when there is no default
1121 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001122 * Note that if the default network is a VPN, this method will return the
1123 * NetworkInfo for one of its underlying networks instead, or null if the
1124 * VPN agent did not specify any. Apps interested in learning about VPNs
1125 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001126 *
1127 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001128 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001129 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001130 */
junyulai9826e7f2018-12-13 12:47:51 +08001131 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001132 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001133 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001134 public NetworkInfo getActiveNetworkInfo() {
1135 try {
1136 return mService.getActiveNetworkInfo();
1137 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001138 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001139 }
1140 }
1141
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001142 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001143 * Returns a {@link Network} object corresponding to the currently active
1144 * default data network. In the event that the current active default data
1145 * network disconnects, the returned {@code Network} object will no longer
1146 * be usable. This will return {@code null} when there is no default
1147 * network.
1148 *
1149 * @return a {@link Network} object for the current default network or
1150 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001151 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001152 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001153 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001154 public Network getActiveNetwork() {
1155 try {
1156 return mService.getActiveNetwork();
1157 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001158 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001159 }
1160 }
1161
1162 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001163 * Returns a {@link Network} object corresponding to the currently active
1164 * default data network for a specific UID. In the event that the default data
1165 * network disconnects, the returned {@code Network} object will no longer
1166 * be usable. This will return {@code null} when there is no default
1167 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001168 *
1169 * @return a {@link Network} object for the current default network for the
1170 * given UID or {@code null} if no default network is currently active
1171 *
1172 * @hide
1173 */
paulhu8e96a752019-08-12 16:25:11 +08001174 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001175 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001176 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001177 return getActiveNetworkForUid(uid, false);
1178 }
1179
1180 /** {@hide} */
1181 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001182 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001183 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001184 } catch (RemoteException e) {
1185 throw e.rethrowFromSystemServer();
1186 }
1187 }
1188
1189 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001190 * Adds or removes a requirement for given UID ranges to use the VPN.
1191 *
1192 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1193 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1194 * otherwise have permission to bypass the VPN (e.g., because they have the
1195 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1196 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1197 * set to {@code false}, a previously-added restriction is removed.
1198 * <p>
1199 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1200 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1201 * remove a previously-added range, the exact range must be removed as is.
1202 * <p>
1203 * The changes are applied asynchronously and may not have been applied by the time the method
1204 * returns. Apps will be notified about any changes that apply to them via
1205 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1206 * effect.
1207 * <p>
1208 * This method should be called only by the VPN code.
1209 *
1210 * @param ranges the UID ranges to restrict
1211 * @param requireVpn whether the specified UID ranges must use a VPN
1212 *
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001213 * @hide
1214 */
1215 @RequiresPermission(anyOf = {
1216 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucasline257bce2021-03-22 11:51:27 +08001217 android.Manifest.permission.NETWORK_STACK,
1218 android.Manifest.permission.NETWORK_SETTINGS})
1219 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001220 public void setRequireVpnForUids(boolean requireVpn,
1221 @NonNull Collection<Range<Integer>> ranges) {
1222 Objects.requireNonNull(ranges);
1223 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1224 // This method is not necessarily expected to be used outside the system server, so
1225 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1226 // stack process, or by tests.
1227 UidRange[] rangesArray = new UidRange[ranges.size()];
1228 int index = 0;
1229 for (Range<Integer> range : ranges) {
1230 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1231 }
1232 try {
1233 mService.setRequireVpnForUids(requireVpn, rangesArray);
1234 } catch (RemoteException e) {
1235 throw e.rethrowFromSystemServer();
1236 }
1237 }
1238
1239 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001240 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1241 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1242 * but is still supported for backwards compatibility.
1243 * <p>
1244 * This type of VPN is assumed always to use the system default network, and must always declare
1245 * exactly one underlying network, which is the network that was the default when the VPN
1246 * connected.
1247 * <p>
1248 * Calling this method with {@code true} enables legacy behaviour, specifically:
1249 * <ul>
1250 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1251 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1252 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1253 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1254 * underlying the VPN.</li>
1255 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1256 * similarly replaced by the VPN network state.</li>
1257 * <li>Information on current network interfaces passed to NetworkStatsService will not
1258 * include any VPN interfaces.</li>
1259 * </ul>
1260 *
1261 * @param enabled whether legacy lockdown VPN is enabled or disabled
1262 *
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001263 * @hide
1264 */
1265 @RequiresPermission(anyOf = {
1266 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucasline257bce2021-03-22 11:51:27 +08001267 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001268 android.Manifest.permission.NETWORK_SETTINGS})
lucasline257bce2021-03-22 11:51:27 +08001269 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001270 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1271 try {
1272 mService.setLegacyLockdownVpnEnabled(enabled);
1273 } catch (RemoteException e) {
1274 throw e.rethrowFromSystemServer();
1275 }
1276 }
1277
1278 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001279 * Returns details about the currently active default data network
1280 * for a given uid. This is for internal use only to avoid spying
1281 * other apps.
1282 *
1283 * @return a {@link NetworkInfo} object for the current default network
1284 * for the given uid or {@code null} if no default network is
1285 * available for the specified uid.
1286 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001287 * {@hide}
1288 */
paulhu8e96a752019-08-12 16:25:11 +08001289 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001290 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001291 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001292 return getActiveNetworkInfoForUid(uid, false);
1293 }
1294
1295 /** {@hide} */
1296 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001297 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001298 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001299 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001300 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001301 }
1302 }
1303
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001304 /**
1305 * Returns connection status information about a particular
1306 * network type.
1307 *
1308 * @param networkType integer specifying which networkType in
1309 * which you're interested.
1310 * @return a {@link NetworkInfo} object for the requested
1311 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001312 * supported by the device. If {@code networkType} is
1313 * TYPE_VPN and a VPN is active for the calling app,
1314 * then this method will try to return one of the
1315 * underlying networks for the VPN or null if the
1316 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001317 *
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.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001321 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001322 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001323 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001324 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001325 public NetworkInfo getNetworkInfo(int networkType) {
1326 try {
1327 return mService.getNetworkInfo(networkType);
1328 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001329 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001330 }
1331 }
1332
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001333 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001334 * Returns connection status information about a particular
1335 * Network.
1336 *
1337 * @param network {@link Network} specifying which network
1338 * in which you're interested.
1339 * @return a {@link NetworkInfo} object for the requested
1340 * network or {@code null} if the {@code Network}
1341 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001342 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001343 */
junyulai9826e7f2018-12-13 12:47:51 +08001344 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001345 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001346 @Nullable
1347 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001348 return getNetworkInfoForUid(network, Process.myUid(), false);
1349 }
1350
1351 /** {@hide} */
1352 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001353 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001354 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001355 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001356 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001357 }
1358 }
1359
1360 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001361 * Returns connection status information about all network
1362 * types supported by the device.
1363 *
1364 * @return an array of {@link NetworkInfo} objects. Check each
1365 * {@link NetworkInfo#getType} for which type each applies.
1366 *
Paul Jensendda8e592015-03-18 12:23:02 -04001367 * @deprecated This method does not support multiple connected networks
1368 * of the same type. Use {@link #getAllNetworks} and
1369 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001370 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001371 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001372 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001373 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001374 public NetworkInfo[] getAllNetworkInfo() {
1375 try {
1376 return mService.getAllNetworkInfo();
1377 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001378 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001379 }
1380 }
1381
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001382 /**
junyulaiebd15162021-03-03 12:09:05 +08001383 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1384 * connected.
1385 * @hide
1386 */
1387 @SystemApi(client = MODULE_LIBRARIES)
1388 @RequiresPermission(anyOf = {
1389 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1390 android.Manifest.permission.NETWORK_STACK,
1391 android.Manifest.permission.NETWORK_SETTINGS})
1392 @NonNull
1393 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1394 try {
1395 return mService.getAllNetworkStateSnapshot();
1396 } catch (RemoteException e) {
1397 throw e.rethrowFromSystemServer();
1398 }
1399 }
1400
1401 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001402 * Returns the {@link Network} object currently serving a given type, or
1403 * null if the given type is not connected.
1404 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001405 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001406 * @deprecated This method does not support multiple connected networks
1407 * of the same type. Use {@link #getAllNetworks} and
1408 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001409 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001410 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001411 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001412 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001413 public Network getNetworkForType(int networkType) {
1414 try {
1415 return mService.getNetworkForType(networkType);
1416 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001417 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001418 }
1419 }
1420
1421 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001422 * Returns an array of all {@link Network} currently tracked by the
1423 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001424 *
1425 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001426 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001427 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001428 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001429 public Network[] getAllNetworks() {
1430 try {
1431 return mService.getAllNetworks();
1432 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001433 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001434 }
1435 }
1436
1437 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001438 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001439 * the Networks that applications run by the given user will use by default.
1440 * @hide
1441 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001442 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001443 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1444 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001445 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001446 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001447 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001448 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001449 }
1450 }
1451
1452 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001453 * Returns the IP information for the current default network.
1454 *
1455 * @return a {@link LinkProperties} object describing the IP info
1456 * for the current default network, or {@code null} if there
1457 * is no current default network.
1458 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001459 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001460 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1461 * value of {@link #getActiveNetwork()} instead. In particular,
1462 * this method will return non-null LinkProperties even if the
1463 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001464 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001465 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001466 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001467 public LinkProperties getActiveLinkProperties() {
1468 try {
1469 return mService.getActiveLinkProperties();
1470 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001471 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001472 }
1473 }
1474
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001475 /**
1476 * Returns the IP information for a given network type.
1477 *
1478 * @param networkType the network type of interest.
1479 * @return a {@link LinkProperties} object describing the IP info
1480 * for the given networkType, or {@code null} if there is
1481 * no current default network.
1482 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001483 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001484 * @deprecated This method does not support multiple connected networks
1485 * of the same type. Use {@link #getAllNetworks},
1486 * {@link #getNetworkInfo(android.net.Network)}, and
1487 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001488 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001489 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001490 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001491 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001492 public LinkProperties getLinkProperties(int networkType) {
1493 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001494 return mService.getLinkPropertiesForType(networkType);
1495 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001496 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001497 }
1498 }
1499
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001500 /**
1501 * Get the {@link LinkProperties} for the given {@link Network}. This
1502 * will return {@code null} if the network is unknown.
1503 *
1504 * @param network The {@link Network} object identifying the network in question.
1505 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001506 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001507 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001508 @Nullable
1509 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001510 try {
1511 return mService.getLinkProperties(network);
1512 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001513 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001514 }
1515 }
1516
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001517 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001518 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001519 * will return {@code null} if the network is unknown.
1520 *
Roshan Pius951c0032020-12-22 15:10:42 -08001521 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1522 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1523 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1524 * this location sensitive information (subject to app's location permissions) will be
1525 * noted by system. To include any location sensitive data in {@link TransportInfo},
1526 * use a {@link NetworkCallback} with
1527 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1528 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001529 * @param network The {@link Network} object identifying the network in question.
Roshan Pius951c0032020-12-22 15:10:42 -08001530 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001531 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001532 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001533 @Nullable
1534 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001535 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001536 return mService.getNetworkCapabilities(
1537 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001538 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001539 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001540 }
1541 }
1542
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001543 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001544 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001545 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1546 * portal is present.
1547 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1548 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1549 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001550 * The system network validation may be using different strategies to detect captive portals,
1551 * so this method does not necessarily return a URL used by the system. It only returns a URL
1552 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001553 *
Udam Sainicd645462016-01-04 12:16:14 -08001554 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001555 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1556 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001557 */
paulhu8e96a752019-08-12 16:25:11 +08001558 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001559 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001560 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001561 public String getCaptivePortalServerUrl() {
1562 try {
1563 return mService.getCaptivePortalServerUrl();
1564 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001565 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001566 }
1567 }
1568
1569 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001570 * Tells the underlying networking system that the caller wants to
1571 * begin using the named feature. The interpretation of {@code feature}
1572 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001573 *
1574 * <p>This method requires the caller to hold either the
1575 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1576 * or the ability to modify system settings as determined by
1577 * {@link android.provider.Settings.System#canWrite}.</p>
1578 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001579 * @param networkType specifies which network the request pertains to
1580 * @param feature the name of the feature to be used
1581 * @return an integer value representing the outcome of the request.
1582 * The interpretation of this value is specific to each networking
1583 * implementation+feature combination, except that the value {@code -1}
1584 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001585 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001586 * @deprecated Deprecated in favor of the cleaner
1587 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001588 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001589 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001590 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001591 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001592 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001593 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001594 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001595 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1596 if (netCap == null) {
1597 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1598 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001599 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001600 }
1601
1602 NetworkRequest request = null;
1603 synchronized (sLegacyRequests) {
1604 LegacyRequest l = sLegacyRequests.get(netCap);
1605 if (l != null) {
1606 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1607 renewRequestLocked(l);
1608 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001609 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001610 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001611 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001612 }
1613 }
1614
1615 request = requestNetworkForFeatureLocked(netCap);
1616 }
1617 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001618 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001619 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001620 } else {
1621 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001622 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001623 }
1624 }
1625
1626 /**
1627 * Tells the underlying networking system that the caller is finished
1628 * using the named feature. The interpretation of {@code feature}
1629 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001630 *
1631 * <p>This method requires the caller to hold either the
1632 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1633 * or the ability to modify system settings as determined by
1634 * {@link android.provider.Settings.System#canWrite}.</p>
1635 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001636 * @param networkType specifies which network the request pertains to
1637 * @param feature the name of the feature that is no longer needed
1638 * @return an integer value representing the outcome of the request.
1639 * The interpretation of this value is specific to each networking
1640 * implementation+feature combination, except that the value {@code -1}
1641 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001642 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001643 * @deprecated Deprecated in favor of the cleaner
1644 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001645 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001646 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001647 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001648 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001649 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001650 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001651 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001652 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1653 if (netCap == null) {
1654 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1655 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001656 return -1;
1657 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001658
Paul Jensen49f74a32014-12-17 10:39:34 -05001659 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001660 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001661 }
1662 return 1;
1663 }
1664
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001665 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001666 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1667 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001668 switch (feature) {
1669 case "enableCBS":
1670 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1671 case "enableDUN":
1672 case "enableDUNAlways":
1673 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1674 case "enableFOTA":
1675 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1676 case "enableHIPRI":
1677 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1678 case "enableIMS":
1679 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1680 case "enableMMS":
1681 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1682 case "enableSUPL":
1683 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1684 default:
1685 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001686 }
Erik Klinece55eb12017-01-26 18:08:28 +09001687 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1688 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001689 }
1690 return null;
1691 }
1692
Robert Greenwalt802c1102014-06-02 15:32:02 -07001693 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001694 if (netCap == null) return TYPE_NONE;
1695 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1696 return TYPE_MOBILE_CBS;
1697 }
1698 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1699 return TYPE_MOBILE_IMS;
1700 }
1701 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1702 return TYPE_MOBILE_FOTA;
1703 }
1704 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1705 return TYPE_MOBILE_DUN;
1706 }
1707 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1708 return TYPE_MOBILE_SUPL;
1709 }
1710 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1711 return TYPE_MOBILE_MMS;
1712 }
1713 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1714 return TYPE_MOBILE_HIPRI;
1715 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001716 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1717 return TYPE_WIFI_P2P;
1718 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001719 return TYPE_NONE;
1720 }
1721
1722 private static class LegacyRequest {
1723 NetworkCapabilities networkCapabilities;
1724 NetworkRequest networkRequest;
1725 int expireSequenceNumber;
1726 Network currentNetwork;
1727 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001728
1729 private void clearDnsBinding() {
1730 if (currentNetwork != null) {
1731 currentNetwork = null;
1732 setProcessDefaultNetworkForHostResolution(null);
1733 }
1734 }
1735
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001736 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001737 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001738 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001739 currentNetwork = network;
1740 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001741 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001742 }
1743 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001744 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001745 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001746 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1747 }
1748 };
1749 }
1750
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001751 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001752 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1753 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001754
1755 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1756 synchronized (sLegacyRequests) {
1757 LegacyRequest l = sLegacyRequests.get(netCap);
1758 if (l != null) return l.networkRequest;
1759 }
1760 return null;
1761 }
1762
1763 private void renewRequestLocked(LegacyRequest l) {
1764 l.expireSequenceNumber++;
1765 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1766 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1767 }
1768
1769 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1770 int ourSeqNum = -1;
1771 synchronized (sLegacyRequests) {
1772 LegacyRequest l = sLegacyRequests.get(netCap);
1773 if (l == null) return;
1774 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001775 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001776 }
1777 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1778 }
1779
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001780 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001781 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1782 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001783 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001784 try {
1785 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001786 } catch (RemoteException e) {
1787 throw e.rethrowFromSystemServer();
1788 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001789 LegacyRequest l = new LegacyRequest();
1790 l.networkCapabilities = netCap;
1791 l.delay = delay;
1792 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001793 l.networkRequest = sendRequestForNetwork(
1794 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001795 if (l.networkRequest == null) return null;
1796 sLegacyRequests.put(netCap, l);
1797 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1798 return l.networkRequest;
1799 }
1800
1801 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1802 if (delay >= 0) {
1803 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001804 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001805 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1806 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001807 }
1808 }
1809
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001810 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001811 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1812 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001813 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001814 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001815 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001816 if (l == null) return false;
1817 unregisterNetworkCallback(l.networkCallback);
1818 l.clearDnsBinding();
1819 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001820 }
1821
Erik Klinece55eb12017-01-26 18:08:28 +09001822 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1823 static {
1824 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1825 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1826 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1827 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1828 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1829 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1830 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1831 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1832 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1833 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1834 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1835 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1836 }
1837
1838 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1839 static {
1840 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1841 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1842 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1843 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1844 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1845 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1846 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1847 }
1848
1849 /**
1850 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1851 * instance suitable for registering a request or callback. Throws an
1852 * IllegalArgumentException if no mapping from the legacy type to
1853 * NetworkCapabilities is known.
1854 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001855 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1856 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001857 * @hide
1858 */
1859 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1860 final NetworkCapabilities nc = new NetworkCapabilities();
1861
1862 // Map from type to transports.
1863 final int NOT_FOUND = -1;
1864 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00001865 if (transport == NOT_FOUND) {
1866 throw new IllegalArgumentException("unknown legacy type: " + type);
1867 }
Erik Klinece55eb12017-01-26 18:08:28 +09001868 nc.addTransportType(transport);
1869
1870 // Map from type to capabilities.
1871 nc.addCapability(sLegacyTypeToCapability.get(
1872 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1873 nc.maybeMarkCapabilitiesRestricted();
1874 return nc;
1875 }
1876
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001877 /** @hide */
1878 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001879 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001880 public PacketKeepaliveCallback() {
1881 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001882 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001883 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001884 public void onStarted() {}
1885 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001886 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001887 public void onStopped() {}
1888 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001889 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001890 public void onError(int error) {}
1891 }
1892
1893 /**
1894 * Allows applications to request that the system periodically send specific packets on their
1895 * behalf, using hardware offload to save battery power.
1896 *
1897 * To request that the system send keepalives, call one of the methods that return a
1898 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1899 * passing in a non-null callback. If the callback is successfully started, the callback's
1900 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1901 * specifying one of the {@code ERROR_*} constants in this class.
1902 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001903 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1904 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1905 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001906 *
junyulai4c95b082018-12-27 17:25:29 +08001907 * @deprecated Use {@link SocketKeepalive} instead.
1908 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001909 * @hide
1910 */
1911 public class PacketKeepalive {
1912
1913 private static final String TAG = "PacketKeepalive";
1914
1915 /** @hide */
1916 public static final int SUCCESS = 0;
1917
1918 /** @hide */
1919 public static final int NO_KEEPALIVE = -1;
1920
1921 /** @hide */
1922 public static final int BINDER_DIED = -10;
1923
1924 /** The specified {@code Network} is not connected. */
1925 public static final int ERROR_INVALID_NETWORK = -20;
1926 /** The specified IP addresses are invalid. For example, the specified source IP address is
1927 * not configured on the specified {@code Network}. */
1928 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1929 /** The requested port is invalid. */
1930 public static final int ERROR_INVALID_PORT = -22;
1931 /** The packet length is invalid (e.g., too long). */
1932 public static final int ERROR_INVALID_LENGTH = -23;
1933 /** The packet transmission interval is invalid (e.g., too short). */
1934 public static final int ERROR_INVALID_INTERVAL = -24;
1935
1936 /** The hardware does not support this request. */
1937 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001938 /** The hardware returned an error. */
1939 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001940
Nathan Harold0990bc82018-02-14 13:09:45 -08001941 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001942 public static final int NATT_PORT = 4500;
1943
Nathan Harold0990bc82018-02-14 13:09:45 -08001944 /** The minimum interval in seconds between keepalive packet transmissions */
1945 public static final int MIN_INTERVAL = 10;
1946
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001947 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001948 private final ISocketKeepaliveCallback mCallback;
1949 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001950
1951 private volatile Integer mSlot;
1952
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001953 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001954 public void stop() {
1955 try {
junyulai070f9ff2019-01-16 20:23:34 +08001956 mExecutor.execute(() -> {
1957 try {
1958 if (mSlot != null) {
1959 mService.stopKeepalive(mNetwork, mSlot);
1960 }
1961 } catch (RemoteException e) {
1962 Log.e(TAG, "Error stopping packet keepalive: ", e);
1963 throw e.rethrowFromSystemServer();
1964 }
1965 });
1966 } catch (RejectedExecutionException e) {
1967 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001968 }
1969 }
1970
1971 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00001972 Objects.requireNonNull(network, "network cannot be null");
1973 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001974 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001975 mExecutor = Executors.newSingleThreadExecutor();
1976 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001977 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001978 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001979 final long token = Binder.clearCallingIdentity();
1980 try {
1981 mExecutor.execute(() -> {
1982 mSlot = slot;
1983 callback.onStarted();
1984 });
1985 } finally {
1986 Binder.restoreCallingIdentity(token);
1987 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001988 }
junyulai070f9ff2019-01-16 20:23:34 +08001989
1990 @Override
1991 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001992 final long token = Binder.clearCallingIdentity();
1993 try {
1994 mExecutor.execute(() -> {
1995 mSlot = null;
1996 callback.onStopped();
1997 });
1998 } finally {
1999 Binder.restoreCallingIdentity(token);
2000 }
junyulai070f9ff2019-01-16 20:23:34 +08002001 mExecutor.shutdown();
2002 }
2003
2004 @Override
2005 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08002006 final long token = Binder.clearCallingIdentity();
2007 try {
2008 mExecutor.execute(() -> {
2009 mSlot = null;
2010 callback.onError(error);
2011 });
2012 } finally {
2013 Binder.restoreCallingIdentity(token);
2014 }
junyulai070f9ff2019-01-16 20:23:34 +08002015 mExecutor.shutdown();
2016 }
2017
2018 @Override
2019 public void onDataReceived() {
2020 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2021 // this callback when data is received.
2022 }
2023 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002024 }
2025 }
2026
2027 /**
2028 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2029 *
junyulai4c95b082018-12-27 17:25:29 +08002030 * @deprecated Use {@link #createSocketKeepalive} instead.
2031 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002032 * @hide
2033 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002034 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002035 public PacketKeepalive startNattKeepalive(
2036 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2037 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2038 final PacketKeepalive k = new PacketKeepalive(network, callback);
2039 try {
junyulai070f9ff2019-01-16 20:23:34 +08002040 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002041 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2042 } catch (RemoteException e) {
2043 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08002044 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002045 }
2046 return k;
2047 }
2048
Chiachang Wang619319a2021-01-15 11:06:21 +08002049 // Construct an invalid fd.
2050 private ParcelFileDescriptor createInvalidFd() {
2051 final int invalidFd = -1;
2052 return ParcelFileDescriptor.adoptFd(invalidFd);
2053 }
2054
The Android Open Source Project28527d22009-03-03 19:31:44 -08002055 /**
junyulai4c95b082018-12-27 17:25:29 +08002056 * Request that keepalives be started on a IPsec NAT-T socket.
2057 *
2058 * @param network The {@link Network} the socket is on.
2059 * @param socket The socket that needs to be kept alive.
2060 * @param source The source address of the {@link UdpEncapsulationSocket}.
2061 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2062 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2063 * must run callback sequentially, otherwise the order of callbacks cannot be
2064 * guaranteed.
2065 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2066 * changes. Must be extended by applications that use this API.
2067 *
junyulai0835a1e2019-01-08 20:04:33 +08002068 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2069 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08002070 **/
junyulai7e06ad42019-03-04 22:45:36 +08002071 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08002072 @NonNull UdpEncapsulationSocket socket,
2073 @NonNull InetAddress source,
2074 @NonNull InetAddress destination,
2075 @NonNull @CallbackExecutor Executor executor,
2076 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002077 ParcelFileDescriptor dup;
2078 try {
junyulai828dad12019-03-27 11:00:37 +08002079 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2080 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08002081 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2082 } catch (IOException ignored) {
2083 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2084 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002085 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002086 }
2087 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2088 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002089 }
2090
2091 /**
2092 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2093 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2094 *
2095 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002096 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2097 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2098 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002099 * @param source The source address of the {@link UdpEncapsulationSocket}.
2100 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2101 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2102 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2103 * must run callback sequentially, otherwise the order of callbacks cannot be
2104 * guaranteed.
2105 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2106 * changes. Must be extended by applications that use this API.
2107 *
junyulai0835a1e2019-01-08 20:04:33 +08002108 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2109 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002110 * @hide
2111 */
2112 @SystemApi
2113 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002114 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2115 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002116 @NonNull InetAddress source,
2117 @NonNull InetAddress destination,
2118 @NonNull @CallbackExecutor Executor executor,
2119 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002120 ParcelFileDescriptor dup;
2121 try {
junyulai828dad12019-03-27 11:00:37 +08002122 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002123 dup = pfd.dup();
2124 } catch (IOException ignored) {
2125 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2126 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002127 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002128 }
2129 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANce355502021-03-11 10:56:49 +00002130 -1 /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002131 }
2132
2133 /**
junyulai0835a1e2019-01-08 20:04:33 +08002134 * Request that keepalives be started on a TCP socket.
2135 * The socket must be established.
2136 *
2137 * @param network The {@link Network} the socket is on.
2138 * @param socket The socket that needs to be kept alive.
2139 * @param executor The executor on which callback will be invoked. This implementation assumes
2140 * the provided {@link Executor} runs the callbacks in sequence with no
2141 * concurrency. Failing this, no guarantee of correctness can be made. It is
2142 * the responsibility of the caller to ensure the executor provides this
2143 * guarantee. A simple way of creating such an executor is with the standard
2144 * tool {@code Executors.newSingleThreadExecutor}.
2145 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2146 * changes. Must be extended by applications that use this API.
2147 *
2148 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2149 * given socket.
2150 * @hide
2151 */
2152 @SystemApi
2153 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002154 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002155 @NonNull Socket socket,
2156 @NonNull Executor executor,
2157 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002158 ParcelFileDescriptor dup;
2159 try {
2160 dup = ParcelFileDescriptor.fromSocket(socket);
2161 } catch (UncheckedIOException ignored) {
2162 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2163 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002164 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002165 }
2166 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002167 }
2168
2169 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002170 * Ensure that a network route exists to deliver traffic to the specified
2171 * host via the specified network interface. An attempt to add a route that
2172 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002173 *
2174 * <p>This method requires the caller to hold either the
2175 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2176 * or the ability to modify system settings as determined by
2177 * {@link android.provider.Settings.System#canWrite}.</p>
2178 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002179 * @param networkType the type of the network over which traffic to the specified
2180 * host is to be routed
2181 * @param hostAddress the IP address of the host to which the route is desired
2182 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002183 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002184 * @deprecated Deprecated in favor of the
2185 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2186 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002187 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002188 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002189 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002190 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002191 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002192 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002193 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002194 }
2195
2196 /**
2197 * Ensure that a network route exists to deliver traffic to the specified
2198 * host via the specified network interface. An attempt to add a route that
2199 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002200 *
2201 * <p>This method requires the caller to hold either the
2202 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2203 * or the ability to modify system settings as determined by
2204 * {@link android.provider.Settings.System#canWrite}.</p>
2205 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002206 * @param networkType the type of the network over which traffic to the specified
2207 * host is to be routed
2208 * @param hostAddress the IP address of the host to which the route is desired
2209 * @return {@code true} on success, {@code false} on failure
2210 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002211 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002212 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002213 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002214 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002215 @UnsupportedAppUsage
lucasline257bce2021-03-22 11:51:27 +08002216 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002217 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002218 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002219 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002220 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2221 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002222 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002223 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002224 }
2225 }
2226
2227 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002228 * @return the context's attribution tag
2229 */
2230 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2231 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002232 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002233 }
2234
2235 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002236 * Returns the value of the setting for background data usage. If false,
2237 * applications should not use the network if the application is not in the
2238 * foreground. Developers should respect this setting, and check the value
2239 * of this before performing any background data operations.
2240 * <p>
2241 * All applications that have background services that use the network
2242 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002243 * <p>
Scott Main50589142011-10-06 18:32:43 -07002244 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002245 * background data depends on several combined factors, and this method will
2246 * always return {@code true}. Instead, when background data is unavailable,
2247 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002248 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002249 * @return Whether background data usage is allowed.
2250 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002251 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002252 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002253 // assume that background data is allowed; final authority is
2254 // NetworkInfo which may be blocked.
2255 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002256 }
2257
2258 /**
2259 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002260 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002261 * @param allowBackgroundData Whether an application should use data while
2262 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002263 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002264 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2265 * @see #getBackgroundDataSetting()
2266 * @hide
2267 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002268 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002269 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002270 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002271 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002272 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002273
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002274 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002275 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002276 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002277 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002278 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002279 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002280 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002281 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2282 if (tm != null) {
2283 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2284 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2285 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2286 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2287 + " retVal=" + retVal);
2288 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002289 }
Wink Saville689f7042014-12-05 11:10:30 -08002290 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002291 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002292 }
2293
The Android Open Source Project28527d22009-03-03 19:31:44 -08002294 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002295 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002296 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002297 */
2298 public interface OnNetworkActiveListener {
2299 /**
2300 * Called on the main thread of the process to report that the current data network
2301 * has become active, and it is now a good time to perform any pending network
2302 * operations. Note that this listener only tells you when the network becomes
2303 * active; if at any other time you want to know whether it is active (and thus okay
2304 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002305 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002306 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002307 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002308 }
2309
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002310 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002311 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002312
2313 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002314 * Start listening to reports when the system's default data network is active, meaning it is
2315 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2316 * to determine the current state of the system's default network after registering the
2317 * listener.
2318 * <p>
2319 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002320 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002321 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002322 *
2323 * @param l The listener to be told when the network is active.
2324 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002325 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002326 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2327 @Override
2328 public void onNetworkActive() throws RemoteException {
2329 l.onNetworkActive();
2330 }
2331 };
2332
2333 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002334 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002335 mNetworkActivityListeners.put(l, rl);
2336 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002337 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002338 }
2339 }
2340
2341 /**
2342 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002343 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002344 *
2345 * @param l Previously registered listener.
2346 */
Chalard Jean158702d2019-01-07 19:26:34 +09002347 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002348 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002349 if (rl == null) {
2350 throw new IllegalArgumentException("Listener was not registered.");
2351 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002352 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002353 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002354 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002355 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002356 }
2357 }
2358
2359 /**
2360 * Return whether the data network is currently active. An active network means that
2361 * it is currently in a high power state for performing data transmission. On some
2362 * types of networks, it may be expensive to move and stay in such a state, so it is
2363 * more power efficient to batch network traffic together when the radio is already in
2364 * this state. This method tells you whether right now is currently a good time to
2365 * initiate network traffic, as the network is already active.
2366 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002367 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002368 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002369 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002370 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002371 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002372 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002373 }
2374
2375 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002376 * {@hide}
2377 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002378 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002379 mContext = Objects.requireNonNull(context, "missing context");
2380 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002381 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002382 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002383 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002384
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002385 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002386 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002387 public static ConnectivityManager from(Context context) {
2388 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2389 }
2390
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002391 /** @hide */
2392 public NetworkRequest getDefaultRequest() {
2393 try {
2394 // This is not racy as the default request is final in ConnectivityService.
2395 return mService.getDefaultRequest();
2396 } catch (RemoteException e) {
2397 throw e.rethrowFromSystemServer();
2398 }
2399 }
2400
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002401 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002402 * Check if the package is a allowed to write settings. This also accounts that such an access
2403 * happened.
2404 *
2405 * @return {@code true} iff the package is allowed to write settings.
2406 */
2407 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2408 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2409 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2410 boolean throwException) {
2411 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2412 throwException);
2413 }
2414
2415 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002416 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2417 * situations where a Context pointer is unavailable.
2418 * @hide
2419 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002420 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002421 static ConnectivityManager getInstanceOrNull() {
2422 return sInstance;
2423 }
2424
2425 /**
2426 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2427 * situations where a Context pointer is unavailable.
2428 * @hide
2429 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002430 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002431 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002432 private static ConnectivityManager getInstance() {
2433 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002434 throw new IllegalStateException("No ConnectivityManager yet constructed");
2435 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002436 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002437 }
2438
2439 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002440 * Get the set of tetherable, available interfaces. This list is limited by
2441 * device configuration and current interface existence.
2442 *
2443 * @return an array of 0 or more Strings of tetherable interface names.
2444 *
markchien6ae63e52020-01-21 13:11:06 +08002445 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002446 * {@hide}
2447 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002448 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002449 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002450 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002451 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002452 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002453 }
2454
2455 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002456 * Get the set of tethered interfaces.
2457 *
2458 * @return an array of 0 or more String of currently tethered interface names.
2459 *
markchien6ae63e52020-01-21 13:11:06 +08002460 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002461 * {@hide}
2462 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002463 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002464 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002465 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002466 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002467 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002468 }
2469
2470 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002471 * Get the set of interface names which attempted to tether but
2472 * failed. Re-attempting to tether may cause them to reset to the Tethered
2473 * state. Alternatively, causing the interface to be destroyed and recreated
2474 * may cause them to reset to the available state.
2475 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2476 * information on the cause of the errors.
2477 *
2478 * @return an array of 0 or more String indicating the interface names
2479 * which failed to tether.
2480 *
markchien6ae63e52020-01-21 13:11:06 +08002481 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002482 * {@hide}
2483 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002484 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002485 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002486 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002487 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002488 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002489 }
2490
2491 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002492 * Get the set of tethered dhcp ranges.
2493 *
markchien2e6ba522020-02-14 11:55:48 +08002494 * @deprecated This method is not supported.
2495 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002496 * {@hide}
2497 */
paulhu8e96a752019-08-12 16:25:11 +08002498 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002499 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002500 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002501 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002502 }
2503
2504 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002505 * Attempt to tether the named interface. This will setup a dhcp server
2506 * on the interface, forward and NAT IP packets and forward DNS requests
2507 * to the best active upstream network interface. Note that if no upstream
2508 * IP network interface is available, dhcp will still run and traffic will be
2509 * allowed between the tethered devices and this device, though upstream net
2510 * access will of course fail until an upstream network interface becomes
2511 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002512 *
2513 * <p>This method requires the caller to hold either the
2514 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2515 * or the ability to modify system settings as determined by
2516 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002517 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002518 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2519 * and WifiStateMachine which need direct access. All other clients should use
2520 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2521 * logic.</p>
2522 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002523 * @param iface the interface name to tether.
2524 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002525 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002526 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002527 * {@hide}
2528 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002529 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002530 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002531 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002532 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002533 }
2534
2535 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002536 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002537 *
2538 * <p>This method requires the caller to hold either the
2539 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2540 * or the ability to modify system settings as determined by
2541 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002542 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002543 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2544 * and WifiStateMachine which need direct access. All other clients should use
2545 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2546 * logic.</p>
2547 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002548 * @param iface the interface name to untether.
2549 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2550 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002551 * {@hide}
2552 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002553 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002554 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002555 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002556 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002557 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002558
2559 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002560 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002561 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002562 * due to device configuration.
2563 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002564 * <p>If this app does not have permission to use this API, it will always
2565 * return false rather than throw an exception.</p>
2566 *
2567 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2568 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2569 *
2570 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2571 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2572 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002573 * @return a boolean - {@code true} indicating Tethering is supported.
2574 *
markchien6ae63e52020-01-21 13:11:06 +08002575 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002576 * {@hide}
2577 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002578 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002579 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2580 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002581 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002582 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002583 }
2584
2585 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002586 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002587 *
2588 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002589 * @hide
2590 */
2591 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002592 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002593 public static abstract class OnStartTetheringCallback {
2594 /**
2595 * Called when tethering has been successfully started.
2596 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002597 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002598
2599 /**
2600 * Called when starting tethering failed.
2601 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002602 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002603 }
2604
2605 /**
2606 * Convenient overload for
2607 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2608 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002609 *
2610 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002611 * @hide
2612 */
2613 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002614 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002615 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002616 public void startTethering(int type, boolean showProvisioningUi,
2617 final OnStartTetheringCallback callback) {
2618 startTethering(type, showProvisioningUi, callback, null);
2619 }
2620
2621 /**
2622 * Runs tether provisioning for the given type if needed and then starts tethering if
2623 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2624 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2625 * schedules tether provisioning re-checks if appropriate.
2626 *
2627 * @param type The type of tethering to start. Must be one of
2628 * {@link ConnectivityManager.TETHERING_WIFI},
2629 * {@link ConnectivityManager.TETHERING_USB}, or
2630 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2631 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2632 * is one. This should be true the first time this function is called and also any time
2633 * the user can see this UI. It gives users information from their carrier about the
2634 * check failing and how they can sign up for tethering if possible.
2635 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2636 * of the result of trying to tether.
2637 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002638 *
2639 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002640 * @hide
2641 */
2642 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002643 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002644 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002645 public void startTethering(int type, boolean showProvisioningUi,
2646 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002647 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002648
markchien91c78e52020-01-20 19:31:56 +08002649 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002650 @Override
markchien91c78e52020-01-20 19:31:56 +08002651 public void execute(Runnable command) {
2652 if (handler == null) {
2653 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002654 } else {
markchien91c78e52020-01-20 19:31:56 +08002655 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002656 }
2657 }
2658 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002659
markchien91c78e52020-01-20 19:31:56 +08002660 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2661 @Override
2662 public void onTetheringStarted() {
2663 callback.onTetheringStarted();
2664 }
2665
2666 @Override
markchienf47d8342020-03-19 13:37:43 +08002667 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002668 callback.onTetheringFailed();
2669 }
2670 };
2671
2672 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002673 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002674
Amos Bianchia9b415a2020-03-04 11:07:38 -08002675 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002676 }
2677
2678 /**
2679 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2680 * applicable.
2681 *
2682 * @param type The type of tethering to stop. Must be one of
2683 * {@link ConnectivityManager.TETHERING_WIFI},
2684 * {@link ConnectivityManager.TETHERING_USB}, or
2685 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002686 *
2687 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002688 * @hide
2689 */
2690 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002691 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002692 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002693 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002694 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002695 }
2696
2697 /**
markchien4ef53e82019-02-27 14:56:11 +08002698 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2699 * upstream status.
2700 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002701 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002702 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002703 */
2704 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002705 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002706 public abstract static class OnTetheringEventCallback {
2707
2708 /**
2709 * Called when tethering upstream changed. This can be called multiple times and can be
2710 * called any time.
2711 *
2712 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2713 * have any upstream.
2714 */
2715 public void onUpstreamChanged(@Nullable Network network) {}
2716 }
2717
markchien6ae63e52020-01-21 13:11:06 +08002718 @GuardedBy("mTetheringEventCallbacks")
2719 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2720 mTetheringEventCallbacks = new ArrayMap<>();
2721
markchien4ef53e82019-02-27 14:56:11 +08002722 /**
2723 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002724 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002725 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2726 * with a null argument. The same callback object cannot be registered twice.
2727 *
2728 * @param executor the executor on which callback will be invoked.
2729 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002730 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002731 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002732 * @hide
2733 */
2734 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002735 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002736 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2737 public void registerTetheringEventCallback(
2738 @NonNull @CallbackExecutor Executor executor,
2739 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002740 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchien4ef53e82019-02-27 14:56:11 +08002741
markchien6ae63e52020-01-21 13:11:06 +08002742 final TetheringEventCallback tetherCallback =
2743 new TetheringEventCallback() {
2744 @Override
2745 public void onUpstreamChanged(@Nullable Network network) {
2746 callback.onUpstreamChanged(network);
2747 }
2748 };
2749
2750 synchronized (mTetheringEventCallbacks) {
2751 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002752 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002753 }
markchien4ef53e82019-02-27 14:56:11 +08002754 }
2755
2756 /**
2757 * Remove tethering event callback previously registered with
2758 * {@link #registerTetheringEventCallback}.
2759 *
2760 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002761 *
2762 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002763 * @hide
2764 */
2765 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002766 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002767 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2768 public void unregisterTetheringEventCallback(
2769 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002770 Objects.requireNonNull(callback, "The callback must be non-null");
2771 synchronized (mTetheringEventCallbacks) {
2772 final TetheringEventCallback tetherCallback =
2773 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002774 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002775 }
markchien4ef53e82019-02-27 14:56:11 +08002776 }
2777
2778
2779 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002780 * Get the list of regular expressions that define any tetherable
2781 * USB network interfaces. If USB tethering is not supported by the
2782 * device, this list should be empty.
2783 *
2784 * @return an array of 0 or more regular expression Strings defining
2785 * what interfaces are considered tetherable usb interfaces.
2786 *
markchien6ae63e52020-01-21 13:11:06 +08002787 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002788 * {@hide}
2789 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002790 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002791 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002792 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002793 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002794 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002795 }
2796
2797 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002798 * Get the list of regular expressions that define any tetherable
2799 * Wifi network interfaces. If Wifi tethering is not supported by the
2800 * device, this list should be empty.
2801 *
2802 * @return an array of 0 or more regular expression Strings defining
2803 * what interfaces are considered tetherable wifi interfaces.
2804 *
markchien6ae63e52020-01-21 13:11:06 +08002805 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002806 * {@hide}
2807 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002808 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002809 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002810 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002811 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002812 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002813 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002814
Danica Chang96567052010-08-11 14:54:43 -07002815 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002816 * Get the list of regular expressions that define any tetherable
2817 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2818 * device, this list should be empty.
2819 *
2820 * @return an array of 0 or more regular expression Strings defining
2821 * what interfaces are considered tetherable bluetooth interfaces.
2822 *
markchien6ae63e52020-01-21 13:11:06 +08002823 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2824 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002825 * {@hide}
2826 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002827 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002828 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002829 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002830 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002831 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002832 }
2833
Mike Lockwooded4a1742011-07-19 13:04:47 -07002834 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002835 * Attempt to both alter the mode of USB and Tethering of USB. A
2836 * utility method to deal with some of the complexity of USB - will
2837 * attempt to switch to Rndis and subsequently tether the resulting
2838 * interface on {@code true} or turn off tethering and switch off
2839 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002840 *
2841 * <p>This method requires the caller to hold either the
2842 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2843 * or the ability to modify system settings as determined by
2844 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002845 *
2846 * @param enable a boolean - {@code true} to enable tethering
2847 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002848 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002849 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002850 * {@hide}
2851 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002852 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002853 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002854 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002855 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002856 }
2857
markchien6ae63e52020-01-21 13:11:06 +08002858 /**
2859 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2860 * {@hide}
2861 */
markchien0f45bb92019-01-16 17:44:13 +08002862 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002863 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002864 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002865 /**
2866 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2867 * {@hide}
2868 */
2869 @Deprecated
2870 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2871 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2872 /**
2873 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2874 * {@hide}
2875 */
2876 @Deprecated
2877 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2878 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2879 /**
2880 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2881 * {@hide}
2882 */
2883 @Deprecated
2884 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2885 /**
2886 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2887 * {@hide}
2888 */
2889 @Deprecated
2890 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2891 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2892 /**
markchienf47d8342020-03-19 13:37:43 +08002893 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002894 * {@hide}
2895 */
2896 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002897 public static final int TETHER_ERROR_MASTER_ERROR =
2898 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002899 /**
2900 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2901 * {@hide}
2902 */
2903 @Deprecated
2904 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2905 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2906 /**
2907 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2908 * {@hide}
2909 */
2910 @Deprecated
2911 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2912 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2913 /**
markchienf47d8342020-03-19 13:37:43 +08002914 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002915 * {@hide}
2916 */
2917 @Deprecated
2918 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002919 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002920 /**
markchienf47d8342020-03-19 13:37:43 +08002921 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002922 * {@hide}
2923 */
2924 @Deprecated
2925 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002926 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002927 /**
2928 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2929 * {@hide}
2930 */
2931 @Deprecated
2932 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2933 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2934 /**
markchienf47d8342020-03-19 13:37:43 +08002935 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002936 * {@hide}
2937 */
markchien0f45bb92019-01-16 17:44:13 +08002938 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002939 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002940 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002941 /**
2942 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2943 * {@hide}
2944 */
2945 @Deprecated
2946 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2947 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2948 /**
2949 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2950 * {@hide}
2951 */
markchien0f45bb92019-01-16 17:44:13 +08002952 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002953 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002954 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002955
2956 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002957 * Get a more detailed error code after a Tethering or Untethering
2958 * request asynchronously failed.
2959 *
2960 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002961 * @return error The error code of the last error tethering or untethering the named
2962 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002963 *
markchien6ae63e52020-01-21 13:11:06 +08002964 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002965 * {@hide}
2966 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002967 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002968 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002969 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002970 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002971 int error = mTetheringManager.getLastTetherError(iface);
2972 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2973 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2974 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2975 // instead.
2976 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2977 }
2978 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002979 }
2980
markchienbf5ab012019-03-06 16:25:00 +08002981 /** @hide */
2982 @Retention(RetentionPolicy.SOURCE)
2983 @IntDef(value = {
2984 TETHER_ERROR_NO_ERROR,
2985 TETHER_ERROR_PROVISION_FAILED,
2986 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2987 })
2988 public @interface EntitlementResultCode {
2989 }
2990
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002991 /**
markchienbf5ab012019-03-06 16:25:00 +08002992 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002993 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002994 *
2995 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002996 * @hide
2997 */
2998 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002999 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08003000 public interface OnTetheringEntitlementResultListener {
3001 /**
3002 * Called to notify entitlement result.
3003 *
3004 * @param resultCode an int value of entitlement result. It may be one of
3005 * {@link #TETHER_ERROR_NO_ERROR},
3006 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3007 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3008 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07003009 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08003010 }
3011
3012 /**
markchien0f45bb92019-01-16 17:44:13 +08003013 * Get the last value of the entitlement check on this downstream. If the cached value is
3014 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3015 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3016 * guaranteed that the UI-based entitlement check will complete in any specific time period
3017 * and may in fact never complete. Any successful entitlement check the platform performs for
3018 * any reason will update the cached value.
3019 *
3020 * @param type the downstream type of tethering. Must be one of
3021 * {@link #TETHERING_WIFI},
3022 * {@link #TETHERING_USB}, or
3023 * {@link #TETHERING_BLUETOOTH}.
3024 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08003025 * @param executor the executor on which callback will be invoked.
3026 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3027 * notify the caller of the result of entitlement check. The listener may be called zero
3028 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08003029 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08003030 * {@hide}
3031 */
3032 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08003033 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08003034 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08003035 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3036 @NonNull @CallbackExecutor Executor executor,
3037 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003038 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchienbf5ab012019-03-06 16:25:00 +08003039 ResultReceiver wrappedListener = new ResultReceiver(null) {
3040 @Override
3041 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08003042 final long token = Binder.clearCallingIdentity();
3043 try {
3044 executor.execute(() -> {
3045 listener.onTetheringEntitlementResult(resultCode);
3046 });
3047 } finally {
3048 Binder.restoreCallingIdentity(token);
3049 }
markchienbf5ab012019-03-06 16:25:00 +08003050 }
3051 };
3052
Amos Bianchia9b415a2020-03-04 11:07:38 -08003053 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08003054 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08003055 }
3056
3057 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003058 * Report network connectivity status. This is currently used only
3059 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003060 * <p>This method requires the caller to hold the permission
3061 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003062 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003063 * @param networkType The type of network you want to report on
3064 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003065 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003066 * {@hide}
3067 */
3068 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003069 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003070 try {
3071 mService.reportInetCondition(networkType, percentage);
3072 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003073 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003074 }
3075 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003076
3077 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003078 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003079 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003080 * the framework to re-evaluate network connectivity and/or switch to another
3081 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003082 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003083 * @param network The {@link Network} the application was attempting to use
3084 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003085 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3086 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003087 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003088 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003089 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003090 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003091 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003092 // One of these will be ignored because it matches system's current state.
3093 // The other will trigger the necessary reevaluation.
3094 mService.reportNetworkConnectivity(network, true);
3095 mService.reportNetworkConnectivity(network, false);
3096 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003097 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003098 }
3099 }
3100
3101 /**
3102 * Report to the framework whether a network has working connectivity.
3103 * This provides a hint to the system that a particular network is providing
3104 * working connectivity or not. In response the framework may re-evaluate
3105 * the network's connectivity and might take further action thereafter.
3106 *
3107 * @param network The {@link Network} the application was attempting to use
3108 * or {@code null} to indicate the current default network.
3109 * @param hasConnectivity {@code true} if the application was able to successfully access the
3110 * Internet using {@code network} or {@code false} if not.
3111 */
Chalard Jean158702d2019-01-07 19:26:34 +09003112 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003113 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003114 try {
3115 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003116 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003117 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003118 }
3119 }
3120
3121 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003122 * Set a network-independent global http proxy. This is not normally what you want
3123 * for typical HTTP proxies - they are general network dependent. However if you're
3124 * doing something unusual like general internal filtering this may be useful. On
3125 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003126 *
3127 * @param p A {@link ProxyInfo} object defining the new global
3128 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003129 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003130 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003131 @SystemApi(client = MODULE_LIBRARIES)
paulhu8e96a752019-08-12 16:25:11 +08003132 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang4d513572021-03-18 09:44:34 +08003133 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003134 try {
3135 mService.setGlobalProxy(p);
3136 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003137 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003138 }
3139 }
3140
3141 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003142 * Retrieve any network-independent global HTTP proxy.
3143 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003144 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003145 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003146 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003147 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003148 @SystemApi(client = MODULE_LIBRARIES)
3149 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04003150 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003151 try {
3152 return mService.getGlobalProxy();
3153 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003154 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003155 }
3156 }
3157
3158 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003159 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3160 * network-specific HTTP proxy. If {@code network} is null, the
3161 * network-specific proxy returned is the proxy of the default active
3162 * network.
3163 *
3164 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3165 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3166 * or when {@code network} is {@code null},
3167 * the {@code ProxyInfo} for the default active network. Returns
3168 * {@code null} when no proxy applies or the caller doesn't have
3169 * permission to use {@code network}.
3170 * @hide
3171 */
3172 public ProxyInfo getProxyForNetwork(Network network) {
3173 try {
3174 return mService.getProxyForNetwork(network);
3175 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003176 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003177 }
3178 }
3179
3180 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003181 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3182 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003183 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003184 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003185 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003186 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003187 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003188 */
Chalard Jean158702d2019-01-07 19:26:34 +09003189 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003190 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003191 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003192 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003193
3194 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003195 * Returns true if the hardware supports the given network type
3196 * else it returns false. This doesn't indicate we have coverage
3197 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003198 * hardware supports it. For example a GSM phone without a SIM
3199 * should still return {@code true} for mobile data, but a wifi only
3200 * tablet would return {@code false}.
3201 *
3202 * @param networkType The network type we'd like to check
3203 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003204 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003205 * @hide
3206 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003207 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003208 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003209 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003210 public boolean isNetworkSupported(int networkType) {
3211 try {
3212 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003213 } catch (RemoteException e) {
3214 throw e.rethrowFromSystemServer();
3215 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003216 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003217
3218 /**
3219 * Returns if the currently active data network is metered. A network is
3220 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003221 * that connection due to monetary costs, data limitations or
3222 * battery/performance issues. You should check this before doing large
3223 * data transfers, and warn the user or delay the operation until another
3224 * network is available.
3225 *
3226 * @return {@code true} if large transfers should be avoided, otherwise
3227 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003228 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003229 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003230 public boolean isActiveNetworkMetered() {
3231 try {
3232 return mService.isActiveNetworkMetered();
3233 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003234 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003235 }
3236 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003237
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003238 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003239 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003240 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003241 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003242 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003243 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003244 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003245 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003246 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003247 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003248 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003249 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003250 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003251 }
3252 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003253
3254 /**
3255 * Set the value for enabling/disabling airplane mode
3256 *
3257 * @param enable whether to enable airplane mode or not
3258 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003259 * @hide
3260 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003261 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003262 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003263 android.Manifest.permission.NETWORK_SETTINGS,
3264 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3265 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003266 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003267 public void setAirplaneMode(boolean enable) {
3268 try {
3269 mService.setAirplaneMode(enable);
3270 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003271 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003272 }
3273 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003274
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003275 /**
3276 * Registers the specified {@link NetworkProvider}.
3277 * Each listener must only be registered once. The listener can be unregistered with
3278 * {@link #unregisterNetworkProvider}.
3279 *
3280 * @param provider the provider to register
3281 * @return the ID of the provider. This ID must be used by the provider when registering
3282 * {@link android.net.NetworkAgent}s.
3283 * @hide
3284 */
3285 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003286 @RequiresPermission(anyOf = {
3287 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3288 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003289 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3290 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003291 throw new IllegalStateException("NetworkProviders can only be registered once");
3292 }
3293
3294 try {
3295 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3296 provider.getName());
3297 provider.setProviderId(providerId);
3298 } catch (RemoteException e) {
3299 throw e.rethrowFromSystemServer();
3300 }
3301 return provider.getProviderId();
3302 }
3303
3304 /**
3305 * Unregisters the specified NetworkProvider.
3306 *
3307 * @param provider the provider to unregister
3308 * @hide
3309 */
3310 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003311 @RequiresPermission(anyOf = {
3312 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3313 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003314 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3315 try {
3316 mService.unregisterNetworkProvider(provider.getMessenger());
3317 } catch (RemoteException e) {
3318 throw e.rethrowFromSystemServer();
3319 }
3320 provider.setProviderId(NetworkProvider.ID_NONE);
3321 }
3322
3323
3324 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003325 @RequiresPermission(anyOf = {
3326 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3327 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003328 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3329 try {
3330 mService.declareNetworkRequestUnfulfillable(request);
3331 } catch (RemoteException e) {
3332 throw e.rethrowFromSystemServer();
3333 }
3334 }
3335
Paul Jensen1f567382015-02-13 14:18:39 -05003336 /**
3337 * @hide
3338 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003339 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003340 */
paulhub6ba8e82020-03-04 09:43:41 +08003341 @RequiresPermission(anyOf = {
3342 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3343 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003344 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jean28018572020-12-21 18:36:52 +09003345 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3346 int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003347 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003348 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003349 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003350 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003351 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003352 }
3353
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003354 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003355 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3356 * changes. Should be extended by applications wanting notifications.
3357 *
3358 * A {@code NetworkCallback} is registered by calling
3359 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3360 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003361 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003362 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3363 * A {@code NetworkCallback} should be registered at most once at any time.
3364 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003365 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003366 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003367 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003368 * No flags associated with this callback.
3369 * @hide
3370 */
3371 public static final int FLAG_NONE = 0;
3372 /**
3373 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3374 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3375 * <p>
3376 * These include:
3377 * <li> Some transport info instances (retrieved via
3378 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3379 * contain location sensitive information.
3380 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3381 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3382 * </p>
3383 * <p>
3384 * Note:
3385 * <li> Retrieving this location sensitive information (subject to app's location
3386 * permissions) will be noted by system. </li>
3387 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3388 * not include location sensitive info.
3389 * </p>
3390 */
3391 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3392
3393 /** @hide */
3394 @Retention(RetentionPolicy.SOURCE)
3395 @IntDef(flag = true, prefix = "FLAG_", value = {
3396 FLAG_NONE,
3397 FLAG_INCLUDE_LOCATION_INFO
3398 })
3399 public @interface Flag { }
3400
3401 /**
3402 * All the valid flags for error checking.
3403 */
3404 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3405
3406 public NetworkCallback() {
3407 this(FLAG_NONE);
3408 }
3409
3410 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003411 if ((flags & VALID_FLAGS) != flags) {
3412 throw new IllegalArgumentException("Invalid flags");
3413 }
Roshan Pius951c0032020-12-22 15:10:42 -08003414 mFlags = flags;
3415 }
3416
3417 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003418 * Called when the framework connects to a new network to evaluate whether it satisfies this
3419 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3420 * callback. There is no guarantee that this new network will satisfy any requests, or that
3421 * the network will stay connected for longer than the time necessary to evaluate it.
3422 * <p>
3423 * Most applications <b>should not</b> act on this callback, and should instead use
3424 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3425 * the framework in properly evaluating the network &mdash; for example, an application that
3426 * can automatically log in to a captive portal without user intervention.
3427 *
3428 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003429 *
3430 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003431 */
paulhu1a407652019-03-22 16:35:06 +08003432 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003433
3434 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003435 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003436 * This callback may be called more than once if the {@link Network} that is
3437 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003438 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003439 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003440 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3441 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003442 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003443 * @hide
3444 */
paulhu1a407652019-03-22 16:35:06 +08003445 public void onAvailable(@NonNull Network network,
3446 @NonNull NetworkCapabilities networkCapabilities,
3447 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003448 // Internally only this method is called when a new network is available, and
3449 // it calls the callback in the same way and order that older versions used
3450 // to call so as not to change the behavior.
3451 onAvailable(network);
3452 if (!networkCapabilities.hasCapability(
3453 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3454 onNetworkSuspended(network);
3455 }
3456 onCapabilitiesChanged(network, networkCapabilities);
3457 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003458 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003459 }
3460
3461 /**
3462 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003463 *
3464 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3465 * be available at the same time, and onAvailable will be called for each of these as they
3466 * appear.
3467 *
3468 * <p>For callbacks registered with {@link #requestNetwork} and
3469 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3470 * is the new best network for this request and is now tracked by this callback ; this
3471 * callback will no longer receive method calls about other networks that may have been
3472 * passed to this method previously. The previously-best network may have disconnected, or
3473 * it may still be around and the newly-best network may simply be better.
3474 *
3475 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3476 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3477 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3478 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3479 *
3480 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3481 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3482 * this callback as this is prone to race conditions (there is no guarantee the objects
3483 * returned by these methods will be current). Instead, wait for a call to
3484 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3485 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3486 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003487 *
3488 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003489 */
paulhu1a407652019-03-22 16:35:06 +08003490 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003491
3492 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003493 * Called when the network is about to be lost, typically because there are no outstanding
3494 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3495 * with the new replacement network for graceful handover. This method is not guaranteed
3496 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3497 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003498 *
Chalard Jean01378b62019-08-30 16:27:28 +09003499 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3500 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3501 * this callback as this is prone to race conditions ; calling these methods while in a
3502 * callback may return an outdated or even a null object.
3503 *
3504 * @param network The {@link Network} that is about to be lost.
3505 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3506 * connected for graceful handover; note that the network may still
3507 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003508 */
paulhu1a407652019-03-22 16:35:06 +08003509 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003510
3511 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003512 * Called when a network disconnects or otherwise no longer satisfies this request or
3513 * callback.
3514 *
3515 * <p>If the callback was registered with requestNetwork() or
3516 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3517 * returned by onAvailable() when that network is lost and no other network satisfies
3518 * the criteria of the request.
3519 *
3520 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3521 * each network which no longer satisfies the criteria of the callback.
3522 *
3523 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3524 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3525 * this callback as this is prone to race conditions ; calling these methods while in a
3526 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003527 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003528 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003529 */
paulhu1a407652019-03-22 16:35:06 +08003530 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003531
3532 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003533 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003534 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3535 * requested network request cannot be fulfilled (whether or not a timeout was
3536 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003537 * {@link NetworkRequest} will have already been removed and released, as if
3538 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003539 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003540 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003541
3542 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003543 * Called when the network corresponding to this request changes capabilities but still
3544 * satisfies the requested criteria.
3545 *
3546 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3547 * to be called immediately after {@link #onAvailable}.
3548 *
3549 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3550 * ConnectivityManager methods in this callback as this is prone to race conditions :
3551 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003552 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003553 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius951c0032020-12-22 15:10:42 -08003554 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003555 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003556 */
paulhu1a407652019-03-22 16:35:06 +08003557 public void onCapabilitiesChanged(@NonNull Network network,
3558 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003559
3560 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003561 * Called when the network corresponding to this request changes {@link LinkProperties}.
3562 *
3563 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3564 * to be called immediately after {@link #onAvailable}.
3565 *
3566 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3567 * ConnectivityManager methods in this callback as this is prone to race conditions :
3568 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003569 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003570 * @param network The {@link Network} whose link properties have changed.
3571 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003572 */
paulhu1a407652019-03-22 16:35:06 +08003573 public void onLinkPropertiesChanged(@NonNull Network network,
3574 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003575
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003576 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003577 * Called when the network the framework connected to for this request suspends data
3578 * transmission temporarily.
3579 *
3580 * <p>This generally means that while the TCP connections are still live temporarily
3581 * network data fails to transfer. To give a specific example, this is used on cellular
3582 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3583 * means read operations on sockets on this network will block once the buffers are
3584 * drained, and write operations will block once the buffers are full.
3585 *
3586 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3587 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3588 * this callback as this is prone to race conditions (there is no guarantee the objects
3589 * returned by these methods will be current).
3590 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003591 * @hide
3592 */
paulhu1a407652019-03-22 16:35:06 +08003593 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003594
3595 /**
3596 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003597 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3598 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003599
3600 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3601 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3602 * this callback as this is prone to race conditions : calling these methods while in a
3603 * callback may return an outdated or even a null object.
3604 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003605 * @hide
3606 */
paulhu1a407652019-03-22 16:35:06 +08003607 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003608
junyulaif2c67e42018-08-07 19:50:45 +08003609 /**
3610 * Called when access to the specified network is blocked or unblocked.
3611 *
Chalard Jean01378b62019-08-30 16:27:28 +09003612 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3613 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3614 * this callback as this is prone to race conditions : calling these methods while in a
3615 * callback may return an outdated or even a null object.
3616 *
junyulaif2c67e42018-08-07 19:50:45 +08003617 * @param network The {@link Network} whose blocked status has changed.
3618 * @param blocked The blocked status of this {@link Network}.
3619 */
junyulai7e06ad42019-03-04 22:45:36 +08003620 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003621
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003622 private NetworkRequest networkRequest;
Roshan Pius951c0032020-12-22 15:10:42 -08003623 private final int mFlags;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003624 }
3625
Hugo Benichia590ab82017-05-11 13:16:17 +09003626 /**
3627 * Constant error codes used by ConnectivityService to communicate about failures and errors
3628 * across a Binder boundary.
3629 * @hide
3630 */
3631 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003632 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003633 }
3634
3635 /** @hide */
3636 public static class TooManyRequestsException extends RuntimeException {}
3637
3638 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3639 switch (e.errorCode) {
3640 case Errors.TOO_MANY_REQUESTS:
3641 return new TooManyRequestsException();
3642 default:
3643 Log.w(TAG, "Unknown service error code " + e.errorCode);
3644 return new RuntimeException(e);
3645 }
3646 }
3647
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003648 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003649 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003650 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003651 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003652 /** @hide arg1 = TTL */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003653 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003654 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003655 public static final int CALLBACK_LOST = 4;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003656 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003657 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003658 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003659 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003660 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003661 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003662 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003663 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003664 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003665 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003666 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003667 public static final int CALLBACK_RESUMED = 10;
junyulaif2c67e42018-08-07 19:50:45 +08003668 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003669 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003670
Erik Kline155a59a2015-11-25 12:49:38 +09003671 /** @hide */
3672 public static String getCallbackName(int whichCallback) {
3673 switch (whichCallback) {
3674 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3675 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3676 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3677 case CALLBACK_LOST: return "CALLBACK_LOST";
3678 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3679 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3680 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003681 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3682 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3683 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003684 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003685 default:
3686 return Integer.toString(whichCallback);
3687 }
3688 }
3689
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003690 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003691 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003692 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003693
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003694 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003695 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003696 }
3697
Hugo Benichifd44e912017-02-02 17:02:36 +09003698 CallbackHandler(Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003699 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003700 }
3701
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003702 @Override
3703 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003704 if (message.what == EXPIRE_LEGACY_REQUEST) {
3705 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3706 return;
3707 }
3708
3709 final NetworkRequest request = getObject(message, NetworkRequest.class);
3710 final Network network = getObject(message, Network.class);
3711 final NetworkCallback callback;
3712 synchronized (sCallbacks) {
3713 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003714 if (callback == null) {
3715 Log.w(TAG,
3716 "callback not found for " + getCallbackName(message.what) + " message");
3717 return;
3718 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003719 if (message.what == CALLBACK_UNAVAIL) {
3720 sCallbacks.remove(request);
3721 callback.networkRequest = ALREADY_UNREGISTERED;
3722 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003723 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003724 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003725 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003726 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003727
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003728 switch (message.what) {
3729 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003730 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003731 break;
3732 }
3733 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003734 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3735 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003736 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003737 break;
3738 }
3739 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003740 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003741 break;
3742 }
3743 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003744 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003745 break;
3746 }
3747 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003748 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003749 break;
3750 }
3751 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003752 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3753 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003754 break;
3755 }
3756 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003757 LinkProperties lp = getObject(message, LinkProperties.class);
3758 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003759 break;
3760 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003761 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003762 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003763 break;
3764 }
3765 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003766 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003767 break;
3768 }
junyulaif2c67e42018-08-07 19:50:45 +08003769 case CALLBACK_BLK_CHANGED: {
3770 boolean blocked = message.arg1 != 0;
3771 callback.onBlockedStatusChanged(network, blocked);
3772 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003773 }
3774 }
3775
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003776 private <T> T getObject(Message msg, Class<T> c) {
3777 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003778 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003779 }
3780
Hugo Benichifd44e912017-02-02 17:02:36 +09003781 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003782 synchronized (sCallbacks) {
3783 if (sCallbackHandler == null) {
3784 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003785 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003786 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003787 }
3788 }
3789
Hugo Benichibc4ac972017-02-03 14:18:44 +09003790 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3791 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003792
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003793 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3794 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3795 CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003796 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003797 checkCallbackNotNull(callback);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003798 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3799 throw new IllegalArgumentException("null NetworkCapabilities");
3800 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003801 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003802 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003803 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003804 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003805 if (callback.networkRequest != null
3806 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003807 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3808 // and requests (http://b/20701525).
3809 Log.e(TAG, "NetworkCallback was already registered");
3810 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003811 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003812 Binder binder = new Binder();
Roshan Pius951c0032020-12-22 15:10:42 -08003813 final int callbackFlags = callback.mFlags;
junyulaiad010792021-01-11 16:53:38 +08003814 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003815 request = mService.listenForNetwork(
Roshan Pius951c0032020-12-22 15:10:42 -08003816 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003817 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003818 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003819 request = mService.requestNetwork(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003820 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3821 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003822 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003823 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003824 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003825 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003826 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003827 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003828 } catch (RemoteException e) {
3829 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003830 } catch (ServiceSpecificException e) {
3831 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003832 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003833 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003834 }
3835
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003836 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3837 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3838 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3839 legacyType, handler);
3840 }
3841
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003842 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003843 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003844 *
markchienfac84a22020-03-18 21:16:15 +08003845 * This API is only for use in internal system code that requests networks with legacy type and
3846 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003847 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003848 *
markchiend6eeffd2020-01-14 00:55:21 +08003849 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003850 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3851 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3852 * be a positive value (i.e. >0).
3853 * @param legacyType to specify the network type(#TYPE_*).
3854 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003855 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3856 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003857 *
3858 * @hide
3859 */
markchiend6eeffd2020-01-14 00:55:21 +08003860 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003861 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003862 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003863 int timeoutMs, int legacyType, @NonNull Handler handler,
3864 @NonNull NetworkCallback networkCallback) {
3865 if (legacyType == TYPE_NONE) {
3866 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3867 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003868 CallbackHandler cbHandler = new CallbackHandler(handler);
3869 NetworkCapabilities nc = request.networkCapabilities;
3870 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003871 }
3872
3873 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003874 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003875 *
Chalard Jean01378b62019-08-30 16:27:28 +09003876 * <p>This method will attempt to find the best network that matches the passed
3877 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3878 * criteria. The platform will evaluate which network is the best at its own discretion.
3879 * Throughput, latency, cost per byte, policy, user preference and other considerations
3880 * may be factored in the decision of what is considered the best network.
3881 *
3882 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3883 * matching this request, while always attempting to match the request to a better network if
3884 * possible. If a better match is found, the platform will switch this request to the now-best
3885 * network and inform the app of the newly best network by invoking
3886 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3887 * will not try to maintain any other network than the best one currently matching the request:
3888 * a network not matching any network request may be disconnected at any time.
3889 *
3890 * <p>For example, an application could use this method to obtain a connected cellular network
3891 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3892 * radio to consume additional power. Or, an application could inform the system that it wants
3893 * a network supporting sending MMSes and have the system let it know about the currently best
3894 * MMS-supporting network through the provided {@link NetworkCallback}.
3895 *
3896 * <p>The status of the request can be followed by listening to the various callbacks described
3897 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3898 * used to direct traffic to the network (although accessing some networks may be subject to
3899 * holding specific permissions). Callers will learn about the specific characteristics of the
3900 * network through
3901 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3902 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3903 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3904 * matching the request at any given time; therefore when a better network matching the request
3905 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3906 * with the new network after which no further updates are given about the previously-best
3907 * network, unless it becomes the best again at some later time. All callbacks are invoked
3908 * in order on the same thread, which by default is a thread created by the framework running
3909 * in the app.
3910 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3911 * callbacks are invoked.
3912 *
3913 * <p>This{@link NetworkRequest} will live until released via
3914 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3915 * which point the system may let go of the network at any time.
3916 *
3917 * <p>A version of this method which takes a timeout is
3918 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3919 * wait for a limited amount of time for the network to become unavailable.
3920 *
Paul Jensenee52d232015-06-16 15:11:58 -04003921 * <p>It is presently unsupported to request a network with mutable
3922 * {@link NetworkCapabilities} such as
3923 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3924 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3925 * as these {@code NetworkCapabilities} represent states that a particular
3926 * network may never attain, and whether a network will attain these states
3927 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003928 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003929 *
3930 * <p>This method requires the caller to hold either the
3931 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3932 * or the ability to modify system settings as determined by
3933 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003934 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003935 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3936 * number of outstanding requests to 100 per app (identified by their UID), shared with
3937 * all variants of this method, of {@link #registerNetworkCallback} as well as
3938 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3939 * Requesting a network with this method will count toward this limit. If this limit is
3940 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3941 * make sure to unregister the callbacks with
3942 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3943 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003944 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003945 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3946 * the callback must not be shared - it uniquely specifies this request.
3947 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003948 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3949 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003950 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003951 */
Chalard Jean158702d2019-01-07 19:26:34 +09003952 public void requestNetwork(@NonNull NetworkRequest request,
3953 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003954 requestNetwork(request, networkCallback, getDefaultHandler());
3955 }
3956
3957 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003958 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichifd44e912017-02-02 17:02:36 +09003959 *
Chalard Jean01378b62019-08-30 16:27:28 +09003960 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3961 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003962 *
Chalard Jean01378b62019-08-30 16:27:28 +09003963 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003964 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3965 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003966 *
3967 * @param request {@link NetworkRequest} describing this request.
3968 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3969 * the callback must not be shared - it uniquely specifies this request.
3970 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003971 */
Chalard Jean158702d2019-01-07 19:26:34 +09003972 public void requestNetwork(@NonNull NetworkRequest request,
3973 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003974 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003975 NetworkCapabilities nc = request.networkCapabilities;
3976 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003977 }
3978
3979 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003980 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohenf67bde92017-03-01 12:47:28 -08003981 * by a timeout.
3982 *
3983 * This function behaves identically to the non-timed-out version
3984 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3985 * is not found within the given time (in milliseconds) the
3986 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3987 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3988 * not have to be released if timed-out (it is automatically released). Unregistering a
3989 * request that timed out is not an error.
3990 *
3991 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3992 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3993 * for that purpose. Calling this method will attempt to bring up the requested network.
3994 *
Chalard Jean01378b62019-08-30 16:27:28 +09003995 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003996 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3997 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003998 *
3999 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004000 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4001 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08004002 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4003 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4004 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08004005 */
Chalard Jean158702d2019-01-07 19:26:34 +09004006 public void requestNetwork(@NonNull NetworkRequest request,
4007 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09004008 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08004009 NetworkCapabilities nc = request.networkCapabilities;
4010 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4011 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09004012 }
4013
Hugo Benichifd44e912017-02-02 17:02:36 +09004014 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004015 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichifd44e912017-02-02 17:02:36 +09004016 * by a timeout.
4017 *
Chalard Jean01378b62019-08-30 16:27:28 +09004018 * This method behaves identically to
4019 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4020 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08004021 *
Chalard Jean01378b62019-08-30 16:27:28 +09004022 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004023 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4024 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09004025 *
4026 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08004027 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4028 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09004029 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004030 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4031 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004032 */
Chalard Jean158702d2019-01-07 19:26:34 +09004033 public void requestNetwork(@NonNull NetworkRequest request,
4034 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09004035 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09004036 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08004037 NetworkCapabilities nc = request.networkCapabilities;
4038 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004039 }
4040
4041 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004042 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004043 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004044 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08004045 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04004046 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4047 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004048 */
Erik Kline8a826212014-11-19 12:12:24 +09004049 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004050
4051 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004052 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004053 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004054 * {@link android.content.Intent#getParcelableExtra(String)}.
4055 */
Erik Kline8a826212014-11-19 12:12:24 +09004056 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004057
4058
4059 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004060 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004061 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004062 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004063 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004064 * the request may outlive the calling application and get called back when a suitable
4065 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004066 * <p>
4067 * The operation is an Intent broadcast that goes to a broadcast receiver that
4068 * you registered with {@link Context#registerReceiver} or through the
4069 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4070 * <p>
4071 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09004072 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4073 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004074 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004075 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004076 * Intent to reserve the network or it will be released shortly after the Intent
4077 * is processed.
4078 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04004079 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004080 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004081 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004082 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004083 * The request may be released normally by calling
4084 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04004085 * <p>It is presently unsupported to request a network with either
4086 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4087 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4088 * as these {@code NetworkCapabilities} represent states that a particular
4089 * network may never attain, and whether a network will attain these states
4090 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09004091 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004092 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004093 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4094 * number of outstanding requests to 100 per app (identified by their UID), shared with
4095 * all variants of this method, of {@link #registerNetworkCallback} as well as
4096 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4097 * Requesting a network with this method will count toward this limit. If this limit is
4098 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4099 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4100 * or {@link #releaseNetworkRequest(PendingIntent)}.
4101 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004102 * <p>This method requires the caller to hold either the
4103 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4104 * or the ability to modify system settings as determined by
4105 * {@link android.provider.Settings.System#canWrite}.</p>
4106 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004107 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004108 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004109 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004110 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004111 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4112 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004113 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004114 */
Chalard Jean158702d2019-01-07 19:26:34 +09004115 public void requestNetwork(@NonNull NetworkRequest request,
4116 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004117 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004118 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004119 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004120 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004121 request.networkCapabilities, operation, mContext.getOpPackageName(),
4122 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004123 } catch (RemoteException e) {
4124 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004125 } catch (ServiceSpecificException e) {
4126 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004127 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004128 }
4129
4130 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004131 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4132 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004133 * This method has the same behavior as
4134 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004135 * releasing network resources and disconnecting.
4136 *
4137 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4138 * PendingIntent passed to
4139 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4140 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4141 */
Chalard Jean158702d2019-01-07 19:26:34 +09004142 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004143 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004144 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004145 try {
4146 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004147 } catch (RemoteException e) {
4148 throw e.rethrowFromSystemServer();
4149 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004150 }
4151
Hugo Benichibc1104b2017-05-09 15:19:01 +09004152 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004153 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004154 }
4155
4156 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004157 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004158 }
4159
4160 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004161 if (timeoutMs <= 0) {
4162 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4163 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004164 }
4165
4166 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004167 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004168 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004169 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4170 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004171 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004172 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4173 * number of outstanding requests to 100 per app (identified by their UID), shared with
4174 * all variants of this method, of {@link #requestNetwork} as well as
4175 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4176 * Requesting a network with this method will count toward this limit. If this limit is
4177 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4178 * make sure to unregister the callbacks with
4179 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4180 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004181 * @param request {@link NetworkRequest} describing this request.
4182 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4183 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004184 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004185 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004186 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004187 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004188 public void registerNetworkCallback(@NonNull NetworkRequest request,
4189 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004190 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4191 }
4192
4193 /**
4194 * Registers to receive notifications about all networks which satisfy the given
4195 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004196 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4197 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004198 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004199 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4200 * number of outstanding requests to 100 per app (identified by their UID), shared with
4201 * all variants of this method, of {@link #requestNetwork} as well as
4202 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4203 * Requesting a network with this method will count toward this limit. If this limit is
4204 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4205 * make sure to unregister the callbacks with
4206 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4207 *
4208 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004209 * @param request {@link NetworkRequest} describing this request.
4210 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4211 * networks change state.
4212 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004213 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004214 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004215 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004216 public void registerNetworkCallback(@NonNull NetworkRequest request,
4217 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004218 CallbackHandler cbHandler = new CallbackHandler(handler);
4219 NetworkCapabilities nc = request.networkCapabilities;
4220 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004221 }
4222
4223 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004224 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4225 * {@link NetworkRequest}.
4226 *
4227 * This function behaves identically to the version that takes a NetworkCallback, but instead
4228 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4229 * the request may outlive the calling application and get called back when a suitable
4230 * network is found.
4231 * <p>
4232 * The operation is an Intent broadcast that goes to a broadcast receiver that
4233 * you registered with {@link Context#registerReceiver} or through the
4234 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4235 * <p>
4236 * The operation Intent is delivered with two extras, a {@link Network} typed
4237 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4238 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4239 * the original requests parameters.
4240 * <p>
4241 * If there is already a request for this Intent registered (with the equality of
4242 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4243 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4244 * <p>
4245 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004246 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004247 *
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 {@link #unregisterNetworkCallback(PendingIntent)}
4255 * or {@link #releaseNetworkRequest(PendingIntent)}.
4256 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004257 * @param request {@link NetworkRequest} describing this request.
4258 * @param operation Action to perform when the network is available (corresponds
4259 * to the {@link NetworkCallback#onAvailable} call. Typically
4260 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004261 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004262 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004263 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004264 public void registerNetworkCallback(@NonNull NetworkRequest request,
4265 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004266 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004267 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004268 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004269 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004270 request.networkCapabilities, operation, mContext.getOpPackageName(),
4271 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004272 } catch (RemoteException e) {
4273 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004274 } catch (ServiceSpecificException e) {
4275 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004276 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004277 }
4278
4279 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004280 * Registers to receive notifications about changes in the application's default network. This
4281 * may be a physical network or a virtual network, such as a VPN that applies to the
4282 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004283 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004284 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004285 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4286 * number of outstanding requests to 100 per app (identified by their UID), shared with
4287 * all variants of this method, of {@link #requestNetwork} as well as
4288 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4289 * Requesting a network with this method will count toward this limit. If this limit is
4290 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4291 * make sure to unregister the callbacks with
4292 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4293 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004294 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004295 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004296 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004297 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004298 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004299 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004300 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004301 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4302 }
4303
4304 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004305 * Registers to receive notifications about changes in the application's default network. This
4306 * may be a physical network or a virtual network, such as a VPN that applies to the
4307 * application. The callbacks will continue to be called until either the application exits or
4308 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4309 *
4310 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4311 * number of outstanding requests to 100 per app (identified by their UID), shared with
4312 * all variants of this method, of {@link #requestNetwork} as well as
4313 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4314 * Requesting a network with this method will count toward this limit. If this limit is
4315 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4316 * make sure to unregister the callbacks with
4317 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4318 *
4319 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4320 * application's default network changes.
4321 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4322 * @throws RuntimeException if the app already has too many callbacks registered.
4323 */
4324 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4325 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4326 @NonNull Handler handler) {
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004327 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4328 }
4329
4330 /**
4331 * Registers to receive notifications about changes in the default network for the specified
4332 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4333 * UID. The callbacks will continue to be called until either the application exits or
4334 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4335 *
4336 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4337 * number of outstanding requests to 100 per app (identified by their UID), shared with
4338 * all variants of this method, of {@link #requestNetwork} as well as
4339 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4340 * Requesting a network with this method will count toward this limit. If this limit is
4341 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4342 * make sure to unregister the callbacks with
4343 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4344 *
4345 * @param uid the UID for which to track default network changes.
4346 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4347 * UID's default network changes.
4348 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4349 * @throws RuntimeException if the app already has too many callbacks registered.
4350 * @hide
4351 */
Lorenzo Colitti92ed8b92021-03-22 18:23:21 +09004352 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004353 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4354 @RequiresPermission(anyOf = {
4355 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4356 android.Manifest.permission.NETWORK_SETTINGS})
4357 public void registerDefaultNetworkCallbackAsUid(int uid,
4358 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004359 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004360 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004361 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4362 }
4363
4364 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004365 * Registers to receive notifications about changes in the system default network. The callbacks
4366 * will continue to be called until either the application exits or
4367 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004368 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004369 * This method should not be used to determine networking state seen by applications, because in
4370 * many cases, most or even all application traffic may not use the default network directly,
4371 * and traffic from different applications may go on different networks by default. As an
4372 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4373 * and not onto the system default network. Applications or system components desiring to do
4374 * determine network state as seen by applications should use other methods such as
4375 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4376 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004377 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4378 * number of outstanding requests to 100 per app (identified by their UID), shared with
4379 * all variants of this method, of {@link #requestNetwork} as well as
4380 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4381 * Requesting a network with this method will count toward this limit. If this limit is
4382 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4383 * make sure to unregister the callbacks with
4384 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4385 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004386 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4387 * system default network changes.
4388 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004389 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004390 *
4391 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004392 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004393 @SystemApi(client = MODULE_LIBRARIES)
4394 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4395 @RequiresPermission(anyOf = {
4396 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4397 android.Manifest.permission.NETWORK_SETTINGS})
4398 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004399 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004400 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004401 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004402 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004403 }
4404
4405 /**
junyulai8eb13a22021-03-15 11:48:48 +08004406 * Registers to receive notifications about the best matching network which satisfy the given
4407 * {@link NetworkRequest}. The callbacks will continue to be called until
4408 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4409 * called.
4410 *
4411 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4412 * number of outstanding requests to 100 per app (identified by their UID), shared with
4413 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4414 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4415 * Requesting a network with this method will count toward this limit. If this limit is
4416 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4417 * make sure to unregister the callbacks with
4418 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4419 *
4420 *
4421 * @param request {@link NetworkRequest} describing this request.
4422 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4423 * networks change state.
4424 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4425 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai7514e312021-03-05 15:51:17 +08004426 */
junyulai7514e312021-03-05 15:51:17 +08004427 @SuppressLint("ExecutorRegistration")
4428 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4429 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4430 final NetworkCapabilities nc = request.networkCapabilities;
4431 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai1b1c8742021-03-12 20:05:08 +08004432 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai7514e312021-03-05 15:51:17 +08004433 }
4434
4435 /**
fenglub00f4882015-04-21 17:12:05 -07004436 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4437 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4438 * network connection for updated bandwidth information. The caller will be notified via
4439 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004440 * method assumes that the caller has previously called
4441 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4442 * changes.
fenglu3f357402015-03-20 11:29:56 -07004443 *
fengluea2d9282015-04-27 14:28:04 -07004444 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004445 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004446 */
Chalard Jean158702d2019-01-07 19:26:34 +09004447 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004448 try {
fenglub00f4882015-04-21 17:12:05 -07004449 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004450 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004451 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004452 }
4453 }
4454
4455 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004456 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004457 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4458 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4459 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004460 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4461 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004462 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004463 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4464 * triggering it as soon as this call returns.
4465 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004466 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004467 */
Chalard Jean158702d2019-01-07 19:26:34 +09004468 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004469 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004470 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004471 final List<NetworkRequest> reqs = new ArrayList<>();
4472 // Find all requests associated to this callback and stop callback triggers immediately.
4473 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4474 synchronized (sCallbacks) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004475 if (networkCallback.networkRequest == null) {
4476 throw new IllegalArgumentException("NetworkCallback was not registered");
4477 }
Etan Cohen6cb65992019-04-16 15:07:55 -07004478 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4479 Log.d(TAG, "NetworkCallback was already unregistered");
4480 return;
4481 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004482 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4483 if (e.getValue() == networkCallback) {
4484 reqs.add(e.getKey());
4485 }
4486 }
4487 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4488 for (NetworkRequest r : reqs) {
4489 try {
4490 mService.releaseNetworkRequest(r);
4491 } catch (RemoteException e) {
4492 throw e.rethrowFromSystemServer();
4493 }
4494 // Only remove mapping if rpc was successful.
4495 sCallbacks.remove(r);
4496 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004497 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004498 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004499 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004500
4501 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004502 * Unregisters a callback previously registered via
4503 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4504 *
4505 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4506 * PendingIntent passed to
4507 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4508 * Cannot be null.
4509 */
Chalard Jean158702d2019-01-07 19:26:34 +09004510 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004511 releaseNetworkRequest(operation);
4512 }
4513
4514 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004515 * Informs the system whether it should switch to {@code network} regardless of whether it is
4516 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4517 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4518 * the system default network regardless of any other network that's currently connected. If
4519 * {@code always} is true, then the choice is remembered, so that the next time the user
4520 * connects to this network, the system will switch to it.
4521 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004522 * @param network The network to accept.
4523 * @param accept Whether to accept the network even if unvalidated.
4524 * @param always Whether to remember this choice in the future.
4525 *
4526 * @hide
4527 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004528 @SystemApi(client = MODULE_LIBRARIES)
4529 @RequiresPermission(anyOf = {
4530 android.Manifest.permission.NETWORK_SETTINGS,
4531 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4532 android.Manifest.permission.NETWORK_STACK,
4533 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4534 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004535 try {
4536 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004537 } catch (RemoteException e) {
4538 throw e.rethrowFromSystemServer();
4539 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004540 }
4541
4542 /**
lucaslin2240ef62019-03-12 13:08:03 +08004543 * Informs the system whether it should consider the network as validated even if it only has
4544 * partial connectivity. If {@code accept} is true, then the network will be considered as
4545 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4546 * is remembered, so that the next time the user connects to this network, the system will
4547 * switch to it.
4548 *
4549 * @param network The network to accept.
4550 * @param accept Whether to consider the network as validated even if it has partial
4551 * connectivity.
4552 * @param always Whether to remember this choice in the future.
4553 *
4554 * @hide
4555 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004556 @SystemApi(client = MODULE_LIBRARIES)
4557 @RequiresPermission(anyOf = {
4558 android.Manifest.permission.NETWORK_SETTINGS,
4559 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4560 android.Manifest.permission.NETWORK_STACK,
4561 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4562 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4563 boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004564 try {
4565 mService.setAcceptPartialConnectivity(network, accept, always);
4566 } catch (RemoteException e) {
4567 throw e.rethrowFromSystemServer();
4568 }
4569 }
4570
4571 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004572 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4573 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4574 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4575 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4576 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004577 * @param network The network to accept.
4578 *
4579 * @hide
4580 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004581 @SystemApi(client = MODULE_LIBRARIES)
4582 @RequiresPermission(anyOf = {
4583 android.Manifest.permission.NETWORK_SETTINGS,
4584 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4585 android.Manifest.permission.NETWORK_STACK,
4586 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4587 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004588 try {
4589 mService.setAvoidUnvalidated(network);
4590 } catch (RemoteException e) {
4591 throw e.rethrowFromSystemServer();
4592 }
4593 }
4594
4595 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004596 * Requests that the system open the captive portal app on the specified network.
4597 *
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004598 * <p>This is to be used on networks where a captive portal was detected, as per
4599 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4600 *
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004601 * @param network The network to log into.
4602 *
4603 * @hide
4604 */
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004605 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4606 @RequiresPermission(anyOf = {
4607 android.Manifest.permission.NETWORK_SETTINGS,
4608 android.Manifest.permission.NETWORK_STACK,
4609 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4610 })
4611 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004612 try {
4613 mService.startCaptivePortalApp(network);
4614 } catch (RemoteException e) {
4615 throw e.rethrowFromSystemServer();
4616 }
4617 }
4618
4619 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004620 * Requests that the system open the captive portal app with the specified extras.
4621 *
4622 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4623 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004624 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004625 * @param appExtras Extras to include in the app start intent.
4626 * @hide
4627 */
4628 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004629 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004630 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004631 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004632 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004633 } catch (RemoteException e) {
4634 throw e.rethrowFromSystemServer();
4635 }
4636 }
4637
4638 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004639 * Determine whether the device is configured to avoid bad wifi.
4640 * @hide
4641 */
4642 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004643 @RequiresPermission(anyOf = {
4644 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4645 android.Manifest.permission.NETWORK_STACK})
4646 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004647 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004648 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004649 } catch (RemoteException e) {
4650 throw e.rethrowFromSystemServer();
4651 }
4652 }
4653
4654 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004655 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4656 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004657 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4658 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004659 *
4660 * An example of such an operation might be a time-sensitive foreground activity, such as a
4661 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4662 */
4663 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4664
4665 /**
4666 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4667 * a backup channel for traffic that is primarily going over another network.
4668 *
4669 * An example might be maintaining backup connections to peers or servers for the purpose of
4670 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4671 * on backup paths should be negligible compared to the traffic on the main path.
4672 */
4673 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4674
4675 /**
4676 * It is acceptable to use metered data to improve network latency and performance.
4677 */
4678 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4679
4680 /**
4681 * Return value to use for unmetered networks. On such networks we currently set all the flags
4682 * to true.
4683 * @hide
4684 */
4685 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4686 MULTIPATH_PREFERENCE_HANDOVER |
4687 MULTIPATH_PREFERENCE_RELIABILITY |
4688 MULTIPATH_PREFERENCE_PERFORMANCE;
4689
4690 /** @hide */
4691 @Retention(RetentionPolicy.SOURCE)
4692 @IntDef(flag = true, value = {
4693 MULTIPATH_PREFERENCE_HANDOVER,
4694 MULTIPATH_PREFERENCE_RELIABILITY,
4695 MULTIPATH_PREFERENCE_PERFORMANCE,
4696 })
4697 public @interface MultipathPreference {
4698 }
4699
4700 /**
4701 * Provides a hint to the calling application on whether it is desirable to use the
4702 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4703 * for multipath data transfer on this network when it is not the system default network.
4704 * Applications desiring to use multipath network protocols should call this method before
4705 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004706 *
4707 * @param network The network on which the application desires to use multipath data.
4708 * If {@code null}, this method will return the a preference that will generally
4709 * apply to metered networks.
4710 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4711 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004712 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004713 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004714 try {
4715 return mService.getMultipathPreference(network);
4716 } catch (RemoteException e) {
4717 throw e.rethrowFromSystemServer();
4718 }
4719 }
4720
4721 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004722 * Resets all connectivity manager settings back to factory defaults.
4723 * @hide
4724 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004725 @SystemApi(client = MODULE_LIBRARIES)
4726 @RequiresPermission(anyOf = {
4727 android.Manifest.permission.NETWORK_SETTINGS,
4728 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scott0f835ac2015-03-30 13:17:11 -07004729 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004730 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004731 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004732 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004733 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004734 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004735 }
4736 }
4737
4738 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004739 * Binds the current process to {@code network}. All Sockets created in the future
4740 * (and not explicitly bound via a bound SocketFactory from
4741 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4742 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4743 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4744 * work and all host name resolutions will fail. This is by design so an application doesn't
4745 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4746 * To clear binding pass {@code null} for {@code network}. Using individually bound
4747 * Sockets created by Network.getSocketFactory().createSocket() and
4748 * performing network-specific host name resolutions via
4749 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004750 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004751 *
4752 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4753 * the current binding.
4754 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4755 */
Chalard Jean158702d2019-01-07 19:26:34 +09004756 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004757 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004758 // instantiated.
4759 return setProcessDefaultNetwork(network);
4760 }
4761
4762 /**
4763 * Binds the current process to {@code network}. All Sockets created in the future
4764 * (and not explicitly bound via a bound SocketFactory from
4765 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4766 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4767 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4768 * work and all host name resolutions will fail. This is by design so an application doesn't
4769 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4770 * To clear binding pass {@code null} for {@code network}. Using individually bound
4771 * Sockets created by Network.getSocketFactory().createSocket() and
4772 * performing network-specific host name resolutions via
4773 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4774 * {@code setProcessDefaultNetwork}.
4775 *
4776 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4777 * the current binding.
4778 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4779 * @deprecated This function can throw {@link IllegalStateException}. Use
4780 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4781 * is a direct replacement.
4782 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004783 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004784 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004785 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004786 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4787
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004788 if (netId != NETID_UNSET) {
4789 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004790 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004791
4792 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4793 return false;
4794 }
4795
4796 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004797 // Set HTTP proxy system properties to match network.
4798 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004799 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004800 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004801 } catch (SecurityException e) {
4802 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4803 Log.e(TAG, "Can't set proxy properties", e);
4804 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004805 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANe1b04f62021-03-18 23:27:19 +09004806 InetAddressCompat.clearDnsCache();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004807 // Must flush socket pool as idle sockets will be bound to previous network and may
4808 // cause subsequent fetches to be performed on old network.
4809 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004810 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004811
4812 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004813 }
4814
4815 /**
4816 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004817 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004818 *
4819 * @return {@code Network} to which this process is bound, or {@code null}.
4820 */
Chalard Jean158702d2019-01-07 19:26:34 +09004821 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004822 public Network getBoundNetworkForProcess() {
4823 // Forcing callers to call thru non-static function ensures ConnectivityManager
4824 // instantiated.
4825 return getProcessDefaultNetwork();
4826 }
4827
4828 /**
4829 * Returns the {@link Network} currently bound to this process via
4830 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4831 *
4832 * @return {@code Network} to which this process is bound, or {@code null}.
4833 * @deprecated Using this function can lead to other functions throwing
4834 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4835 * {@code getBoundNetworkForProcess} is a direct replacement.
4836 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004837 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004838 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004839 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004840 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004841 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004842 return new Network(netId);
4843 }
4844
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004845 private void unsupportedStartingFrom(int version) {
4846 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004847 // The getApplicationInfo() call we make below is not supported in system context. Let
4848 // the call through here, and rely on the fact that ConnectivityService will refuse to
4849 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004850 return;
4851 }
4852
4853 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4854 throw new UnsupportedOperationException(
4855 "This method is not supported in target SDK version " + version + " and above");
4856 }
4857 }
4858
4859 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4860 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004861 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004862 // remove these exemptions. Note that this check is not secure, and apps can still access these
4863 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4864 // so is unsupported and may break in the future. http://b/22728205
4865 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004866 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004867 }
4868
Paul Jensen8cdda642014-05-29 10:12:39 -04004869 /**
4870 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004871 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004872 *
4873 * @param network The {@link Network} to bind host resolutions from the current process to, or
4874 * {@code null} to clear the current binding.
4875 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4876 * @hide
4877 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4878 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004879 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004880 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004881 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004882 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004883 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004884 }
Felipe Leme30511352016-01-22 09:44:57 -08004885
4886 /**
4887 * Device is not restricting metered network activity while application is running on
4888 * background.
4889 */
4890 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4891
4892 /**
4893 * Device is restricting metered network activity while application is running on background,
4894 * but application is allowed to bypass it.
4895 * <p>
4896 * In this state, application should take action to mitigate metered network access.
4897 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4898 */
4899 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4900
4901 /**
4902 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004903 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004904 * In this state, application should not try to use the network while running on background,
4905 * because it would be denied.
4906 */
4907 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4908
Felipe Lemed34c9af2016-01-27 14:46:39 -08004909 /**
4910 * A change in the background metered network activity restriction has occurred.
4911 * <p>
4912 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4913 * applies to them.
4914 * <p>
4915 * This is only sent to registered receivers, not manifest receivers.
4916 */
4917 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4918 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4919 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4920
Felipe Leme7e4c1852016-01-25 11:48:04 -08004921 /** @hide */
4922 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004923 @IntDef(flag = false, value = {
4924 RESTRICT_BACKGROUND_STATUS_DISABLED,
4925 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4926 RESTRICT_BACKGROUND_STATUS_ENABLED,
4927 })
Felipe Leme30511352016-01-22 09:44:57 -08004928 public @interface RestrictBackgroundStatus {
4929 }
4930
Felipe Leme30511352016-01-22 09:44:57 -08004931 /**
4932 * Determines if the calling application is subject to metered network restrictions while
4933 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004934 *
4935 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4936 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4937 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004938 */
4939 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4940 try {
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004941 return mService.getRestrictBackgroundStatusByCaller();
Felipe Leme30511352016-01-22 09:44:57 -08004942 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004943 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004944 }
4945 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004946
4947 /**
4948 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004949 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4950 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004951 *
4952 * @return Hash of network watchlist config file. Null if config does not exist.
4953 */
Chalard Jean158702d2019-01-07 19:26:34 +09004954 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004955 public byte[] getNetworkWatchlistConfigHash() {
4956 try {
4957 return mService.getNetworkWatchlistConfigHash();
4958 } catch (RemoteException e) {
4959 Log.e(TAG, "Unable to get watchlist config hash");
4960 throw e.rethrowFromSystemServer();
4961 }
4962 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004963
4964 /**
4965 * Returns the {@code uid} of the owner of a network connection.
4966 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004967 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4968 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004969 * @param local The local {@link InetSocketAddress} of a connection.
4970 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004971 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004972 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4973 * android.os.Process#INVALID_UID} if the connection is not found.
4974 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4975 * user.
4976 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004977 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004978 public int getConnectionOwnerUid(
4979 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004980 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4981 try {
4982 return mService.getConnectionOwnerUid(connectionInfo);
4983 } catch (RemoteException e) {
4984 throw e.rethrowFromSystemServer();
4985 }
4986 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004987
4988 private void printStackTrace() {
4989 if (DEBUG) {
4990 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4991 final StringBuffer sb = new StringBuffer();
4992 for (int i = 3; i < callStack.length; i++) {
4993 final String stackTrace = callStack[i].toString();
4994 if (stackTrace == null || stackTrace.contains("android.os")) {
4995 break;
4996 }
4997 sb.append(" [").append(stackTrace).append("]");
4998 }
4999 Log.d(TAG, "StackLog:" + sb.toString());
5000 }
5001 }
Cody Kestingf53a0752020-04-15 12:33:28 -07005002
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09005003 /** @hide */
5004 public TestNetworkManager startOrGetTestNetworkManager() {
5005 final IBinder tnBinder;
5006 try {
5007 tnBinder = mService.startOrGetTestNetworkService();
5008 } catch (RemoteException e) {
5009 throw e.rethrowFromSystemServer();
5010 }
5011
5012 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5013 }
5014
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09005015 /** @hide */
5016 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5017 return new ConnectivityDiagnosticsManager(mContext, mService);
5018 }
5019
Cody Kestingf53a0752020-04-15 12:33:28 -07005020 /**
5021 * Simulates a Data Stall for the specified Network.
5022 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09005023 * <p>This method should only be used for tests.
5024 *
Cody Kestingf53a0752020-04-15 12:33:28 -07005025 * <p>The caller must be the owner of the specified Network.
5026 *
5027 * @param detectionMethod The detection method used to identify the Data Stall.
5028 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
5029 * @param network The Network for which a Data Stall is being simluated.
5030 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5031 * @throws SecurityException if the caller is not the owner of the given network.
5032 * @hide
5033 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09005034 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07005035 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5036 android.Manifest.permission.NETWORK_STACK})
5037 public void simulateDataStall(int detectionMethod, long timestampMillis,
5038 @NonNull Network network, @NonNull PersistableBundle extras) {
5039 try {
5040 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5041 } catch (RemoteException e) {
5042 e.rethrowFromSystemServer();
5043 }
5044 }
James Mattis356a8792020-10-28 21:48:54 -07005045
Daniel Brightf9e945b2020-06-15 16:10:01 -07005046 @NonNull
5047 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5048
5049 /**
5050 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5051 * receive available QoS events related to the {@link Network} and local ip + port
5052 * specified within socketInfo.
5053 * <p/>
5054 * The same {@link QosCallback} must be unregistered before being registered a second time,
5055 * otherwise {@link QosCallbackRegistrationException} is thrown.
5056 * <p/>
5057 * This API does not, in itself, require any permission if called with a network that is not
5058 * restricted. However, the underlying implementation currently only supports the IMS network,
5059 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5060 * useful, because they'd never be called back on networks that they would have access to.
5061 *
5062 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5063 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5064 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5065 * @throws RuntimeException if the app already has too many callbacks registered.
5066 *
5067 * Exceptions after the time of registration is passed through
5068 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5069 *
5070 * @param socketInfo the socket information used to match QoS events
Daniel Brightf9e945b2020-06-15 16:10:01 -07005071 * @param executor The executor on which the callback will be invoked. The provided
5072 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright7ee5f522021-03-10 11:51:50 -08005073 * callbacks cannot be guaranteed.onQosCallbackRegistered
5074 * @param callback receives qos events that satisfy socketInfo
Daniel Brightf9e945b2020-06-15 16:10:01 -07005075 *
5076 * @hide
5077 */
5078 @SystemApi
5079 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright7ee5f522021-03-10 11:51:50 -08005080 @CallbackExecutor @NonNull final Executor executor,
5081 @NonNull final QosCallback callback) {
Daniel Brightf9e945b2020-06-15 16:10:01 -07005082 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07005083 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright7ee5f522021-03-10 11:51:50 -08005084 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07005085
5086 try {
5087 synchronized (mQosCallbackConnections) {
5088 if (getQosCallbackConnection(callback) == null) {
5089 final QosCallbackConnection connection =
5090 new QosCallbackConnection(this, callback, executor);
5091 mQosCallbackConnections.add(connection);
5092 mService.registerQosSocketCallback(socketInfo, connection);
5093 } else {
5094 Log.e(TAG, "registerQosCallback: Callback already registered");
5095 throw new QosCallbackRegistrationException();
5096 }
5097 }
5098 } catch (final RemoteException e) {
5099 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5100
5101 // The same unregister method method is called for consistency even though nothing
5102 // will be sent to the ConnectivityService since the callback was never successfully
5103 // registered.
5104 unregisterQosCallback(callback);
5105 e.rethrowFromSystemServer();
5106 } catch (final ServiceSpecificException e) {
5107 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5108 unregisterQosCallback(callback);
5109 throw convertServiceException(e);
5110 }
5111 }
5112
5113 /**
5114 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5115 * events once unregistered and can be registered a second time.
5116 * <p/>
5117 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5118 *
5119 * @param callback the callback being unregistered
5120 *
5121 * @hide
5122 */
5123 @SystemApi
5124 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5125 Objects.requireNonNull(callback, "The callback must be non-null");
5126 try {
5127 synchronized (mQosCallbackConnections) {
5128 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5129 if (connection != null) {
5130 connection.stopReceivingMessages();
5131 mService.unregisterQosCallback(connection);
5132 mQosCallbackConnections.remove(connection);
5133 } else {
5134 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5135 }
5136 }
5137 } catch (final RemoteException e) {
5138 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5139 e.rethrowFromSystemServer();
5140 }
5141 }
5142
5143 /**
5144 * Gets the connection related to the callback.
5145 *
5146 * @param callback the callback to look up
5147 * @return the related connection
5148 */
5149 @Nullable
5150 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5151 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5152 // Checking by reference here is intentional
5153 if (connection.getCallback() == callback) {
5154 return connection;
5155 }
5156 }
5157 return null;
5158 }
Junyu Laia62493f2021-01-19 11:10:56 +00005159
5160 /**
Roshan Pius951c0032020-12-22 15:10:42 -08005161 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Laia62493f2021-01-19 11:10:56 +00005162 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5163 * be used to request that the system provide a network without causing the network to be
5164 * in the foreground.
5165 *
5166 * <p>This method will attempt to find the best network that matches the passed
5167 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5168 * criteria. The platform will evaluate which network is the best at its own discretion.
5169 * Throughput, latency, cost per byte, policy, user preference and other considerations
5170 * may be factored in the decision of what is considered the best network.
5171 *
5172 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5173 * matching this request, while always attempting to match the request to a better network if
5174 * possible. If a better match is found, the platform will switch this request to the now-best
5175 * network and inform the app of the newly best network by invoking
5176 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5177 * will not try to maintain any other network than the best one currently matching the request:
5178 * a network not matching any network request may be disconnected at any time.
5179 *
5180 * <p>For example, an application could use this method to obtain a connected cellular network
5181 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5182 * radio to consume additional power. Or, an application could inform the system that it wants
5183 * a network supporting sending MMSes and have the system let it know about the currently best
5184 * MMS-supporting network through the provided {@link NetworkCallback}.
5185 *
5186 * <p>The status of the request can be followed by listening to the various callbacks described
5187 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5188 * used to direct traffic to the network (although accessing some networks may be subject to
5189 * holding specific permissions). Callers will learn about the specific characteristics of the
5190 * network through
5191 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5192 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5193 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5194 * matching the request at any given time; therefore when a better network matching the request
5195 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5196 * with the new network after which no further updates are given about the previously-best
5197 * network, unless it becomes the best again at some later time. All callbacks are invoked
5198 * in order on the same thread, which by default is a thread created by the framework running
5199 * in the app.
5200 *
5201 * <p>This{@link NetworkRequest} will live until released via
5202 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5203 * which point the system may let go of the network at any time.
5204 *
5205 * <p>It is presently unsupported to request a network with mutable
5206 * {@link NetworkCapabilities} such as
5207 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5208 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5209 * as these {@code NetworkCapabilities} represent states that a particular
5210 * network may never attain, and whether a network will attain these states
5211 * is unknown prior to bringing up the network so the framework does not
5212 * know how to go about satisfying a request with these capabilities.
5213 *
5214 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5215 * number of outstanding requests to 100 per app (identified by their UID), shared with
5216 * all variants of this method, of {@link #registerNetworkCallback} as well as
5217 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5218 * Requesting a network with this method will count toward this limit. If this limit is
5219 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5220 * make sure to unregister the callbacks with
5221 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5222 *
5223 * @param request {@link NetworkRequest} describing this request.
5224 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5225 * If null, the callback is invoked on the default internal Handler.
5226 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5227 * the callback must not be shared - it uniquely specifies this request.
5228 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5229 * @throws SecurityException if missing the appropriate permissions.
5230 * @throws RuntimeException if the app already has too many callbacks registered.
5231 *
5232 * @hide
5233 */
5234 @SystemApi(client = MODULE_LIBRARIES)
5235 @SuppressLint("ExecutorRegistration")
5236 @RequiresPermission(anyOf = {
5237 android.Manifest.permission.NETWORK_SETTINGS,
5238 android.Manifest.permission.NETWORK_STACK,
5239 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5240 })
5241 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai962bdb82021-03-09 20:49:48 +08005242 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Laia62493f2021-01-19 11:10:56 +00005243 final NetworkCapabilities nc = request.networkCapabilities;
5244 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulai962bdb82021-03-09 20:49:48 +08005245 TYPE_NONE, new CallbackHandler(handler));
Junyu Laia62493f2021-01-19 11:10:56 +00005246 }
James Mattis45d81842021-01-10 14:24:24 -08005247
5248 /**
James Mattis45d81842021-01-10 14:24:24 -08005249 * Used by automotive devices to set the network preferences used to direct traffic at an
5250 * application level as per the given OemNetworkPreferences. An example use-case would be an
5251 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5252 * vehicle via a particular network.
5253 *
5254 * Calling this will overwrite the existing preference.
5255 *
5256 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5257 * @param executor the executor on which listener will be invoked.
5258 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5259 * communicate completion of setOemNetworkPreference(). This will only be
5260 * called once upon successful completion of setOemNetworkPreference().
5261 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5262 * @throws SecurityException if missing the appropriate permissions.
5263 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005264 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005265 */
James Mattisda32cfe2021-01-26 16:23:52 -08005266 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005267 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005268 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005269 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean6010c002021-03-03 16:37:13 +09005270 @Nullable final Runnable listener) {
James Mattis45d81842021-01-10 14:24:24 -08005271 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5272 if (null != listener) {
5273 Objects.requireNonNull(executor, "Executor must be non-null");
5274 }
Chalard Jean6010c002021-03-03 16:37:13 +09005275 final IOnCompleteListener listenerInternal = listener == null ? null :
5276 new IOnCompleteListener.Stub() {
James Mattis45d81842021-01-10 14:24:24 -08005277 @Override
5278 public void onComplete() {
Chalard Jean6010c002021-03-03 16:37:13 +09005279 executor.execute(listener::run);
James Mattis45d81842021-01-10 14:24:24 -08005280 }
5281 };
5282
5283 try {
5284 mService.setOemNetworkPreference(preference, listenerInternal);
5285 } catch (RemoteException e) {
5286 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5287 throw e.rethrowFromSystemServer();
5288 }
5289 }
lucaslin30e70a82021-03-12 00:46:33 +08005290
Chalard Jeanfa45a682021-02-25 17:23:40 +09005291 /**
5292 * Request that a user profile is put by default on a network matching a given preference.
5293 *
5294 * See the documentation for the individual preferences for a description of the supported
5295 * behaviors.
5296 *
5297 * @param profile the profile concerned.
5298 * @param preference the preference for this profile.
5299 * @param executor an executor to execute the listener on. Optional if listener is null.
5300 * @param listener an optional listener to listen for completion of the operation.
5301 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5302 * @throws SecurityException if missing the appropriate permissions.
5303 * @hide
5304 */
Chalard Jean6010c002021-03-03 16:37:13 +09005305 // This function is for establishing per-profile default networking and can only be called by
5306 // the device policy manager, running as the system server. It would make no sense to call it
5307 // on a context for a user because it does not establish a setting on behalf of a user, rather
5308 // it establishes a setting for a user on behalf of the DPM.
5309 @SuppressLint({"UserHandle"})
5310 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09005311 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5312 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5313 @ProfileNetworkPreference final int preference,
5314 @Nullable @CallbackExecutor final Executor executor,
5315 @Nullable final Runnable listener) {
5316 if (null != listener) {
5317 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5318 }
5319 final IOnCompleteListener proxy;
5320 if (null == listener) {
5321 proxy = null;
5322 } else {
5323 proxy = new IOnCompleteListener.Stub() {
5324 @Override
5325 public void onComplete() {
5326 executor.execute(listener::run);
5327 }
5328 };
5329 }
5330 try {
5331 mService.setProfileNetworkPreference(profile, preference, proxy);
5332 } catch (RemoteException e) {
5333 throw e.rethrowFromSystemServer();
5334 }
5335 }
5336
lucaslin30e70a82021-03-12 00:46:33 +08005337 // The first network ID of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005338 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin30e70a82021-03-12 00:46:33 +08005339 // The network ID range of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005340 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin30e70a82021-03-12 00:46:33 +08005341
5342 /**
5343 * Get the network ID range reserved for IPSec tunnel interfaces.
5344 *
5345 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5346 * @hide
5347 */
5348 @SystemApi(client = MODULE_LIBRARIES)
5349 @NonNull
5350 public static Range<Integer> getIpSecNetIdRange() {
5351 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5352 }
lucaslin705c3332021-03-12 17:56:09 +08005353
5354 /**
5355 * Get private DNS mode from settings.
5356 *
lucaslin7abe7e02021-03-17 14:53:35 +08005357 * @param context The Context to query the private DNS mode from settings.
lucaslin705c3332021-03-12 17:56:09 +08005358 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5359 *
5360 * @hide
5361 */
5362 @SystemApi(client = MODULE_LIBRARIES)
5363 @NonNull
5364 @PrivateDnsMode
lucaslin20f04882021-03-16 17:11:14 +08005365 public static String getPrivateDnsMode(@NonNull Context context) {
5366 final ContentResolver cr = context.getContentResolver();
lucaslin705c3332021-03-12 17:56:09 +08005367 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5368 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5369 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5370 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5371 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5372 return mode;
5373 }
paulhu89a762a2021-03-25 12:36:56 +08005374
5375 /**
5376 * Set private DNS mode to settings.
5377 *
5378 * @param context The {@link Context} to set the private DNS mode.
5379 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5380 *
5381 * @hide
5382 */
5383 @SystemApi(client = MODULE_LIBRARIES)
5384 public static void setPrivateDnsMode(@NonNull Context context,
5385 @NonNull @PrivateDnsMode String mode) {
5386 if (!(mode == PRIVATE_DNS_MODE_OFF
5387 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5388 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5389 throw new IllegalArgumentException("Invalid private dns mode");
5390 }
5391 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5392 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005393}