blob: 0a4d409c7d0fe0f2799aba1dd606f6b260ee2d18 [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 *
1213 * TODO: expose as @SystemApi.
1214 * @hide
1215 */
1216 @RequiresPermission(anyOf = {
1217 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1218 android.Manifest.permission.NETWORK_STACK})
1219 public void setRequireVpnForUids(boolean requireVpn,
1220 @NonNull Collection<Range<Integer>> ranges) {
1221 Objects.requireNonNull(ranges);
1222 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1223 // This method is not necessarily expected to be used outside the system server, so
1224 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1225 // stack process, or by tests.
1226 UidRange[] rangesArray = new UidRange[ranges.size()];
1227 int index = 0;
1228 for (Range<Integer> range : ranges) {
1229 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1230 }
1231 try {
1232 mService.setRequireVpnForUids(requireVpn, rangesArray);
1233 } catch (RemoteException e) {
1234 throw e.rethrowFromSystemServer();
1235 }
1236 }
1237
1238 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001239 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1240 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1241 * but is still supported for backwards compatibility.
1242 * <p>
1243 * This type of VPN is assumed always to use the system default network, and must always declare
1244 * exactly one underlying network, which is the network that was the default when the VPN
1245 * connected.
1246 * <p>
1247 * Calling this method with {@code true} enables legacy behaviour, specifically:
1248 * <ul>
1249 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1250 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1251 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1252 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1253 * underlying the VPN.</li>
1254 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1255 * similarly replaced by the VPN network state.</li>
1256 * <li>Information on current network interfaces passed to NetworkStatsService will not
1257 * include any VPN interfaces.</li>
1258 * </ul>
1259 *
1260 * @param enabled whether legacy lockdown VPN is enabled or disabled
1261 *
1262 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1263 *
1264 * @hide
1265 */
1266 @RequiresPermission(anyOf = {
1267 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1268 android.Manifest.permission.NETWORK_SETTINGS})
1269 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1270 try {
1271 mService.setLegacyLockdownVpnEnabled(enabled);
1272 } catch (RemoteException e) {
1273 throw e.rethrowFromSystemServer();
1274 }
1275 }
1276
1277 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001278 * Returns details about the currently active default data network
1279 * for a given uid. This is for internal use only to avoid spying
1280 * other apps.
1281 *
1282 * @return a {@link NetworkInfo} object for the current default network
1283 * for the given uid or {@code null} if no default network is
1284 * available for the specified uid.
1285 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001286 * {@hide}
1287 */
paulhu8e96a752019-08-12 16:25:11 +08001288 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001289 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001290 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001291 return getActiveNetworkInfoForUid(uid, false);
1292 }
1293
1294 /** {@hide} */
1295 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001296 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001297 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001298 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001299 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001300 }
1301 }
1302
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001303 /**
1304 * Returns connection status information about a particular
1305 * network type.
1306 *
1307 * @param networkType integer specifying which networkType in
1308 * which you're interested.
1309 * @return a {@link NetworkInfo} object for the requested
1310 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001311 * supported by the device. If {@code networkType} is
1312 * TYPE_VPN and a VPN is active for the calling app,
1313 * then this method will try to return one of the
1314 * underlying networks for the VPN or null if the
1315 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001316 *
Paul Jensendda8e592015-03-18 12:23:02 -04001317 * @deprecated This method does not support multiple connected networks
1318 * of the same type. Use {@link #getAllNetworks} and
1319 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001320 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001321 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001322 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001323 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001324 public NetworkInfo getNetworkInfo(int networkType) {
1325 try {
1326 return mService.getNetworkInfo(networkType);
1327 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001328 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001329 }
1330 }
1331
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001332 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001333 * Returns connection status information about a particular
1334 * Network.
1335 *
1336 * @param network {@link Network} specifying which network
1337 * in which you're interested.
1338 * @return a {@link NetworkInfo} object for the requested
1339 * network or {@code null} if the {@code Network}
1340 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001341 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001342 */
junyulai9826e7f2018-12-13 12:47:51 +08001343 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001344 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001345 @Nullable
1346 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001347 return getNetworkInfoForUid(network, Process.myUid(), false);
1348 }
1349
1350 /** {@hide} */
1351 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001352 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001353 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001354 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001355 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001356 }
1357 }
1358
1359 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001360 * Returns connection status information about all network
1361 * types supported by the device.
1362 *
1363 * @return an array of {@link NetworkInfo} objects. Check each
1364 * {@link NetworkInfo#getType} for which type each applies.
1365 *
Paul Jensendda8e592015-03-18 12:23:02 -04001366 * @deprecated This method does not support multiple connected networks
1367 * of the same type. Use {@link #getAllNetworks} and
1368 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001369 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001370 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001371 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001372 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001373 public NetworkInfo[] getAllNetworkInfo() {
1374 try {
1375 return mService.getAllNetworkInfo();
1376 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001377 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001378 }
1379 }
1380
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001381 /**
junyulaiebd15162021-03-03 12:09:05 +08001382 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1383 * connected.
1384 * @hide
1385 */
1386 @SystemApi(client = MODULE_LIBRARIES)
1387 @RequiresPermission(anyOf = {
1388 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1389 android.Manifest.permission.NETWORK_STACK,
1390 android.Manifest.permission.NETWORK_SETTINGS})
1391 @NonNull
1392 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1393 try {
1394 return mService.getAllNetworkStateSnapshot();
1395 } catch (RemoteException e) {
1396 throw e.rethrowFromSystemServer();
1397 }
1398 }
1399
1400 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001401 * Returns the {@link Network} object currently serving a given type, or
1402 * null if the given type is not connected.
1403 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001404 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001405 * @deprecated This method does not support multiple connected networks
1406 * of the same type. Use {@link #getAllNetworks} and
1407 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001408 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001409 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001410 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001411 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001412 public Network getNetworkForType(int networkType) {
1413 try {
1414 return mService.getNetworkForType(networkType);
1415 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001416 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001417 }
1418 }
1419
1420 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001421 * Returns an array of all {@link Network} currently tracked by the
1422 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001423 *
1424 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001425 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001426 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001427 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001428 public Network[] getAllNetworks() {
1429 try {
1430 return mService.getAllNetworks();
1431 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001432 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001433 }
1434 }
1435
1436 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001437 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001438 * the Networks that applications run by the given user will use by default.
1439 * @hide
1440 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001441 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001442 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1443 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001444 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001445 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001446 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001447 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001448 }
1449 }
1450
1451 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001452 * Returns the IP information for the current default network.
1453 *
1454 * @return a {@link LinkProperties} object describing the IP info
1455 * for the current default network, or {@code null} if there
1456 * is no current default network.
1457 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001458 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001459 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1460 * value of {@link #getActiveNetwork()} instead. In particular,
1461 * this method will return non-null LinkProperties even if the
1462 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001463 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001464 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001465 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001466 public LinkProperties getActiveLinkProperties() {
1467 try {
1468 return mService.getActiveLinkProperties();
1469 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001470 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001471 }
1472 }
1473
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001474 /**
1475 * Returns the IP information for a given network type.
1476 *
1477 * @param networkType the network type of interest.
1478 * @return a {@link LinkProperties} object describing the IP info
1479 * for the given networkType, or {@code null} if there is
1480 * no current default network.
1481 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001482 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001483 * @deprecated This method does not support multiple connected networks
1484 * of the same type. Use {@link #getAllNetworks},
1485 * {@link #getNetworkInfo(android.net.Network)}, and
1486 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001487 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001488 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001489 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001490 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001491 public LinkProperties getLinkProperties(int networkType) {
1492 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001493 return mService.getLinkPropertiesForType(networkType);
1494 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001495 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001496 }
1497 }
1498
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001499 /**
1500 * Get the {@link LinkProperties} for the given {@link Network}. This
1501 * will return {@code null} if the network is unknown.
1502 *
1503 * @param network The {@link Network} object identifying the network in question.
1504 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001505 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001506 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001507 @Nullable
1508 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001509 try {
1510 return mService.getLinkProperties(network);
1511 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001512 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001513 }
1514 }
1515
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001516 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001517 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001518 * will return {@code null} if the network is unknown.
1519 *
Roshan Pius951c0032020-12-22 15:10:42 -08001520 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1521 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1522 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1523 * this location sensitive information (subject to app's location permissions) will be
1524 * noted by system. To include any location sensitive data in {@link TransportInfo},
1525 * use a {@link NetworkCallback} with
1526 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1527 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001528 * @param network The {@link Network} object identifying the network in question.
Roshan Pius951c0032020-12-22 15:10:42 -08001529 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001530 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001531 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001532 @Nullable
1533 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001534 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001535 return mService.getNetworkCapabilities(
1536 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001537 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001538 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001539 }
1540 }
1541
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001542 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001543 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001544 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1545 * portal is present.
1546 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1547 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1548 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001549 * The system network validation may be using different strategies to detect captive portals,
1550 * so this method does not necessarily return a URL used by the system. It only returns a URL
1551 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001552 *
Udam Sainicd645462016-01-04 12:16:14 -08001553 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001554 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1555 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001556 */
paulhu8e96a752019-08-12 16:25:11 +08001557 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001558 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001559 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001560 public String getCaptivePortalServerUrl() {
1561 try {
1562 return mService.getCaptivePortalServerUrl();
1563 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001564 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001565 }
1566 }
1567
1568 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001569 * Tells the underlying networking system that the caller wants to
1570 * begin using the named feature. The interpretation of {@code feature}
1571 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001572 *
1573 * <p>This method requires the caller to hold either the
1574 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1575 * or the ability to modify system settings as determined by
1576 * {@link android.provider.Settings.System#canWrite}.</p>
1577 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001578 * @param networkType specifies which network the request pertains to
1579 * @param feature the name of the feature to be used
1580 * @return an integer value representing the outcome of the request.
1581 * The interpretation of this value is specific to each networking
1582 * implementation+feature combination, except that the value {@code -1}
1583 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001584 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001585 * @deprecated Deprecated in favor of the cleaner
1586 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001587 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001588 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001589 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001590 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001591 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001592 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001593 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001594 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1595 if (netCap == null) {
1596 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1597 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001598 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001599 }
1600
1601 NetworkRequest request = null;
1602 synchronized (sLegacyRequests) {
1603 LegacyRequest l = sLegacyRequests.get(netCap);
1604 if (l != null) {
1605 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1606 renewRequestLocked(l);
1607 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001608 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001609 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001610 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001611 }
1612 }
1613
1614 request = requestNetworkForFeatureLocked(netCap);
1615 }
1616 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001617 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001618 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001619 } else {
1620 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001621 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001622 }
1623 }
1624
1625 /**
1626 * Tells the underlying networking system that the caller is finished
1627 * using the named feature. The interpretation of {@code feature}
1628 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001629 *
1630 * <p>This method requires the caller to hold either the
1631 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1632 * or the ability to modify system settings as determined by
1633 * {@link android.provider.Settings.System#canWrite}.</p>
1634 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001635 * @param networkType specifies which network the request pertains to
1636 * @param feature the name of the feature that is no longer needed
1637 * @return an integer value representing the outcome of the request.
1638 * The interpretation of this value is specific to each networking
1639 * implementation+feature combination, except that the value {@code -1}
1640 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001641 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001642 * @deprecated Deprecated in favor of the cleaner
1643 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001644 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001645 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001646 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001647 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001648 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001649 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001650 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001651 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1652 if (netCap == null) {
1653 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1654 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001655 return -1;
1656 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001657
Paul Jensen49f74a32014-12-17 10:39:34 -05001658 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001659 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001660 }
1661 return 1;
1662 }
1663
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001664 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001665 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1666 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001667 switch (feature) {
1668 case "enableCBS":
1669 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1670 case "enableDUN":
1671 case "enableDUNAlways":
1672 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1673 case "enableFOTA":
1674 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1675 case "enableHIPRI":
1676 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1677 case "enableIMS":
1678 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1679 case "enableMMS":
1680 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1681 case "enableSUPL":
1682 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1683 default:
1684 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001685 }
Erik Klinece55eb12017-01-26 18:08:28 +09001686 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1687 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001688 }
1689 return null;
1690 }
1691
Robert Greenwalt802c1102014-06-02 15:32:02 -07001692 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001693 if (netCap == null) return TYPE_NONE;
1694 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1695 return TYPE_MOBILE_CBS;
1696 }
1697 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1698 return TYPE_MOBILE_IMS;
1699 }
1700 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1701 return TYPE_MOBILE_FOTA;
1702 }
1703 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1704 return TYPE_MOBILE_DUN;
1705 }
1706 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1707 return TYPE_MOBILE_SUPL;
1708 }
1709 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1710 return TYPE_MOBILE_MMS;
1711 }
1712 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1713 return TYPE_MOBILE_HIPRI;
1714 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001715 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1716 return TYPE_WIFI_P2P;
1717 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001718 return TYPE_NONE;
1719 }
1720
1721 private static class LegacyRequest {
1722 NetworkCapabilities networkCapabilities;
1723 NetworkRequest networkRequest;
1724 int expireSequenceNumber;
1725 Network currentNetwork;
1726 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001727
1728 private void clearDnsBinding() {
1729 if (currentNetwork != null) {
1730 currentNetwork = null;
1731 setProcessDefaultNetworkForHostResolution(null);
1732 }
1733 }
1734
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001735 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001736 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001737 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001738 currentNetwork = network;
1739 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001740 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001741 }
1742 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001743 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001744 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001745 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1746 }
1747 };
1748 }
1749
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001750 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001751 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1752 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001753
1754 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1755 synchronized (sLegacyRequests) {
1756 LegacyRequest l = sLegacyRequests.get(netCap);
1757 if (l != null) return l.networkRequest;
1758 }
1759 return null;
1760 }
1761
1762 private void renewRequestLocked(LegacyRequest l) {
1763 l.expireSequenceNumber++;
1764 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1765 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1766 }
1767
1768 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1769 int ourSeqNum = -1;
1770 synchronized (sLegacyRequests) {
1771 LegacyRequest l = sLegacyRequests.get(netCap);
1772 if (l == null) return;
1773 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001774 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001775 }
1776 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1777 }
1778
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001779 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001780 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1781 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001782 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001783 try {
1784 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001785 } catch (RemoteException e) {
1786 throw e.rethrowFromSystemServer();
1787 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001788 LegacyRequest l = new LegacyRequest();
1789 l.networkCapabilities = netCap;
1790 l.delay = delay;
1791 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001792 l.networkRequest = sendRequestForNetwork(
1793 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001794 if (l.networkRequest == null) return null;
1795 sLegacyRequests.put(netCap, l);
1796 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1797 return l.networkRequest;
1798 }
1799
1800 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1801 if (delay >= 0) {
1802 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001803 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001804 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1805 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001806 }
1807 }
1808
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001809 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001810 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1811 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001812 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001813 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001814 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001815 if (l == null) return false;
1816 unregisterNetworkCallback(l.networkCallback);
1817 l.clearDnsBinding();
1818 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001819 }
1820
Erik Klinece55eb12017-01-26 18:08:28 +09001821 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1822 static {
1823 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1824 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1825 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1826 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1827 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1828 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1829 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1830 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1831 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1832 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1833 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1834 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1835 }
1836
1837 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1838 static {
1839 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1840 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1841 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1842 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1843 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1844 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1845 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1846 }
1847
1848 /**
1849 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1850 * instance suitable for registering a request or callback. Throws an
1851 * IllegalArgumentException if no mapping from the legacy type to
1852 * NetworkCapabilities is known.
1853 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001854 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1855 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001856 * @hide
1857 */
1858 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1859 final NetworkCapabilities nc = new NetworkCapabilities();
1860
1861 // Map from type to transports.
1862 final int NOT_FOUND = -1;
1863 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00001864 if (transport == NOT_FOUND) {
1865 throw new IllegalArgumentException("unknown legacy type: " + type);
1866 }
Erik Klinece55eb12017-01-26 18:08:28 +09001867 nc.addTransportType(transport);
1868
1869 // Map from type to capabilities.
1870 nc.addCapability(sLegacyTypeToCapability.get(
1871 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1872 nc.maybeMarkCapabilitiesRestricted();
1873 return nc;
1874 }
1875
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001876 /** @hide */
1877 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001878 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001879 public PacketKeepaliveCallback() {
1880 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001881 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001882 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001883 public void onStarted() {}
1884 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001885 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001886 public void onStopped() {}
1887 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001888 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001889 public void onError(int error) {}
1890 }
1891
1892 /**
1893 * Allows applications to request that the system periodically send specific packets on their
1894 * behalf, using hardware offload to save battery power.
1895 *
1896 * To request that the system send keepalives, call one of the methods that return a
1897 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1898 * passing in a non-null callback. If the callback is successfully started, the callback's
1899 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1900 * specifying one of the {@code ERROR_*} constants in this class.
1901 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001902 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1903 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1904 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001905 *
junyulai4c95b082018-12-27 17:25:29 +08001906 * @deprecated Use {@link SocketKeepalive} instead.
1907 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001908 * @hide
1909 */
1910 public class PacketKeepalive {
1911
1912 private static final String TAG = "PacketKeepalive";
1913
1914 /** @hide */
1915 public static final int SUCCESS = 0;
1916
1917 /** @hide */
1918 public static final int NO_KEEPALIVE = -1;
1919
1920 /** @hide */
1921 public static final int BINDER_DIED = -10;
1922
1923 /** The specified {@code Network} is not connected. */
1924 public static final int ERROR_INVALID_NETWORK = -20;
1925 /** The specified IP addresses are invalid. For example, the specified source IP address is
1926 * not configured on the specified {@code Network}. */
1927 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1928 /** The requested port is invalid. */
1929 public static final int ERROR_INVALID_PORT = -22;
1930 /** The packet length is invalid (e.g., too long). */
1931 public static final int ERROR_INVALID_LENGTH = -23;
1932 /** The packet transmission interval is invalid (e.g., too short). */
1933 public static final int ERROR_INVALID_INTERVAL = -24;
1934
1935 /** The hardware does not support this request. */
1936 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001937 /** The hardware returned an error. */
1938 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001939
Nathan Harold0990bc82018-02-14 13:09:45 -08001940 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001941 public static final int NATT_PORT = 4500;
1942
Nathan Harold0990bc82018-02-14 13:09:45 -08001943 /** The minimum interval in seconds between keepalive packet transmissions */
1944 public static final int MIN_INTERVAL = 10;
1945
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001946 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001947 private final ISocketKeepaliveCallback mCallback;
1948 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001949
1950 private volatile Integer mSlot;
1951
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001952 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001953 public void stop() {
1954 try {
junyulai070f9ff2019-01-16 20:23:34 +08001955 mExecutor.execute(() -> {
1956 try {
1957 if (mSlot != null) {
1958 mService.stopKeepalive(mNetwork, mSlot);
1959 }
1960 } catch (RemoteException e) {
1961 Log.e(TAG, "Error stopping packet keepalive: ", e);
1962 throw e.rethrowFromSystemServer();
1963 }
1964 });
1965 } catch (RejectedExecutionException e) {
1966 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001967 }
1968 }
1969
1970 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00001971 Objects.requireNonNull(network, "network cannot be null");
1972 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001973 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001974 mExecutor = Executors.newSingleThreadExecutor();
1975 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001976 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001977 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001978 final long token = Binder.clearCallingIdentity();
1979 try {
1980 mExecutor.execute(() -> {
1981 mSlot = slot;
1982 callback.onStarted();
1983 });
1984 } finally {
1985 Binder.restoreCallingIdentity(token);
1986 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001987 }
junyulai070f9ff2019-01-16 20:23:34 +08001988
1989 @Override
1990 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001991 final long token = Binder.clearCallingIdentity();
1992 try {
1993 mExecutor.execute(() -> {
1994 mSlot = null;
1995 callback.onStopped();
1996 });
1997 } finally {
1998 Binder.restoreCallingIdentity(token);
1999 }
junyulai070f9ff2019-01-16 20:23:34 +08002000 mExecutor.shutdown();
2001 }
2002
2003 @Override
2004 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08002005 final long token = Binder.clearCallingIdentity();
2006 try {
2007 mExecutor.execute(() -> {
2008 mSlot = null;
2009 callback.onError(error);
2010 });
2011 } finally {
2012 Binder.restoreCallingIdentity(token);
2013 }
junyulai070f9ff2019-01-16 20:23:34 +08002014 mExecutor.shutdown();
2015 }
2016
2017 @Override
2018 public void onDataReceived() {
2019 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2020 // this callback when data is received.
2021 }
2022 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002023 }
2024 }
2025
2026 /**
2027 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2028 *
junyulai4c95b082018-12-27 17:25:29 +08002029 * @deprecated Use {@link #createSocketKeepalive} instead.
2030 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002031 * @hide
2032 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002033 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002034 public PacketKeepalive startNattKeepalive(
2035 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2036 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2037 final PacketKeepalive k = new PacketKeepalive(network, callback);
2038 try {
junyulai070f9ff2019-01-16 20:23:34 +08002039 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002040 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2041 } catch (RemoteException e) {
2042 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08002043 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002044 }
2045 return k;
2046 }
2047
Chiachang Wang619319a2021-01-15 11:06:21 +08002048 // Construct an invalid fd.
2049 private ParcelFileDescriptor createInvalidFd() {
2050 final int invalidFd = -1;
2051 return ParcelFileDescriptor.adoptFd(invalidFd);
2052 }
2053
The Android Open Source Project28527d22009-03-03 19:31:44 -08002054 /**
junyulai4c95b082018-12-27 17:25:29 +08002055 * Request that keepalives be started on a IPsec NAT-T socket.
2056 *
2057 * @param network The {@link Network} the socket is on.
2058 * @param socket The socket that needs to be kept alive.
2059 * @param source The source address of the {@link UdpEncapsulationSocket}.
2060 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2061 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2062 * must run callback sequentially, otherwise the order of callbacks cannot be
2063 * guaranteed.
2064 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2065 * changes. Must be extended by applications that use this API.
2066 *
junyulai0835a1e2019-01-08 20:04:33 +08002067 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2068 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08002069 **/
junyulai7e06ad42019-03-04 22:45:36 +08002070 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08002071 @NonNull UdpEncapsulationSocket socket,
2072 @NonNull InetAddress source,
2073 @NonNull InetAddress destination,
2074 @NonNull @CallbackExecutor Executor executor,
2075 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002076 ParcelFileDescriptor dup;
2077 try {
junyulai828dad12019-03-27 11:00:37 +08002078 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2079 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08002080 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2081 } catch (IOException ignored) {
2082 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2083 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002084 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002085 }
2086 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2087 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002088 }
2089
2090 /**
2091 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2092 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2093 *
2094 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002095 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2096 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2097 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002098 * @param source The source address of the {@link UdpEncapsulationSocket}.
2099 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2100 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2101 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2102 * must run callback sequentially, otherwise the order of callbacks cannot be
2103 * guaranteed.
2104 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2105 * changes. Must be extended by applications that use this API.
2106 *
junyulai0835a1e2019-01-08 20:04:33 +08002107 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2108 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002109 * @hide
2110 */
2111 @SystemApi
2112 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002113 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2114 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002115 @NonNull InetAddress source,
2116 @NonNull InetAddress destination,
2117 @NonNull @CallbackExecutor Executor executor,
2118 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002119 ParcelFileDescriptor dup;
2120 try {
junyulai828dad12019-03-27 11:00:37 +08002121 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002122 dup = pfd.dup();
2123 } catch (IOException ignored) {
2124 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2125 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002126 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002127 }
2128 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANce355502021-03-11 10:56:49 +00002129 -1 /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002130 }
2131
2132 /**
junyulai0835a1e2019-01-08 20:04:33 +08002133 * Request that keepalives be started on a TCP socket.
2134 * The socket must be established.
2135 *
2136 * @param network The {@link Network} the socket is on.
2137 * @param socket The socket that needs to be kept alive.
2138 * @param executor The executor on which callback will be invoked. This implementation assumes
2139 * the provided {@link Executor} runs the callbacks in sequence with no
2140 * concurrency. Failing this, no guarantee of correctness can be made. It is
2141 * the responsibility of the caller to ensure the executor provides this
2142 * guarantee. A simple way of creating such an executor is with the standard
2143 * tool {@code Executors.newSingleThreadExecutor}.
2144 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2145 * changes. Must be extended by applications that use this API.
2146 *
2147 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2148 * given socket.
2149 * @hide
2150 */
2151 @SystemApi
2152 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002153 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002154 @NonNull Socket socket,
2155 @NonNull Executor executor,
2156 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002157 ParcelFileDescriptor dup;
2158 try {
2159 dup = ParcelFileDescriptor.fromSocket(socket);
2160 } catch (UncheckedIOException ignored) {
2161 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2162 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002163 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002164 }
2165 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002166 }
2167
2168 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002169 * Ensure that a network route exists to deliver traffic to the specified
2170 * host via the specified network interface. An attempt to add a route that
2171 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002172 *
2173 * <p>This method requires the caller to hold either the
2174 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2175 * or the ability to modify system settings as determined by
2176 * {@link android.provider.Settings.System#canWrite}.</p>
2177 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002178 * @param networkType the type of the network over which traffic to the specified
2179 * host is to be routed
2180 * @param hostAddress the IP address of the host to which the route is desired
2181 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002182 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002183 * @deprecated Deprecated in favor of the
2184 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2185 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002186 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002187 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002188 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002189 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002190 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002191 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002192 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002193 }
2194
2195 /**
2196 * Ensure that a network route exists to deliver traffic to the specified
2197 * host via the specified network interface. An attempt to add a route that
2198 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002199 *
2200 * <p>This method requires the caller to hold either the
2201 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2202 * or the ability to modify system settings as determined by
2203 * {@link android.provider.Settings.System#canWrite}.</p>
2204 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002205 * @param networkType the type of the network over which traffic to the specified
2206 * host is to be routed
2207 * @param hostAddress the IP address of the host to which the route is desired
2208 * @return {@code true} on success, {@code false} on failure
2209 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002210 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002211 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002212 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002213 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002214 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002215 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002216 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002217 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002218 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2219 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002220 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002221 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002222 }
2223 }
2224
2225 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002226 * @return the context's attribution tag
2227 */
2228 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2229 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002230 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002231 }
2232
2233 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002234 * Returns the value of the setting for background data usage. If false,
2235 * applications should not use the network if the application is not in the
2236 * foreground. Developers should respect this setting, and check the value
2237 * of this before performing any background data operations.
2238 * <p>
2239 * All applications that have background services that use the network
2240 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002241 * <p>
Scott Main50589142011-10-06 18:32:43 -07002242 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002243 * background data depends on several combined factors, and this method will
2244 * always return {@code true}. Instead, when background data is unavailable,
2245 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002246 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002247 * @return Whether background data usage is allowed.
2248 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002249 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002250 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002251 // assume that background data is allowed; final authority is
2252 // NetworkInfo which may be blocked.
2253 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002254 }
2255
2256 /**
2257 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002258 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002259 * @param allowBackgroundData Whether an application should use data while
2260 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002261 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002262 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2263 * @see #getBackgroundDataSetting()
2264 * @hide
2265 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002266 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002267 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002268 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002269 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002270 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002271
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002272 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002273 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002274 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002275 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002276 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002277 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002278 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002279 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2280 if (tm != null) {
2281 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2282 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2283 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2284 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2285 + " retVal=" + retVal);
2286 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002287 }
Wink Saville689f7042014-12-05 11:10:30 -08002288 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002289 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002290 }
2291
The Android Open Source Project28527d22009-03-03 19:31:44 -08002292 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002293 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002294 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002295 */
2296 public interface OnNetworkActiveListener {
2297 /**
2298 * Called on the main thread of the process to report that the current data network
2299 * has become active, and it is now a good time to perform any pending network
2300 * operations. Note that this listener only tells you when the network becomes
2301 * active; if at any other time you want to know whether it is active (and thus okay
2302 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002303 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002304 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002305 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002306 }
2307
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002308 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002309 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002310
2311 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002312 * Start listening to reports when the system's default data network is active, meaning it is
2313 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2314 * to determine the current state of the system's default network after registering the
2315 * listener.
2316 * <p>
2317 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002318 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002319 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002320 *
2321 * @param l The listener to be told when the network is active.
2322 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002323 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002324 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2325 @Override
2326 public void onNetworkActive() throws RemoteException {
2327 l.onNetworkActive();
2328 }
2329 };
2330
2331 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002332 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002333 mNetworkActivityListeners.put(l, rl);
2334 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002335 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002336 }
2337 }
2338
2339 /**
2340 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002341 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002342 *
2343 * @param l Previously registered listener.
2344 */
Chalard Jean158702d2019-01-07 19:26:34 +09002345 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002346 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002347 if (rl == null) {
2348 throw new IllegalArgumentException("Listener was not registered.");
2349 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002350 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002351 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002352 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002353 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002354 }
2355 }
2356
2357 /**
2358 * Return whether the data network is currently active. An active network means that
2359 * it is currently in a high power state for performing data transmission. On some
2360 * types of networks, it may be expensive to move and stay in such a state, so it is
2361 * more power efficient to batch network traffic together when the radio is already in
2362 * this state. This method tells you whether right now is currently a good time to
2363 * initiate network traffic, as the network is already active.
2364 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002365 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002366 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002367 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002368 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002369 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002370 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002371 }
2372
2373 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002374 * {@hide}
2375 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002376 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002377 mContext = Objects.requireNonNull(context, "missing context");
2378 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002379 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002380 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002381 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002382
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002383 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002384 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002385 public static ConnectivityManager from(Context context) {
2386 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2387 }
2388
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002389 /** @hide */
2390 public NetworkRequest getDefaultRequest() {
2391 try {
2392 // This is not racy as the default request is final in ConnectivityService.
2393 return mService.getDefaultRequest();
2394 } catch (RemoteException e) {
2395 throw e.rethrowFromSystemServer();
2396 }
2397 }
2398
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002399 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002400 * Check if the package is a allowed to write settings. This also accounts that such an access
2401 * happened.
2402 *
2403 * @return {@code true} iff the package is allowed to write settings.
2404 */
2405 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2406 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2407 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2408 boolean throwException) {
2409 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2410 throwException);
2411 }
2412
2413 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002414 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2415 * situations where a Context pointer is unavailable.
2416 * @hide
2417 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002418 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002419 static ConnectivityManager getInstanceOrNull() {
2420 return sInstance;
2421 }
2422
2423 /**
2424 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2425 * situations where a Context pointer is unavailable.
2426 * @hide
2427 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002428 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002429 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002430 private static ConnectivityManager getInstance() {
2431 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002432 throw new IllegalStateException("No ConnectivityManager yet constructed");
2433 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002434 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002435 }
2436
2437 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002438 * Get the set of tetherable, available interfaces. This list is limited by
2439 * device configuration and current interface existence.
2440 *
2441 * @return an array of 0 or more Strings of tetherable interface names.
2442 *
markchien6ae63e52020-01-21 13:11:06 +08002443 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002444 * {@hide}
2445 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002446 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002447 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002448 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002449 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002450 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002451 }
2452
2453 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002454 * Get the set of tethered interfaces.
2455 *
2456 * @return an array of 0 or more String of currently tethered interface names.
2457 *
markchien6ae63e52020-01-21 13:11:06 +08002458 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002459 * {@hide}
2460 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002461 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002462 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002463 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002464 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002465 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002466 }
2467
2468 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002469 * Get the set of interface names which attempted to tether but
2470 * failed. Re-attempting to tether may cause them to reset to the Tethered
2471 * state. Alternatively, causing the interface to be destroyed and recreated
2472 * may cause them to reset to the available state.
2473 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2474 * information on the cause of the errors.
2475 *
2476 * @return an array of 0 or more String indicating the interface names
2477 * which failed to tether.
2478 *
markchien6ae63e52020-01-21 13:11:06 +08002479 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002480 * {@hide}
2481 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002482 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002483 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002484 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002485 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002486 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002487 }
2488
2489 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002490 * Get the set of tethered dhcp ranges.
2491 *
markchien2e6ba522020-02-14 11:55:48 +08002492 * @deprecated This method is not supported.
2493 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002494 * {@hide}
2495 */
paulhu8e96a752019-08-12 16:25:11 +08002496 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002497 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002498 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002499 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002500 }
2501
2502 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002503 * Attempt to tether the named interface. This will setup a dhcp server
2504 * on the interface, forward and NAT IP packets and forward DNS requests
2505 * to the best active upstream network interface. Note that if no upstream
2506 * IP network interface is available, dhcp will still run and traffic will be
2507 * allowed between the tethered devices and this device, though upstream net
2508 * access will of course fail until an upstream network interface becomes
2509 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002510 *
2511 * <p>This method requires the caller to hold either the
2512 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2513 * or the ability to modify system settings as determined by
2514 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002515 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002516 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2517 * and WifiStateMachine which need direct access. All other clients should use
2518 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2519 * logic.</p>
2520 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002521 * @param iface the interface name to tether.
2522 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002523 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002524 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002525 * {@hide}
2526 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002527 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002528 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002529 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002530 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002531 }
2532
2533 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002534 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002535 *
2536 * <p>This method requires the caller to hold either the
2537 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2538 * or the ability to modify system settings as determined by
2539 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002540 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002541 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2542 * and WifiStateMachine which need direct access. All other clients should use
2543 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2544 * logic.</p>
2545 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002546 * @param iface the interface name to untether.
2547 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2548 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002549 * {@hide}
2550 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002551 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002552 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002553 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002554 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002555 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002556
2557 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002558 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002559 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002560 * due to device configuration.
2561 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002562 * <p>If this app does not have permission to use this API, it will always
2563 * return false rather than throw an exception.</p>
2564 *
2565 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2566 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2567 *
2568 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2569 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2570 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002571 * @return a boolean - {@code true} indicating Tethering is supported.
2572 *
markchien6ae63e52020-01-21 13:11:06 +08002573 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002574 * {@hide}
2575 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002576 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002577 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2578 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002579 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002580 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002581 }
2582
2583 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002584 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002585 *
2586 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002587 * @hide
2588 */
2589 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002590 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002591 public static abstract class OnStartTetheringCallback {
2592 /**
2593 * Called when tethering has been successfully started.
2594 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002595 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002596
2597 /**
2598 * Called when starting tethering failed.
2599 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002600 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002601 }
2602
2603 /**
2604 * Convenient overload for
2605 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2606 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002607 *
2608 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002609 * @hide
2610 */
2611 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002612 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002613 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002614 public void startTethering(int type, boolean showProvisioningUi,
2615 final OnStartTetheringCallback callback) {
2616 startTethering(type, showProvisioningUi, callback, null);
2617 }
2618
2619 /**
2620 * Runs tether provisioning for the given type if needed and then starts tethering if
2621 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2622 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2623 * schedules tether provisioning re-checks if appropriate.
2624 *
2625 * @param type The type of tethering to start. Must be one of
2626 * {@link ConnectivityManager.TETHERING_WIFI},
2627 * {@link ConnectivityManager.TETHERING_USB}, or
2628 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2629 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2630 * is one. This should be true the first time this function is called and also any time
2631 * the user can see this UI. It gives users information from their carrier about the
2632 * check failing and how they can sign up for tethering if possible.
2633 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2634 * of the result of trying to tether.
2635 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002636 *
2637 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002638 * @hide
2639 */
2640 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002641 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002642 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002643 public void startTethering(int type, boolean showProvisioningUi,
2644 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002645 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002646
markchien91c78e52020-01-20 19:31:56 +08002647 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002648 @Override
markchien91c78e52020-01-20 19:31:56 +08002649 public void execute(Runnable command) {
2650 if (handler == null) {
2651 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002652 } else {
markchien91c78e52020-01-20 19:31:56 +08002653 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002654 }
2655 }
2656 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002657
markchien91c78e52020-01-20 19:31:56 +08002658 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2659 @Override
2660 public void onTetheringStarted() {
2661 callback.onTetheringStarted();
2662 }
2663
2664 @Override
markchienf47d8342020-03-19 13:37:43 +08002665 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002666 callback.onTetheringFailed();
2667 }
2668 };
2669
2670 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002671 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002672
Amos Bianchia9b415a2020-03-04 11:07:38 -08002673 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002674 }
2675
2676 /**
2677 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2678 * applicable.
2679 *
2680 * @param type The type of tethering to stop. Must be one of
2681 * {@link ConnectivityManager.TETHERING_WIFI},
2682 * {@link ConnectivityManager.TETHERING_USB}, or
2683 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002684 *
2685 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002686 * @hide
2687 */
2688 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002689 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002690 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002691 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002692 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002693 }
2694
2695 /**
markchien4ef53e82019-02-27 14:56:11 +08002696 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2697 * upstream status.
2698 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002699 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002700 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002701 */
2702 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002703 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002704 public abstract static class OnTetheringEventCallback {
2705
2706 /**
2707 * Called when tethering upstream changed. This can be called multiple times and can be
2708 * called any time.
2709 *
2710 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2711 * have any upstream.
2712 */
2713 public void onUpstreamChanged(@Nullable Network network) {}
2714 }
2715
markchien6ae63e52020-01-21 13:11:06 +08002716 @GuardedBy("mTetheringEventCallbacks")
2717 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2718 mTetheringEventCallbacks = new ArrayMap<>();
2719
markchien4ef53e82019-02-27 14:56:11 +08002720 /**
2721 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002722 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002723 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2724 * with a null argument. The same callback object cannot be registered twice.
2725 *
2726 * @param executor the executor on which callback will be invoked.
2727 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002728 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002729 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002730 * @hide
2731 */
2732 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002733 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002734 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2735 public void registerTetheringEventCallback(
2736 @NonNull @CallbackExecutor Executor executor,
2737 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002738 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchien4ef53e82019-02-27 14:56:11 +08002739
markchien6ae63e52020-01-21 13:11:06 +08002740 final TetheringEventCallback tetherCallback =
2741 new TetheringEventCallback() {
2742 @Override
2743 public void onUpstreamChanged(@Nullable Network network) {
2744 callback.onUpstreamChanged(network);
2745 }
2746 };
2747
2748 synchronized (mTetheringEventCallbacks) {
2749 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002750 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002751 }
markchien4ef53e82019-02-27 14:56:11 +08002752 }
2753
2754 /**
2755 * Remove tethering event callback previously registered with
2756 * {@link #registerTetheringEventCallback}.
2757 *
2758 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002759 *
2760 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002761 * @hide
2762 */
2763 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002764 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002765 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2766 public void unregisterTetheringEventCallback(
2767 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002768 Objects.requireNonNull(callback, "The callback must be non-null");
2769 synchronized (mTetheringEventCallbacks) {
2770 final TetheringEventCallback tetherCallback =
2771 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002772 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002773 }
markchien4ef53e82019-02-27 14:56:11 +08002774 }
2775
2776
2777 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002778 * Get the list of regular expressions that define any tetherable
2779 * USB network interfaces. If USB tethering is not supported by the
2780 * device, this list should be empty.
2781 *
2782 * @return an array of 0 or more regular expression Strings defining
2783 * what interfaces are considered tetherable usb interfaces.
2784 *
markchien6ae63e52020-01-21 13:11:06 +08002785 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002786 * {@hide}
2787 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002788 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002789 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002790 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002791 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002792 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002793 }
2794
2795 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002796 * Get the list of regular expressions that define any tetherable
2797 * Wifi network interfaces. If Wifi tethering is not supported by the
2798 * device, this list should be empty.
2799 *
2800 * @return an array of 0 or more regular expression Strings defining
2801 * what interfaces are considered tetherable wifi interfaces.
2802 *
markchien6ae63e52020-01-21 13:11:06 +08002803 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002804 * {@hide}
2805 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002806 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002807 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002808 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002809 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002810 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002811 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002812
Danica Chang96567052010-08-11 14:54:43 -07002813 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002814 * Get the list of regular expressions that define any tetherable
2815 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2816 * device, this list should be empty.
2817 *
2818 * @return an array of 0 or more regular expression Strings defining
2819 * what interfaces are considered tetherable bluetooth interfaces.
2820 *
markchien6ae63e52020-01-21 13:11:06 +08002821 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2822 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002823 * {@hide}
2824 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002825 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002826 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002827 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002828 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002829 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002830 }
2831
Mike Lockwooded4a1742011-07-19 13:04:47 -07002832 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002833 * Attempt to both alter the mode of USB and Tethering of USB. A
2834 * utility method to deal with some of the complexity of USB - will
2835 * attempt to switch to Rndis and subsequently tether the resulting
2836 * interface on {@code true} or turn off tethering and switch off
2837 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002838 *
2839 * <p>This method requires the caller to hold either the
2840 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2841 * or the ability to modify system settings as determined by
2842 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002843 *
2844 * @param enable a boolean - {@code true} to enable tethering
2845 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002846 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002847 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002848 * {@hide}
2849 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002850 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002851 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002852 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002853 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002854 }
2855
markchien6ae63e52020-01-21 13:11:06 +08002856 /**
2857 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2858 * {@hide}
2859 */
markchien0f45bb92019-01-16 17:44:13 +08002860 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002861 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002862 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002863 /**
2864 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2865 * {@hide}
2866 */
2867 @Deprecated
2868 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2869 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2870 /**
2871 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2872 * {@hide}
2873 */
2874 @Deprecated
2875 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2876 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2877 /**
2878 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2879 * {@hide}
2880 */
2881 @Deprecated
2882 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2883 /**
2884 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2885 * {@hide}
2886 */
2887 @Deprecated
2888 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2889 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2890 /**
markchienf47d8342020-03-19 13:37:43 +08002891 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002892 * {@hide}
2893 */
2894 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002895 public static final int TETHER_ERROR_MASTER_ERROR =
2896 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002897 /**
2898 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2899 * {@hide}
2900 */
2901 @Deprecated
2902 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2903 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2904 /**
2905 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2906 * {@hide}
2907 */
2908 @Deprecated
2909 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2910 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2911 /**
markchienf47d8342020-03-19 13:37:43 +08002912 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002913 * {@hide}
2914 */
2915 @Deprecated
2916 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002917 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002918 /**
markchienf47d8342020-03-19 13:37:43 +08002919 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002920 * {@hide}
2921 */
2922 @Deprecated
2923 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002924 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002925 /**
2926 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2927 * {@hide}
2928 */
2929 @Deprecated
2930 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2931 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2932 /**
markchienf47d8342020-03-19 13:37:43 +08002933 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002934 * {@hide}
2935 */
markchien0f45bb92019-01-16 17:44:13 +08002936 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002937 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002938 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002939 /**
2940 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2941 * {@hide}
2942 */
2943 @Deprecated
2944 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2945 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2946 /**
2947 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2948 * {@hide}
2949 */
markchien0f45bb92019-01-16 17:44:13 +08002950 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002951 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002952 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002953
2954 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002955 * Get a more detailed error code after a Tethering or Untethering
2956 * request asynchronously failed.
2957 *
2958 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002959 * @return error The error code of the last error tethering or untethering the named
2960 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002961 *
markchien6ae63e52020-01-21 13:11:06 +08002962 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002963 * {@hide}
2964 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002965 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002966 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002967 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002968 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002969 int error = mTetheringManager.getLastTetherError(iface);
2970 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2971 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2972 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2973 // instead.
2974 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2975 }
2976 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002977 }
2978
markchienbf5ab012019-03-06 16:25:00 +08002979 /** @hide */
2980 @Retention(RetentionPolicy.SOURCE)
2981 @IntDef(value = {
2982 TETHER_ERROR_NO_ERROR,
2983 TETHER_ERROR_PROVISION_FAILED,
2984 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2985 })
2986 public @interface EntitlementResultCode {
2987 }
2988
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002989 /**
markchienbf5ab012019-03-06 16:25:00 +08002990 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002991 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002992 *
2993 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002994 * @hide
2995 */
2996 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002997 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002998 public interface OnTetheringEntitlementResultListener {
2999 /**
3000 * Called to notify entitlement result.
3001 *
3002 * @param resultCode an int value of entitlement result. It may be one of
3003 * {@link #TETHER_ERROR_NO_ERROR},
3004 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3005 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3006 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07003007 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08003008 }
3009
3010 /**
markchien0f45bb92019-01-16 17:44:13 +08003011 * Get the last value of the entitlement check on this downstream. If the cached value is
3012 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3013 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3014 * guaranteed that the UI-based entitlement check will complete in any specific time period
3015 * and may in fact never complete. Any successful entitlement check the platform performs for
3016 * any reason will update the cached value.
3017 *
3018 * @param type the downstream type of tethering. Must be one of
3019 * {@link #TETHERING_WIFI},
3020 * {@link #TETHERING_USB}, or
3021 * {@link #TETHERING_BLUETOOTH}.
3022 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08003023 * @param executor the executor on which callback will be invoked.
3024 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3025 * notify the caller of the result of entitlement check. The listener may be called zero
3026 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08003027 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08003028 * {@hide}
3029 */
3030 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08003031 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08003032 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08003033 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3034 @NonNull @CallbackExecutor Executor executor,
3035 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003036 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchienbf5ab012019-03-06 16:25:00 +08003037 ResultReceiver wrappedListener = new ResultReceiver(null) {
3038 @Override
3039 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08003040 final long token = Binder.clearCallingIdentity();
3041 try {
3042 executor.execute(() -> {
3043 listener.onTetheringEntitlementResult(resultCode);
3044 });
3045 } finally {
3046 Binder.restoreCallingIdentity(token);
3047 }
markchienbf5ab012019-03-06 16:25:00 +08003048 }
3049 };
3050
Amos Bianchia9b415a2020-03-04 11:07:38 -08003051 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08003052 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08003053 }
3054
3055 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003056 * Report network connectivity status. This is currently used only
3057 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003058 * <p>This method requires the caller to hold the permission
3059 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003060 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003061 * @param networkType The type of network you want to report on
3062 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003063 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003064 * {@hide}
3065 */
3066 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003067 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003068 try {
3069 mService.reportInetCondition(networkType, percentage);
3070 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003071 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003072 }
3073 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003074
3075 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003076 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003077 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003078 * the framework to re-evaluate network connectivity and/or switch to another
3079 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003080 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003081 * @param network The {@link Network} the application was attempting to use
3082 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003083 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3084 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003085 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003086 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003087 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003088 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003089 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003090 // One of these will be ignored because it matches system's current state.
3091 // The other will trigger the necessary reevaluation.
3092 mService.reportNetworkConnectivity(network, true);
3093 mService.reportNetworkConnectivity(network, false);
3094 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003095 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003096 }
3097 }
3098
3099 /**
3100 * Report to the framework whether a network has working connectivity.
3101 * This provides a hint to the system that a particular network is providing
3102 * working connectivity or not. In response the framework may re-evaluate
3103 * the network's connectivity and might take further action thereafter.
3104 *
3105 * @param network The {@link Network} the application was attempting to use
3106 * or {@code null} to indicate the current default network.
3107 * @param hasConnectivity {@code true} if the application was able to successfully access the
3108 * Internet using {@code network} or {@code false} if not.
3109 */
Chalard Jean158702d2019-01-07 19:26:34 +09003110 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003111 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003112 try {
3113 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003114 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003115 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003116 }
3117 }
3118
3119 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003120 * Set a network-independent global http proxy. This is not normally what you want
3121 * for typical HTTP proxies - they are general network dependent. However if you're
3122 * doing something unusual like general internal filtering this may be useful. On
3123 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003124 *
3125 * @param p A {@link ProxyInfo} object defining the new global
3126 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003127 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003128 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003129 @SystemApi(client = MODULE_LIBRARIES)
paulhu8e96a752019-08-12 16:25:11 +08003130 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang4d513572021-03-18 09:44:34 +08003131 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003132 try {
3133 mService.setGlobalProxy(p);
3134 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003135 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003136 }
3137 }
3138
3139 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003140 * Retrieve any network-independent global HTTP proxy.
3141 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003142 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003143 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003144 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003145 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003146 @SystemApi(client = MODULE_LIBRARIES)
3147 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04003148 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003149 try {
3150 return mService.getGlobalProxy();
3151 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003152 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003153 }
3154 }
3155
3156 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003157 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3158 * network-specific HTTP proxy. If {@code network} is null, the
3159 * network-specific proxy returned is the proxy of the default active
3160 * network.
3161 *
3162 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3163 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3164 * or when {@code network} is {@code null},
3165 * the {@code ProxyInfo} for the default active network. Returns
3166 * {@code null} when no proxy applies or the caller doesn't have
3167 * permission to use {@code network}.
3168 * @hide
3169 */
3170 public ProxyInfo getProxyForNetwork(Network network) {
3171 try {
3172 return mService.getProxyForNetwork(network);
3173 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003174 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003175 }
3176 }
3177
3178 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003179 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3180 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003181 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003182 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003183 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003184 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003185 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003186 */
Chalard Jean158702d2019-01-07 19:26:34 +09003187 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003188 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003189 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003190 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003191
3192 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003193 * Returns true if the hardware supports the given network type
3194 * else it returns false. This doesn't indicate we have coverage
3195 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003196 * hardware supports it. For example a GSM phone without a SIM
3197 * should still return {@code true} for mobile data, but a wifi only
3198 * tablet would return {@code false}.
3199 *
3200 * @param networkType The network type we'd like to check
3201 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003202 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003203 * @hide
3204 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003205 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003206 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003207 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003208 public boolean isNetworkSupported(int networkType) {
3209 try {
3210 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003211 } catch (RemoteException e) {
3212 throw e.rethrowFromSystemServer();
3213 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003214 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003215
3216 /**
3217 * Returns if the currently active data network is metered. A network is
3218 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003219 * that connection due to monetary costs, data limitations or
3220 * battery/performance issues. You should check this before doing large
3221 * data transfers, and warn the user or delay the operation until another
3222 * network is available.
3223 *
3224 * @return {@code true} if large transfers should be avoided, otherwise
3225 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003226 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003227 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003228 public boolean isActiveNetworkMetered() {
3229 try {
3230 return mService.isActiveNetworkMetered();
3231 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003232 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003233 }
3234 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003235
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003236 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003237 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003238 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003239 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003240 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003241 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003242 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003243 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003244 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003245 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003246 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003247 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003248 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003249 }
3250 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003251
3252 /**
3253 * Set the value for enabling/disabling airplane mode
3254 *
3255 * @param enable whether to enable airplane mode or not
3256 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003257 * @hide
3258 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003259 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003260 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003261 android.Manifest.permission.NETWORK_SETTINGS,
3262 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3263 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003264 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003265 public void setAirplaneMode(boolean enable) {
3266 try {
3267 mService.setAirplaneMode(enable);
3268 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003269 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003270 }
3271 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003272
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003273 /**
3274 * Registers the specified {@link NetworkProvider}.
3275 * Each listener must only be registered once. The listener can be unregistered with
3276 * {@link #unregisterNetworkProvider}.
3277 *
3278 * @param provider the provider to register
3279 * @return the ID of the provider. This ID must be used by the provider when registering
3280 * {@link android.net.NetworkAgent}s.
3281 * @hide
3282 */
3283 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003284 @RequiresPermission(anyOf = {
3285 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3286 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003287 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3288 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003289 throw new IllegalStateException("NetworkProviders can only be registered once");
3290 }
3291
3292 try {
3293 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3294 provider.getName());
3295 provider.setProviderId(providerId);
3296 } catch (RemoteException e) {
3297 throw e.rethrowFromSystemServer();
3298 }
3299 return provider.getProviderId();
3300 }
3301
3302 /**
3303 * Unregisters the specified NetworkProvider.
3304 *
3305 * @param provider the provider to unregister
3306 * @hide
3307 */
3308 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003309 @RequiresPermission(anyOf = {
3310 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3311 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003312 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3313 try {
3314 mService.unregisterNetworkProvider(provider.getMessenger());
3315 } catch (RemoteException e) {
3316 throw e.rethrowFromSystemServer();
3317 }
3318 provider.setProviderId(NetworkProvider.ID_NONE);
3319 }
3320
3321
3322 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003323 @RequiresPermission(anyOf = {
3324 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3325 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003326 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3327 try {
3328 mService.declareNetworkRequestUnfulfillable(request);
3329 } catch (RemoteException e) {
3330 throw e.rethrowFromSystemServer();
3331 }
3332 }
3333
Paul Jensen1f567382015-02-13 14:18:39 -05003334 /**
3335 * @hide
3336 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003337 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003338 */
paulhub6ba8e82020-03-04 09:43:41 +08003339 @RequiresPermission(anyOf = {
3340 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3341 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003342 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jean28018572020-12-21 18:36:52 +09003343 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3344 int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003345 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003346 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003347 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003348 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003349 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003350 }
3351
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003352 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003353 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3354 * changes. Should be extended by applications wanting notifications.
3355 *
3356 * A {@code NetworkCallback} is registered by calling
3357 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3358 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003359 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003360 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3361 * A {@code NetworkCallback} should be registered at most once at any time.
3362 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003363 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003364 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003365 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003366 * No flags associated with this callback.
3367 * @hide
3368 */
3369 public static final int FLAG_NONE = 0;
3370 /**
3371 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3372 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3373 * <p>
3374 * These include:
3375 * <li> Some transport info instances (retrieved via
3376 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3377 * contain location sensitive information.
3378 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3379 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3380 * </p>
3381 * <p>
3382 * Note:
3383 * <li> Retrieving this location sensitive information (subject to app's location
3384 * permissions) will be noted by system. </li>
3385 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3386 * not include location sensitive info.
3387 * </p>
3388 */
3389 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3390
3391 /** @hide */
3392 @Retention(RetentionPolicy.SOURCE)
3393 @IntDef(flag = true, prefix = "FLAG_", value = {
3394 FLAG_NONE,
3395 FLAG_INCLUDE_LOCATION_INFO
3396 })
3397 public @interface Flag { }
3398
3399 /**
3400 * All the valid flags for error checking.
3401 */
3402 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3403
3404 public NetworkCallback() {
3405 this(FLAG_NONE);
3406 }
3407
3408 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003409 if ((flags & VALID_FLAGS) != flags) {
3410 throw new IllegalArgumentException("Invalid flags");
3411 }
Roshan Pius951c0032020-12-22 15:10:42 -08003412 mFlags = flags;
3413 }
3414
3415 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003416 * Called when the framework connects to a new network to evaluate whether it satisfies this
3417 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3418 * callback. There is no guarantee that this new network will satisfy any requests, or that
3419 * the network will stay connected for longer than the time necessary to evaluate it.
3420 * <p>
3421 * Most applications <b>should not</b> act on this callback, and should instead use
3422 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3423 * the framework in properly evaluating the network &mdash; for example, an application that
3424 * can automatically log in to a captive portal without user intervention.
3425 *
3426 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003427 *
3428 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003429 */
paulhu1a407652019-03-22 16:35:06 +08003430 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003431
3432 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003433 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003434 * This callback may be called more than once if the {@link Network} that is
3435 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003436 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003437 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003438 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3439 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003440 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003441 * @hide
3442 */
paulhu1a407652019-03-22 16:35:06 +08003443 public void onAvailable(@NonNull Network network,
3444 @NonNull NetworkCapabilities networkCapabilities,
3445 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003446 // Internally only this method is called when a new network is available, and
3447 // it calls the callback in the same way and order that older versions used
3448 // to call so as not to change the behavior.
3449 onAvailable(network);
3450 if (!networkCapabilities.hasCapability(
3451 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3452 onNetworkSuspended(network);
3453 }
3454 onCapabilitiesChanged(network, networkCapabilities);
3455 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003456 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003457 }
3458
3459 /**
3460 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003461 *
3462 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3463 * be available at the same time, and onAvailable will be called for each of these as they
3464 * appear.
3465 *
3466 * <p>For callbacks registered with {@link #requestNetwork} and
3467 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3468 * is the new best network for this request and is now tracked by this callback ; this
3469 * callback will no longer receive method calls about other networks that may have been
3470 * passed to this method previously. The previously-best network may have disconnected, or
3471 * it may still be around and the newly-best network may simply be better.
3472 *
3473 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3474 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3475 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3476 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3477 *
3478 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3479 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3480 * this callback as this is prone to race conditions (there is no guarantee the objects
3481 * returned by these methods will be current). Instead, wait for a call to
3482 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3483 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3484 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003485 *
3486 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003487 */
paulhu1a407652019-03-22 16:35:06 +08003488 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003489
3490 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003491 * Called when the network is about to be lost, typically because there are no outstanding
3492 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3493 * with the new replacement network for graceful handover. This method is not guaranteed
3494 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3495 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003496 *
Chalard Jean01378b62019-08-30 16:27:28 +09003497 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3498 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3499 * this callback as this is prone to race conditions ; calling these methods while in a
3500 * callback may return an outdated or even a null object.
3501 *
3502 * @param network The {@link Network} that is about to be lost.
3503 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3504 * connected for graceful handover; note that the network may still
3505 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003506 */
paulhu1a407652019-03-22 16:35:06 +08003507 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003508
3509 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003510 * Called when a network disconnects or otherwise no longer satisfies this request or
3511 * callback.
3512 *
3513 * <p>If the callback was registered with requestNetwork() or
3514 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3515 * returned by onAvailable() when that network is lost and no other network satisfies
3516 * the criteria of the request.
3517 *
3518 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3519 * each network which no longer satisfies the criteria of the callback.
3520 *
3521 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3522 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3523 * this callback as this is prone to race conditions ; calling these methods while in a
3524 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003525 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003526 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003527 */
paulhu1a407652019-03-22 16:35:06 +08003528 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003529
3530 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003531 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003532 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3533 * requested network request cannot be fulfilled (whether or not a timeout was
3534 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003535 * {@link NetworkRequest} will have already been removed and released, as if
3536 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003537 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003538 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003539
3540 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003541 * Called when the network corresponding to this request changes capabilities but still
3542 * satisfies the requested criteria.
3543 *
3544 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3545 * to be called immediately after {@link #onAvailable}.
3546 *
3547 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3548 * ConnectivityManager methods in this callback as this is prone to race conditions :
3549 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003550 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003551 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius951c0032020-12-22 15:10:42 -08003552 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003553 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003554 */
paulhu1a407652019-03-22 16:35:06 +08003555 public void onCapabilitiesChanged(@NonNull Network network,
3556 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003557
3558 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003559 * Called when the network corresponding to this request changes {@link LinkProperties}.
3560 *
3561 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3562 * to be called immediately after {@link #onAvailable}.
3563 *
3564 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3565 * ConnectivityManager methods in this callback as this is prone to race conditions :
3566 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003567 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003568 * @param network The {@link Network} whose link properties have changed.
3569 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003570 */
paulhu1a407652019-03-22 16:35:06 +08003571 public void onLinkPropertiesChanged(@NonNull Network network,
3572 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003573
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003574 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003575 * Called when the network the framework connected to for this request suspends data
3576 * transmission temporarily.
3577 *
3578 * <p>This generally means that while the TCP connections are still live temporarily
3579 * network data fails to transfer. To give a specific example, this is used on cellular
3580 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3581 * means read operations on sockets on this network will block once the buffers are
3582 * drained, and write operations will block once the buffers are full.
3583 *
3584 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3585 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3586 * this callback as this is prone to race conditions (there is no guarantee the objects
3587 * returned by these methods will be current).
3588 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003589 * @hide
3590 */
paulhu1a407652019-03-22 16:35:06 +08003591 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003592
3593 /**
3594 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003595 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3596 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003597
3598 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3599 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3600 * this callback as this is prone to race conditions : calling these methods while in a
3601 * callback may return an outdated or even a null object.
3602 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003603 * @hide
3604 */
paulhu1a407652019-03-22 16:35:06 +08003605 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003606
junyulaif2c67e42018-08-07 19:50:45 +08003607 /**
3608 * Called when access to the specified network is blocked or unblocked.
3609 *
Chalard Jean01378b62019-08-30 16:27:28 +09003610 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3611 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3612 * this callback as this is prone to race conditions : calling these methods while in a
3613 * callback may return an outdated or even a null object.
3614 *
junyulaif2c67e42018-08-07 19:50:45 +08003615 * @param network The {@link Network} whose blocked status has changed.
3616 * @param blocked The blocked status of this {@link Network}.
3617 */
junyulai7e06ad42019-03-04 22:45:36 +08003618 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003619
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003620 private NetworkRequest networkRequest;
Roshan Pius951c0032020-12-22 15:10:42 -08003621 private final int mFlags;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003622 }
3623
Hugo Benichia590ab82017-05-11 13:16:17 +09003624 /**
3625 * Constant error codes used by ConnectivityService to communicate about failures and errors
3626 * across a Binder boundary.
3627 * @hide
3628 */
3629 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003630 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003631 }
3632
3633 /** @hide */
3634 public static class TooManyRequestsException extends RuntimeException {}
3635
3636 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3637 switch (e.errorCode) {
3638 case Errors.TOO_MANY_REQUESTS:
3639 return new TooManyRequestsException();
3640 default:
3641 Log.w(TAG, "Unknown service error code " + e.errorCode);
3642 return new RuntimeException(e);
3643 }
3644 }
3645
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003646 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003647 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003648 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003649 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003650 /** @hide arg1 = TTL */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003651 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003652 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003653 public static final int CALLBACK_LOST = 4;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003654 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003655 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003656 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003657 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003658 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003659 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003660 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003661 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003662 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003663 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003664 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003665 public static final int CALLBACK_RESUMED = 10;
junyulaif2c67e42018-08-07 19:50:45 +08003666 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003667 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003668
Erik Kline155a59a2015-11-25 12:49:38 +09003669 /** @hide */
3670 public static String getCallbackName(int whichCallback) {
3671 switch (whichCallback) {
3672 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3673 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3674 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3675 case CALLBACK_LOST: return "CALLBACK_LOST";
3676 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3677 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3678 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003679 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3680 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3681 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003682 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003683 default:
3684 return Integer.toString(whichCallback);
3685 }
3686 }
3687
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003688 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003689 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003690 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003691
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003692 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003693 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003694 }
3695
Hugo Benichifd44e912017-02-02 17:02:36 +09003696 CallbackHandler(Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003697 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003698 }
3699
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003700 @Override
3701 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003702 if (message.what == EXPIRE_LEGACY_REQUEST) {
3703 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3704 return;
3705 }
3706
3707 final NetworkRequest request = getObject(message, NetworkRequest.class);
3708 final Network network = getObject(message, Network.class);
3709 final NetworkCallback callback;
3710 synchronized (sCallbacks) {
3711 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003712 if (callback == null) {
3713 Log.w(TAG,
3714 "callback not found for " + getCallbackName(message.what) + " message");
3715 return;
3716 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003717 if (message.what == CALLBACK_UNAVAIL) {
3718 sCallbacks.remove(request);
3719 callback.networkRequest = ALREADY_UNREGISTERED;
3720 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003721 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003722 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003723 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003724 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003725
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003726 switch (message.what) {
3727 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003728 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003729 break;
3730 }
3731 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003732 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3733 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003734 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003735 break;
3736 }
3737 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003738 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003739 break;
3740 }
3741 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003742 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003743 break;
3744 }
3745 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003746 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003747 break;
3748 }
3749 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003750 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3751 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003752 break;
3753 }
3754 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003755 LinkProperties lp = getObject(message, LinkProperties.class);
3756 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003757 break;
3758 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003759 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003760 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003761 break;
3762 }
3763 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003764 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003765 break;
3766 }
junyulaif2c67e42018-08-07 19:50:45 +08003767 case CALLBACK_BLK_CHANGED: {
3768 boolean blocked = message.arg1 != 0;
3769 callback.onBlockedStatusChanged(network, blocked);
3770 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003771 }
3772 }
3773
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003774 private <T> T getObject(Message msg, Class<T> c) {
3775 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003776 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003777 }
3778
Hugo Benichifd44e912017-02-02 17:02:36 +09003779 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003780 synchronized (sCallbacks) {
3781 if (sCallbackHandler == null) {
3782 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003783 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003784 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003785 }
3786 }
3787
Hugo Benichibc4ac972017-02-03 14:18:44 +09003788 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3789 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003790
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003791 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3792 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3793 CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003794 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003795 checkCallbackNotNull(callback);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003796 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3797 throw new IllegalArgumentException("null NetworkCapabilities");
3798 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003799 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003800 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003801 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003802 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003803 if (callback.networkRequest != null
3804 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003805 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3806 // and requests (http://b/20701525).
3807 Log.e(TAG, "NetworkCallback was already registered");
3808 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003809 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003810 Binder binder = new Binder();
Roshan Pius951c0032020-12-22 15:10:42 -08003811 final int callbackFlags = callback.mFlags;
junyulaiad010792021-01-11 16:53:38 +08003812 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003813 request = mService.listenForNetwork(
Roshan Pius951c0032020-12-22 15:10:42 -08003814 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003815 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003816 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003817 request = mService.requestNetwork(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003818 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3819 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003820 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003821 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003822 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003823 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003824 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003825 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003826 } catch (RemoteException e) {
3827 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003828 } catch (ServiceSpecificException e) {
3829 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003830 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003831 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003832 }
3833
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003834 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3835 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3836 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3837 legacyType, handler);
3838 }
3839
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003840 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003841 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003842 *
markchienfac84a22020-03-18 21:16:15 +08003843 * This API is only for use in internal system code that requests networks with legacy type and
3844 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003845 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003846 *
markchiend6eeffd2020-01-14 00:55:21 +08003847 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003848 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3849 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3850 * be a positive value (i.e. >0).
3851 * @param legacyType to specify the network type(#TYPE_*).
3852 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003853 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3854 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003855 *
3856 * @hide
3857 */
markchiend6eeffd2020-01-14 00:55:21 +08003858 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003859 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003860 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003861 int timeoutMs, int legacyType, @NonNull Handler handler,
3862 @NonNull NetworkCallback networkCallback) {
3863 if (legacyType == TYPE_NONE) {
3864 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3865 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003866 CallbackHandler cbHandler = new CallbackHandler(handler);
3867 NetworkCapabilities nc = request.networkCapabilities;
3868 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003869 }
3870
3871 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003872 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003873 *
Chalard Jean01378b62019-08-30 16:27:28 +09003874 * <p>This method will attempt to find the best network that matches the passed
3875 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3876 * criteria. The platform will evaluate which network is the best at its own discretion.
3877 * Throughput, latency, cost per byte, policy, user preference and other considerations
3878 * may be factored in the decision of what is considered the best network.
3879 *
3880 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3881 * matching this request, while always attempting to match the request to a better network if
3882 * possible. If a better match is found, the platform will switch this request to the now-best
3883 * network and inform the app of the newly best network by invoking
3884 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3885 * will not try to maintain any other network than the best one currently matching the request:
3886 * a network not matching any network request may be disconnected at any time.
3887 *
3888 * <p>For example, an application could use this method to obtain a connected cellular network
3889 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3890 * radio to consume additional power. Or, an application could inform the system that it wants
3891 * a network supporting sending MMSes and have the system let it know about the currently best
3892 * MMS-supporting network through the provided {@link NetworkCallback}.
3893 *
3894 * <p>The status of the request can be followed by listening to the various callbacks described
3895 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3896 * used to direct traffic to the network (although accessing some networks may be subject to
3897 * holding specific permissions). Callers will learn about the specific characteristics of the
3898 * network through
3899 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3900 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3901 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3902 * matching the request at any given time; therefore when a better network matching the request
3903 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3904 * with the new network after which no further updates are given about the previously-best
3905 * network, unless it becomes the best again at some later time. All callbacks are invoked
3906 * in order on the same thread, which by default is a thread created by the framework running
3907 * in the app.
3908 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3909 * callbacks are invoked.
3910 *
3911 * <p>This{@link NetworkRequest} will live until released via
3912 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3913 * which point the system may let go of the network at any time.
3914 *
3915 * <p>A version of this method which takes a timeout is
3916 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3917 * wait for a limited amount of time for the network to become unavailable.
3918 *
Paul Jensenee52d232015-06-16 15:11:58 -04003919 * <p>It is presently unsupported to request a network with mutable
3920 * {@link NetworkCapabilities} such as
3921 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3922 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3923 * as these {@code NetworkCapabilities} represent states that a particular
3924 * network may never attain, and whether a network will attain these states
3925 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003926 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003927 *
3928 * <p>This method requires the caller to hold either the
3929 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3930 * or the ability to modify system settings as determined by
3931 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003932 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003933 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3934 * number of outstanding requests to 100 per app (identified by their UID), shared with
3935 * all variants of this method, of {@link #registerNetworkCallback} as well as
3936 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3937 * Requesting a network with this method will count toward this limit. If this limit is
3938 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3939 * make sure to unregister the callbacks with
3940 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3941 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003942 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003943 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3944 * the callback must not be shared - it uniquely specifies this request.
3945 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003946 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3947 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003948 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003949 */
Chalard Jean158702d2019-01-07 19:26:34 +09003950 public void requestNetwork(@NonNull NetworkRequest request,
3951 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003952 requestNetwork(request, networkCallback, getDefaultHandler());
3953 }
3954
3955 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003956 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichifd44e912017-02-02 17:02:36 +09003957 *
Chalard Jean01378b62019-08-30 16:27:28 +09003958 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3959 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003960 *
Chalard Jean01378b62019-08-30 16:27:28 +09003961 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003962 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3963 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003964 *
3965 * @param request {@link NetworkRequest} describing this request.
3966 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3967 * the callback must not be shared - it uniquely specifies this request.
3968 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003969 */
Chalard Jean158702d2019-01-07 19:26:34 +09003970 public void requestNetwork(@NonNull NetworkRequest request,
3971 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003972 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003973 NetworkCapabilities nc = request.networkCapabilities;
3974 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003975 }
3976
3977 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003978 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohenf67bde92017-03-01 12:47:28 -08003979 * by a timeout.
3980 *
3981 * This function behaves identically to the non-timed-out version
3982 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3983 * is not found within the given time (in milliseconds) the
3984 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3985 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3986 * not have to be released if timed-out (it is automatically released). Unregistering a
3987 * request that timed out is not an error.
3988 *
3989 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3990 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3991 * for that purpose. Calling this method will attempt to bring up the requested network.
3992 *
Chalard Jean01378b62019-08-30 16:27:28 +09003993 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003994 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3995 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003996 *
3997 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003998 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3999 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08004000 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4001 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4002 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08004003 */
Chalard Jean158702d2019-01-07 19:26:34 +09004004 public void requestNetwork(@NonNull NetworkRequest request,
4005 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09004006 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08004007 NetworkCapabilities nc = request.networkCapabilities;
4008 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4009 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09004010 }
4011
Hugo Benichifd44e912017-02-02 17:02:36 +09004012 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004013 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichifd44e912017-02-02 17:02:36 +09004014 * by a timeout.
4015 *
Chalard Jean01378b62019-08-30 16:27:28 +09004016 * This method behaves identically to
4017 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4018 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08004019 *
Chalard Jean01378b62019-08-30 16:27:28 +09004020 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004021 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4022 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09004023 *
4024 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08004025 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4026 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09004027 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004028 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4029 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004030 */
Chalard Jean158702d2019-01-07 19:26:34 +09004031 public void requestNetwork(@NonNull NetworkRequest request,
4032 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09004033 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09004034 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08004035 NetworkCapabilities nc = request.networkCapabilities;
4036 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004037 }
4038
4039 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004040 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004041 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004042 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08004043 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04004044 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4045 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004046 */
Erik Kline8a826212014-11-19 12:12:24 +09004047 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004048
4049 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004050 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004051 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004052 * {@link android.content.Intent#getParcelableExtra(String)}.
4053 */
Erik Kline8a826212014-11-19 12:12:24 +09004054 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004055
4056
4057 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004058 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004059 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004060 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004061 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004062 * the request may outlive the calling application and get called back when a suitable
4063 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004064 * <p>
4065 * The operation is an Intent broadcast that goes to a broadcast receiver that
4066 * you registered with {@link Context#registerReceiver} or through the
4067 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4068 * <p>
4069 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09004070 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4071 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004072 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004073 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004074 * Intent to reserve the network or it will be released shortly after the Intent
4075 * is processed.
4076 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04004077 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004078 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004079 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004080 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004081 * The request may be released normally by calling
4082 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04004083 * <p>It is presently unsupported to request a network with either
4084 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4085 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4086 * as these {@code NetworkCapabilities} represent states that a particular
4087 * network may never attain, and whether a network will attain these states
4088 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09004089 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004090 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004091 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4092 * number of outstanding requests to 100 per app (identified by their UID), shared with
4093 * all variants of this method, of {@link #registerNetworkCallback} as well as
4094 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4095 * Requesting a network with this method will count toward this limit. If this limit is
4096 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4097 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4098 * or {@link #releaseNetworkRequest(PendingIntent)}.
4099 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004100 * <p>This method requires the caller to hold either the
4101 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4102 * or the ability to modify system settings as determined by
4103 * {@link android.provider.Settings.System#canWrite}.</p>
4104 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004105 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004106 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004107 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004108 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004109 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4110 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004111 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004112 */
Chalard Jean158702d2019-01-07 19:26:34 +09004113 public void requestNetwork(@NonNull NetworkRequest request,
4114 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004115 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004116 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004117 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004118 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004119 request.networkCapabilities, operation, mContext.getOpPackageName(),
4120 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004121 } catch (RemoteException e) {
4122 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004123 } catch (ServiceSpecificException e) {
4124 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004125 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004126 }
4127
4128 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004129 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4130 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004131 * This method has the same behavior as
4132 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004133 * releasing network resources and disconnecting.
4134 *
4135 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4136 * PendingIntent passed to
4137 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4138 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4139 */
Chalard Jean158702d2019-01-07 19:26:34 +09004140 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004141 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004142 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004143 try {
4144 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004145 } catch (RemoteException e) {
4146 throw e.rethrowFromSystemServer();
4147 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004148 }
4149
Hugo Benichibc1104b2017-05-09 15:19:01 +09004150 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004151 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004152 }
4153
4154 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004155 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004156 }
4157
4158 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004159 if (timeoutMs <= 0) {
4160 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4161 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004162 }
4163
4164 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004165 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004166 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004167 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4168 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004169 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004170 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4171 * number of outstanding requests to 100 per app (identified by their UID), shared with
4172 * all variants of this method, of {@link #requestNetwork} as well as
4173 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4174 * Requesting a network with this method will count toward this limit. If this limit is
4175 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4176 * make sure to unregister the callbacks with
4177 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4178 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004179 * @param request {@link NetworkRequest} describing this request.
4180 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4181 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004182 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004183 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004184 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004185 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004186 public void registerNetworkCallback(@NonNull NetworkRequest request,
4187 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004188 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4189 }
4190
4191 /**
4192 * Registers to receive notifications about all networks which satisfy the given
4193 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004194 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4195 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004196 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004197 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4198 * number of outstanding requests to 100 per app (identified by their UID), shared with
4199 * all variants of this method, of {@link #requestNetwork} as well as
4200 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4201 * Requesting a network with this method will count toward this limit. If this limit is
4202 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4203 * make sure to unregister the callbacks with
4204 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4205 *
4206 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004207 * @param request {@link NetworkRequest} describing this request.
4208 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4209 * networks change state.
4210 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004211 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004212 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004213 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004214 public void registerNetworkCallback(@NonNull NetworkRequest request,
4215 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004216 CallbackHandler cbHandler = new CallbackHandler(handler);
4217 NetworkCapabilities nc = request.networkCapabilities;
4218 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004219 }
4220
4221 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004222 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4223 * {@link NetworkRequest}.
4224 *
4225 * This function behaves identically to the version that takes a NetworkCallback, but instead
4226 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4227 * the request may outlive the calling application and get called back when a suitable
4228 * network is found.
4229 * <p>
4230 * The operation is an Intent broadcast that goes to a broadcast receiver that
4231 * you registered with {@link Context#registerReceiver} or through the
4232 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4233 * <p>
4234 * The operation Intent is delivered with two extras, a {@link Network} typed
4235 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4236 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4237 * the original requests parameters.
4238 * <p>
4239 * If there is already a request for this Intent registered (with the equality of
4240 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4241 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4242 * <p>
4243 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004244 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004245 *
4246 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4247 * number of outstanding requests to 100 per app (identified by their UID), shared with
4248 * all variants of this method, of {@link #requestNetwork} as well as
4249 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4250 * Requesting a network with this method will count toward this limit. If this limit is
4251 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4252 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4253 * or {@link #releaseNetworkRequest(PendingIntent)}.
4254 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004255 * @param request {@link NetworkRequest} describing this request.
4256 * @param operation Action to perform when the network is available (corresponds
4257 * to the {@link NetworkCallback#onAvailable} call. Typically
4258 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004259 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004260 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004261 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004262 public void registerNetworkCallback(@NonNull NetworkRequest request,
4263 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004264 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004265 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004266 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004267 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004268 request.networkCapabilities, operation, mContext.getOpPackageName(),
4269 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004270 } catch (RemoteException e) {
4271 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004272 } catch (ServiceSpecificException e) {
4273 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004274 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004275 }
4276
4277 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004278 * Registers to receive notifications about changes in the application's default network. This
4279 * may be a physical network or a virtual network, such as a VPN that applies to the
4280 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004281 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004282 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004283 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4284 * number of outstanding requests to 100 per app (identified by their UID), shared with
4285 * all variants of this method, of {@link #requestNetwork} as well as
4286 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4287 * Requesting a network with this method will count toward this limit. If this limit is
4288 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4289 * make sure to unregister the callbacks with
4290 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4291 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004292 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004293 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004294 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004295 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004296 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004297 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004298 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004299 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4300 }
4301
4302 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004303 * Registers to receive notifications about changes in the application's default network. This
4304 * may be a physical network or a virtual network, such as a VPN that applies to the
4305 * application. The callbacks will continue to be called until either the application exits or
4306 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4307 *
4308 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4309 * number of outstanding requests to 100 per app (identified by their UID), shared with
4310 * all variants of this method, of {@link #requestNetwork} as well as
4311 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4312 * Requesting a network with this method will count toward this limit. If this limit is
4313 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4314 * make sure to unregister the callbacks with
4315 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4316 *
4317 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4318 * application's default network changes.
4319 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4320 * @throws RuntimeException if the app already has too many callbacks registered.
4321 */
4322 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4323 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4324 @NonNull Handler handler) {
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004325 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4326 }
4327
4328 /**
4329 * Registers to receive notifications about changes in the default network for the specified
4330 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4331 * UID. The callbacks will continue to be called until either the application exits or
4332 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4333 *
4334 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4335 * number of outstanding requests to 100 per app (identified by their UID), shared with
4336 * all variants of this method, of {@link #requestNetwork} as well as
4337 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4338 * Requesting a network with this method will count toward this limit. If this limit is
4339 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4340 * make sure to unregister the callbacks with
4341 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4342 *
4343 * @param uid the UID for which to track default network changes.
4344 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4345 * UID's default network changes.
4346 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4347 * @throws RuntimeException if the app already has too many callbacks registered.
4348 * @hide
4349 */
Lorenzo Colitti92ed8b92021-03-22 18:23:21 +09004350 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004351 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4352 @RequiresPermission(anyOf = {
4353 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4354 android.Manifest.permission.NETWORK_SETTINGS})
4355 public void registerDefaultNetworkCallbackAsUid(int uid,
4356 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004357 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004358 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004359 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4360 }
4361
4362 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004363 * Registers to receive notifications about changes in the system default network. The callbacks
4364 * will continue to be called until either the application exits or
4365 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004366 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004367 * This method should not be used to determine networking state seen by applications, because in
4368 * many cases, most or even all application traffic may not use the default network directly,
4369 * and traffic from different applications may go on different networks by default. As an
4370 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4371 * and not onto the system default network. Applications or system components desiring to do
4372 * determine network state as seen by applications should use other methods such as
4373 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4374 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004375 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4376 * number of outstanding requests to 100 per app (identified by their UID), shared with
4377 * all variants of this method, of {@link #requestNetwork} as well as
4378 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4379 * Requesting a network with this method will count toward this limit. If this limit is
4380 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4381 * make sure to unregister the callbacks with
4382 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4383 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004384 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4385 * system default network changes.
4386 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004387 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004388 *
4389 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004390 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004391 @SystemApi(client = MODULE_LIBRARIES)
4392 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4393 @RequiresPermission(anyOf = {
4394 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4395 android.Manifest.permission.NETWORK_SETTINGS})
4396 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004397 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004398 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004399 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004400 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004401 }
4402
4403 /**
junyulai8eb13a22021-03-15 11:48:48 +08004404 * Registers to receive notifications about the best matching network which satisfy the given
4405 * {@link NetworkRequest}. The callbacks will continue to be called until
4406 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4407 * called.
4408 *
4409 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4410 * number of outstanding requests to 100 per app (identified by their UID), shared with
4411 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4412 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4413 * Requesting a network with this method will count toward this limit. If this limit is
4414 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4415 * make sure to unregister the callbacks with
4416 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4417 *
4418 *
4419 * @param request {@link NetworkRequest} describing this request.
4420 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4421 * networks change state.
4422 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4423 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai7514e312021-03-05 15:51:17 +08004424 */
junyulai7514e312021-03-05 15:51:17 +08004425 @SuppressLint("ExecutorRegistration")
4426 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4427 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4428 final NetworkCapabilities nc = request.networkCapabilities;
4429 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai1b1c8742021-03-12 20:05:08 +08004430 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai7514e312021-03-05 15:51:17 +08004431 }
4432
4433 /**
fenglub00f4882015-04-21 17:12:05 -07004434 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4435 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4436 * network connection for updated bandwidth information. The caller will be notified via
4437 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004438 * method assumes that the caller has previously called
4439 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4440 * changes.
fenglu3f357402015-03-20 11:29:56 -07004441 *
fengluea2d9282015-04-27 14:28:04 -07004442 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004443 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004444 */
Chalard Jean158702d2019-01-07 19:26:34 +09004445 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004446 try {
fenglub00f4882015-04-21 17:12:05 -07004447 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004448 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004449 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004450 }
4451 }
4452
4453 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004454 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004455 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4456 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4457 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004458 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4459 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004460 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004461 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4462 * triggering it as soon as this call returns.
4463 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004464 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004465 */
Chalard Jean158702d2019-01-07 19:26:34 +09004466 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004467 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004468 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004469 final List<NetworkRequest> reqs = new ArrayList<>();
4470 // Find all requests associated to this callback and stop callback triggers immediately.
4471 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4472 synchronized (sCallbacks) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004473 if (networkCallback.networkRequest == null) {
4474 throw new IllegalArgumentException("NetworkCallback was not registered");
4475 }
Etan Cohen6cb65992019-04-16 15:07:55 -07004476 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4477 Log.d(TAG, "NetworkCallback was already unregistered");
4478 return;
4479 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004480 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4481 if (e.getValue() == networkCallback) {
4482 reqs.add(e.getKey());
4483 }
4484 }
4485 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4486 for (NetworkRequest r : reqs) {
4487 try {
4488 mService.releaseNetworkRequest(r);
4489 } catch (RemoteException e) {
4490 throw e.rethrowFromSystemServer();
4491 }
4492 // Only remove mapping if rpc was successful.
4493 sCallbacks.remove(r);
4494 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004495 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004496 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004497 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004498
4499 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004500 * Unregisters a callback previously registered via
4501 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4502 *
4503 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4504 * PendingIntent passed to
4505 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4506 * Cannot be null.
4507 */
Chalard Jean158702d2019-01-07 19:26:34 +09004508 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004509 releaseNetworkRequest(operation);
4510 }
4511
4512 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004513 * Informs the system whether it should switch to {@code network} regardless of whether it is
4514 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4515 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4516 * the system default network regardless of any other network that's currently connected. If
4517 * {@code always} is true, then the choice is remembered, so that the next time the user
4518 * connects to this network, the system will switch to it.
4519 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004520 * @param network The network to accept.
4521 * @param accept Whether to accept the network even if unvalidated.
4522 * @param always Whether to remember this choice in the future.
4523 *
4524 * @hide
4525 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004526 @SystemApi(client = MODULE_LIBRARIES)
4527 @RequiresPermission(anyOf = {
4528 android.Manifest.permission.NETWORK_SETTINGS,
4529 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4530 android.Manifest.permission.NETWORK_STACK,
4531 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4532 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004533 try {
4534 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004535 } catch (RemoteException e) {
4536 throw e.rethrowFromSystemServer();
4537 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004538 }
4539
4540 /**
lucaslin2240ef62019-03-12 13:08:03 +08004541 * Informs the system whether it should consider the network as validated even if it only has
4542 * partial connectivity. If {@code accept} is true, then the network will be considered as
4543 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4544 * is remembered, so that the next time the user connects to this network, the system will
4545 * switch to it.
4546 *
4547 * @param network The network to accept.
4548 * @param accept Whether to consider the network as validated even if it has partial
4549 * connectivity.
4550 * @param always Whether to remember this choice in the future.
4551 *
4552 * @hide
4553 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004554 @SystemApi(client = MODULE_LIBRARIES)
4555 @RequiresPermission(anyOf = {
4556 android.Manifest.permission.NETWORK_SETTINGS,
4557 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4558 android.Manifest.permission.NETWORK_STACK,
4559 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4560 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4561 boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004562 try {
4563 mService.setAcceptPartialConnectivity(network, accept, always);
4564 } catch (RemoteException e) {
4565 throw e.rethrowFromSystemServer();
4566 }
4567 }
4568
4569 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004570 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4571 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4572 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4573 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4574 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004575 * @param network The network to accept.
4576 *
4577 * @hide
4578 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004579 @SystemApi(client = MODULE_LIBRARIES)
4580 @RequiresPermission(anyOf = {
4581 android.Manifest.permission.NETWORK_SETTINGS,
4582 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4583 android.Manifest.permission.NETWORK_STACK,
4584 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4585 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004586 try {
4587 mService.setAvoidUnvalidated(network);
4588 } catch (RemoteException e) {
4589 throw e.rethrowFromSystemServer();
4590 }
4591 }
4592
4593 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004594 * Requests that the system open the captive portal app on the specified network.
4595 *
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004596 * <p>This is to be used on networks where a captive portal was detected, as per
4597 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4598 *
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004599 * @param network The network to log into.
4600 *
4601 * @hide
4602 */
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004603 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4604 @RequiresPermission(anyOf = {
4605 android.Manifest.permission.NETWORK_SETTINGS,
4606 android.Manifest.permission.NETWORK_STACK,
4607 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4608 })
4609 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004610 try {
4611 mService.startCaptivePortalApp(network);
4612 } catch (RemoteException e) {
4613 throw e.rethrowFromSystemServer();
4614 }
4615 }
4616
4617 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004618 * Requests that the system open the captive portal app with the specified extras.
4619 *
4620 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4621 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004622 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004623 * @param appExtras Extras to include in the app start intent.
4624 * @hide
4625 */
4626 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004627 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004628 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004629 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004630 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004631 } catch (RemoteException e) {
4632 throw e.rethrowFromSystemServer();
4633 }
4634 }
4635
4636 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004637 * Determine whether the device is configured to avoid bad wifi.
4638 * @hide
4639 */
4640 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004641 @RequiresPermission(anyOf = {
4642 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4643 android.Manifest.permission.NETWORK_STACK})
4644 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004645 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004646 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004647 } catch (RemoteException e) {
4648 throw e.rethrowFromSystemServer();
4649 }
4650 }
4651
4652 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004653 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4654 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004655 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4656 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004657 *
4658 * An example of such an operation might be a time-sensitive foreground activity, such as a
4659 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4660 */
4661 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4662
4663 /**
4664 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4665 * a backup channel for traffic that is primarily going over another network.
4666 *
4667 * An example might be maintaining backup connections to peers or servers for the purpose of
4668 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4669 * on backup paths should be negligible compared to the traffic on the main path.
4670 */
4671 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4672
4673 /**
4674 * It is acceptable to use metered data to improve network latency and performance.
4675 */
4676 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4677
4678 /**
4679 * Return value to use for unmetered networks. On such networks we currently set all the flags
4680 * to true.
4681 * @hide
4682 */
4683 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4684 MULTIPATH_PREFERENCE_HANDOVER |
4685 MULTIPATH_PREFERENCE_RELIABILITY |
4686 MULTIPATH_PREFERENCE_PERFORMANCE;
4687
4688 /** @hide */
4689 @Retention(RetentionPolicy.SOURCE)
4690 @IntDef(flag = true, value = {
4691 MULTIPATH_PREFERENCE_HANDOVER,
4692 MULTIPATH_PREFERENCE_RELIABILITY,
4693 MULTIPATH_PREFERENCE_PERFORMANCE,
4694 })
4695 public @interface MultipathPreference {
4696 }
4697
4698 /**
4699 * Provides a hint to the calling application on whether it is desirable to use the
4700 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4701 * for multipath data transfer on this network when it is not the system default network.
4702 * Applications desiring to use multipath network protocols should call this method before
4703 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004704 *
4705 * @param network The network on which the application desires to use multipath data.
4706 * If {@code null}, this method will return the a preference that will generally
4707 * apply to metered networks.
4708 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4709 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004710 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004711 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004712 try {
4713 return mService.getMultipathPreference(network);
4714 } catch (RemoteException e) {
4715 throw e.rethrowFromSystemServer();
4716 }
4717 }
4718
4719 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004720 * Resets all connectivity manager settings back to factory defaults.
4721 * @hide
4722 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004723 @SystemApi(client = MODULE_LIBRARIES)
4724 @RequiresPermission(anyOf = {
4725 android.Manifest.permission.NETWORK_SETTINGS,
4726 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scott0f835ac2015-03-30 13:17:11 -07004727 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004728 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004729 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004730 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004731 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004732 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004733 }
4734 }
4735
4736 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004737 * Binds the current process to {@code network}. All Sockets created in the future
4738 * (and not explicitly bound via a bound SocketFactory from
4739 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4740 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4741 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4742 * work and all host name resolutions will fail. This is by design so an application doesn't
4743 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4744 * To clear binding pass {@code null} for {@code network}. Using individually bound
4745 * Sockets created by Network.getSocketFactory().createSocket() and
4746 * performing network-specific host name resolutions via
4747 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004748 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004749 *
4750 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4751 * the current binding.
4752 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4753 */
Chalard Jean158702d2019-01-07 19:26:34 +09004754 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004755 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004756 // instantiated.
4757 return setProcessDefaultNetwork(network);
4758 }
4759
4760 /**
4761 * Binds the current process to {@code network}. All Sockets created in the future
4762 * (and not explicitly bound via a bound SocketFactory from
4763 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4764 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4765 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4766 * work and all host name resolutions will fail. This is by design so an application doesn't
4767 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4768 * To clear binding pass {@code null} for {@code network}. Using individually bound
4769 * Sockets created by Network.getSocketFactory().createSocket() and
4770 * performing network-specific host name resolutions via
4771 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4772 * {@code setProcessDefaultNetwork}.
4773 *
4774 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4775 * the current binding.
4776 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4777 * @deprecated This function can throw {@link IllegalStateException}. Use
4778 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4779 * is a direct replacement.
4780 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004781 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004782 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004783 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004784 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4785
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004786 if (netId != NETID_UNSET) {
4787 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004788 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004789
4790 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4791 return false;
4792 }
4793
4794 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004795 // Set HTTP proxy system properties to match network.
4796 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004797 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004798 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004799 } catch (SecurityException e) {
4800 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4801 Log.e(TAG, "Can't set proxy properties", e);
4802 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004803 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANe1b04f62021-03-18 23:27:19 +09004804 InetAddressCompat.clearDnsCache();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004805 // Must flush socket pool as idle sockets will be bound to previous network and may
4806 // cause subsequent fetches to be performed on old network.
4807 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004808 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004809
4810 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004811 }
4812
4813 /**
4814 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004815 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004816 *
4817 * @return {@code Network} to which this process is bound, or {@code null}.
4818 */
Chalard Jean158702d2019-01-07 19:26:34 +09004819 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004820 public Network getBoundNetworkForProcess() {
4821 // Forcing callers to call thru non-static function ensures ConnectivityManager
4822 // instantiated.
4823 return getProcessDefaultNetwork();
4824 }
4825
4826 /**
4827 * Returns the {@link Network} currently bound to this process via
4828 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4829 *
4830 * @return {@code Network} to which this process is bound, or {@code null}.
4831 * @deprecated Using this function can lead to other functions throwing
4832 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4833 * {@code getBoundNetworkForProcess} is a direct replacement.
4834 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004835 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004836 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004837 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004838 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004839 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004840 return new Network(netId);
4841 }
4842
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004843 private void unsupportedStartingFrom(int version) {
4844 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004845 // The getApplicationInfo() call we make below is not supported in system context. Let
4846 // the call through here, and rely on the fact that ConnectivityService will refuse to
4847 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004848 return;
4849 }
4850
4851 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4852 throw new UnsupportedOperationException(
4853 "This method is not supported in target SDK version " + version + " and above");
4854 }
4855 }
4856
4857 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4858 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004859 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004860 // remove these exemptions. Note that this check is not secure, and apps can still access these
4861 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4862 // so is unsupported and may break in the future. http://b/22728205
4863 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004864 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004865 }
4866
Paul Jensen8cdda642014-05-29 10:12:39 -04004867 /**
4868 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004869 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004870 *
4871 * @param network The {@link Network} to bind host resolutions from the current process to, or
4872 * {@code null} to clear the current binding.
4873 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4874 * @hide
4875 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4876 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004877 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004878 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004879 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004880 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004881 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004882 }
Felipe Leme30511352016-01-22 09:44:57 -08004883
4884 /**
4885 * Device is not restricting metered network activity while application is running on
4886 * background.
4887 */
4888 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4889
4890 /**
4891 * Device is restricting metered network activity while application is running on background,
4892 * but application is allowed to bypass it.
4893 * <p>
4894 * In this state, application should take action to mitigate metered network access.
4895 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4896 */
4897 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4898
4899 /**
4900 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004901 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004902 * In this state, application should not try to use the network while running on background,
4903 * because it would be denied.
4904 */
4905 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4906
Felipe Lemed34c9af2016-01-27 14:46:39 -08004907 /**
4908 * A change in the background metered network activity restriction has occurred.
4909 * <p>
4910 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4911 * applies to them.
4912 * <p>
4913 * This is only sent to registered receivers, not manifest receivers.
4914 */
4915 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4916 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4917 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4918
Felipe Leme7e4c1852016-01-25 11:48:04 -08004919 /** @hide */
4920 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004921 @IntDef(flag = false, value = {
4922 RESTRICT_BACKGROUND_STATUS_DISABLED,
4923 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4924 RESTRICT_BACKGROUND_STATUS_ENABLED,
4925 })
Felipe Leme30511352016-01-22 09:44:57 -08004926 public @interface RestrictBackgroundStatus {
4927 }
4928
Felipe Leme30511352016-01-22 09:44:57 -08004929 /**
4930 * Determines if the calling application is subject to metered network restrictions while
4931 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004932 *
4933 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4934 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4935 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004936 */
4937 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4938 try {
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004939 return mService.getRestrictBackgroundStatusByCaller();
Felipe Leme30511352016-01-22 09:44:57 -08004940 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004941 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004942 }
4943 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004944
4945 /**
4946 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004947 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4948 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004949 *
4950 * @return Hash of network watchlist config file. Null if config does not exist.
4951 */
Chalard Jean158702d2019-01-07 19:26:34 +09004952 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004953 public byte[] getNetworkWatchlistConfigHash() {
4954 try {
4955 return mService.getNetworkWatchlistConfigHash();
4956 } catch (RemoteException e) {
4957 Log.e(TAG, "Unable to get watchlist config hash");
4958 throw e.rethrowFromSystemServer();
4959 }
4960 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004961
4962 /**
4963 * Returns the {@code uid} of the owner of a network connection.
4964 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004965 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4966 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004967 * @param local The local {@link InetSocketAddress} of a connection.
4968 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004969 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004970 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4971 * android.os.Process#INVALID_UID} if the connection is not found.
4972 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4973 * user.
4974 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004975 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004976 public int getConnectionOwnerUid(
4977 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004978 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4979 try {
4980 return mService.getConnectionOwnerUid(connectionInfo);
4981 } catch (RemoteException e) {
4982 throw e.rethrowFromSystemServer();
4983 }
4984 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004985
4986 private void printStackTrace() {
4987 if (DEBUG) {
4988 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4989 final StringBuffer sb = new StringBuffer();
4990 for (int i = 3; i < callStack.length; i++) {
4991 final String stackTrace = callStack[i].toString();
4992 if (stackTrace == null || stackTrace.contains("android.os")) {
4993 break;
4994 }
4995 sb.append(" [").append(stackTrace).append("]");
4996 }
4997 Log.d(TAG, "StackLog:" + sb.toString());
4998 }
4999 }
Cody Kestingf53a0752020-04-15 12:33:28 -07005000
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09005001 /** @hide */
5002 public TestNetworkManager startOrGetTestNetworkManager() {
5003 final IBinder tnBinder;
5004 try {
5005 tnBinder = mService.startOrGetTestNetworkService();
5006 } catch (RemoteException e) {
5007 throw e.rethrowFromSystemServer();
5008 }
5009
5010 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5011 }
5012
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09005013 /** @hide */
5014 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5015 return new ConnectivityDiagnosticsManager(mContext, mService);
5016 }
5017
Cody Kestingf53a0752020-04-15 12:33:28 -07005018 /**
5019 * Simulates a Data Stall for the specified Network.
5020 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09005021 * <p>This method should only be used for tests.
5022 *
Cody Kestingf53a0752020-04-15 12:33:28 -07005023 * <p>The caller must be the owner of the specified Network.
5024 *
5025 * @param detectionMethod The detection method used to identify the Data Stall.
5026 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
5027 * @param network The Network for which a Data Stall is being simluated.
5028 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5029 * @throws SecurityException if the caller is not the owner of the given network.
5030 * @hide
5031 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09005032 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07005033 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5034 android.Manifest.permission.NETWORK_STACK})
5035 public void simulateDataStall(int detectionMethod, long timestampMillis,
5036 @NonNull Network network, @NonNull PersistableBundle extras) {
5037 try {
5038 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5039 } catch (RemoteException e) {
5040 e.rethrowFromSystemServer();
5041 }
5042 }
James Mattis356a8792020-10-28 21:48:54 -07005043
Daniel Brightf9e945b2020-06-15 16:10:01 -07005044 @NonNull
5045 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5046
5047 /**
5048 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5049 * receive available QoS events related to the {@link Network} and local ip + port
5050 * specified within socketInfo.
5051 * <p/>
5052 * The same {@link QosCallback} must be unregistered before being registered a second time,
5053 * otherwise {@link QosCallbackRegistrationException} is thrown.
5054 * <p/>
5055 * This API does not, in itself, require any permission if called with a network that is not
5056 * restricted. However, the underlying implementation currently only supports the IMS network,
5057 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5058 * useful, because they'd never be called back on networks that they would have access to.
5059 *
5060 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5061 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5062 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5063 * @throws RuntimeException if the app already has too many callbacks registered.
5064 *
5065 * Exceptions after the time of registration is passed through
5066 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5067 *
5068 * @param socketInfo the socket information used to match QoS events
Daniel Brightf9e945b2020-06-15 16:10:01 -07005069 * @param executor The executor on which the callback will be invoked. The provided
5070 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright7ee5f522021-03-10 11:51:50 -08005071 * callbacks cannot be guaranteed.onQosCallbackRegistered
5072 * @param callback receives qos events that satisfy socketInfo
Daniel Brightf9e945b2020-06-15 16:10:01 -07005073 *
5074 * @hide
5075 */
5076 @SystemApi
5077 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright7ee5f522021-03-10 11:51:50 -08005078 @CallbackExecutor @NonNull final Executor executor,
5079 @NonNull final QosCallback callback) {
Daniel Brightf9e945b2020-06-15 16:10:01 -07005080 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07005081 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright7ee5f522021-03-10 11:51:50 -08005082 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07005083
5084 try {
5085 synchronized (mQosCallbackConnections) {
5086 if (getQosCallbackConnection(callback) == null) {
5087 final QosCallbackConnection connection =
5088 new QosCallbackConnection(this, callback, executor);
5089 mQosCallbackConnections.add(connection);
5090 mService.registerQosSocketCallback(socketInfo, connection);
5091 } else {
5092 Log.e(TAG, "registerQosCallback: Callback already registered");
5093 throw new QosCallbackRegistrationException();
5094 }
5095 }
5096 } catch (final RemoteException e) {
5097 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5098
5099 // The same unregister method method is called for consistency even though nothing
5100 // will be sent to the ConnectivityService since the callback was never successfully
5101 // registered.
5102 unregisterQosCallback(callback);
5103 e.rethrowFromSystemServer();
5104 } catch (final ServiceSpecificException e) {
5105 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5106 unregisterQosCallback(callback);
5107 throw convertServiceException(e);
5108 }
5109 }
5110
5111 /**
5112 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5113 * events once unregistered and can be registered a second time.
5114 * <p/>
5115 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5116 *
5117 * @param callback the callback being unregistered
5118 *
5119 * @hide
5120 */
5121 @SystemApi
5122 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5123 Objects.requireNonNull(callback, "The callback must be non-null");
5124 try {
5125 synchronized (mQosCallbackConnections) {
5126 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5127 if (connection != null) {
5128 connection.stopReceivingMessages();
5129 mService.unregisterQosCallback(connection);
5130 mQosCallbackConnections.remove(connection);
5131 } else {
5132 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5133 }
5134 }
5135 } catch (final RemoteException e) {
5136 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5137 e.rethrowFromSystemServer();
5138 }
5139 }
5140
5141 /**
5142 * Gets the connection related to the callback.
5143 *
5144 * @param callback the callback to look up
5145 * @return the related connection
5146 */
5147 @Nullable
5148 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5149 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5150 // Checking by reference here is intentional
5151 if (connection.getCallback() == callback) {
5152 return connection;
5153 }
5154 }
5155 return null;
5156 }
Junyu Laia62493f2021-01-19 11:10:56 +00005157
5158 /**
Roshan Pius951c0032020-12-22 15:10:42 -08005159 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Laia62493f2021-01-19 11:10:56 +00005160 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5161 * be used to request that the system provide a network without causing the network to be
5162 * in the foreground.
5163 *
5164 * <p>This method will attempt to find the best network that matches the passed
5165 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5166 * criteria. The platform will evaluate which network is the best at its own discretion.
5167 * Throughput, latency, cost per byte, policy, user preference and other considerations
5168 * may be factored in the decision of what is considered the best network.
5169 *
5170 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5171 * matching this request, while always attempting to match the request to a better network if
5172 * possible. If a better match is found, the platform will switch this request to the now-best
5173 * network and inform the app of the newly best network by invoking
5174 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5175 * will not try to maintain any other network than the best one currently matching the request:
5176 * a network not matching any network request may be disconnected at any time.
5177 *
5178 * <p>For example, an application could use this method to obtain a connected cellular network
5179 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5180 * radio to consume additional power. Or, an application could inform the system that it wants
5181 * a network supporting sending MMSes and have the system let it know about the currently best
5182 * MMS-supporting network through the provided {@link NetworkCallback}.
5183 *
5184 * <p>The status of the request can be followed by listening to the various callbacks described
5185 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5186 * used to direct traffic to the network (although accessing some networks may be subject to
5187 * holding specific permissions). Callers will learn about the specific characteristics of the
5188 * network through
5189 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5190 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5191 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5192 * matching the request at any given time; therefore when a better network matching the request
5193 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5194 * with the new network after which no further updates are given about the previously-best
5195 * network, unless it becomes the best again at some later time. All callbacks are invoked
5196 * in order on the same thread, which by default is a thread created by the framework running
5197 * in the app.
5198 *
5199 * <p>This{@link NetworkRequest} will live until released via
5200 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5201 * which point the system may let go of the network at any time.
5202 *
5203 * <p>It is presently unsupported to request a network with mutable
5204 * {@link NetworkCapabilities} such as
5205 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5206 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5207 * as these {@code NetworkCapabilities} represent states that a particular
5208 * network may never attain, and whether a network will attain these states
5209 * is unknown prior to bringing up the network so the framework does not
5210 * know how to go about satisfying a request with these capabilities.
5211 *
5212 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5213 * number of outstanding requests to 100 per app (identified by their UID), shared with
5214 * all variants of this method, of {@link #registerNetworkCallback} as well as
5215 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5216 * Requesting a network with this method will count toward this limit. If this limit is
5217 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5218 * make sure to unregister the callbacks with
5219 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5220 *
5221 * @param request {@link NetworkRequest} describing this request.
5222 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5223 * If null, the callback is invoked on the default internal Handler.
5224 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5225 * the callback must not be shared - it uniquely specifies this request.
5226 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5227 * @throws SecurityException if missing the appropriate permissions.
5228 * @throws RuntimeException if the app already has too many callbacks registered.
5229 *
5230 * @hide
5231 */
5232 @SystemApi(client = MODULE_LIBRARIES)
5233 @SuppressLint("ExecutorRegistration")
5234 @RequiresPermission(anyOf = {
5235 android.Manifest.permission.NETWORK_SETTINGS,
5236 android.Manifest.permission.NETWORK_STACK,
5237 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5238 })
5239 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai962bdb82021-03-09 20:49:48 +08005240 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Laia62493f2021-01-19 11:10:56 +00005241 final NetworkCapabilities nc = request.networkCapabilities;
5242 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulai962bdb82021-03-09 20:49:48 +08005243 TYPE_NONE, new CallbackHandler(handler));
Junyu Laia62493f2021-01-19 11:10:56 +00005244 }
James Mattis45d81842021-01-10 14:24:24 -08005245
5246 /**
James Mattis45d81842021-01-10 14:24:24 -08005247 * Used by automotive devices to set the network preferences used to direct traffic at an
5248 * application level as per the given OemNetworkPreferences. An example use-case would be an
5249 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5250 * vehicle via a particular network.
5251 *
5252 * Calling this will overwrite the existing preference.
5253 *
5254 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5255 * @param executor the executor on which listener will be invoked.
5256 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5257 * communicate completion of setOemNetworkPreference(). This will only be
5258 * called once upon successful completion of setOemNetworkPreference().
5259 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5260 * @throws SecurityException if missing the appropriate permissions.
5261 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005262 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005263 */
James Mattisda32cfe2021-01-26 16:23:52 -08005264 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005265 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005266 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005267 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean6010c002021-03-03 16:37:13 +09005268 @Nullable final Runnable listener) {
James Mattis45d81842021-01-10 14:24:24 -08005269 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5270 if (null != listener) {
5271 Objects.requireNonNull(executor, "Executor must be non-null");
5272 }
Chalard Jean6010c002021-03-03 16:37:13 +09005273 final IOnCompleteListener listenerInternal = listener == null ? null :
5274 new IOnCompleteListener.Stub() {
James Mattis45d81842021-01-10 14:24:24 -08005275 @Override
5276 public void onComplete() {
Chalard Jean6010c002021-03-03 16:37:13 +09005277 executor.execute(listener::run);
James Mattis45d81842021-01-10 14:24:24 -08005278 }
5279 };
5280
5281 try {
5282 mService.setOemNetworkPreference(preference, listenerInternal);
5283 } catch (RemoteException e) {
5284 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5285 throw e.rethrowFromSystemServer();
5286 }
5287 }
lucaslin30e70a82021-03-12 00:46:33 +08005288
Chalard Jeanfa45a682021-02-25 17:23:40 +09005289 /**
5290 * Request that a user profile is put by default on a network matching a given preference.
5291 *
5292 * See the documentation for the individual preferences for a description of the supported
5293 * behaviors.
5294 *
5295 * @param profile the profile concerned.
5296 * @param preference the preference for this profile.
5297 * @param executor an executor to execute the listener on. Optional if listener is null.
5298 * @param listener an optional listener to listen for completion of the operation.
5299 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5300 * @throws SecurityException if missing the appropriate permissions.
5301 * @hide
5302 */
Chalard Jean6010c002021-03-03 16:37:13 +09005303 // This function is for establishing per-profile default networking and can only be called by
5304 // the device policy manager, running as the system server. It would make no sense to call it
5305 // on a context for a user because it does not establish a setting on behalf of a user, rather
5306 // it establishes a setting for a user on behalf of the DPM.
5307 @SuppressLint({"UserHandle"})
5308 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09005309 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5310 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5311 @ProfileNetworkPreference final int preference,
5312 @Nullable @CallbackExecutor final Executor executor,
5313 @Nullable final Runnable listener) {
5314 if (null != listener) {
5315 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5316 }
5317 final IOnCompleteListener proxy;
5318 if (null == listener) {
5319 proxy = null;
5320 } else {
5321 proxy = new IOnCompleteListener.Stub() {
5322 @Override
5323 public void onComplete() {
5324 executor.execute(listener::run);
5325 }
5326 };
5327 }
5328 try {
5329 mService.setProfileNetworkPreference(profile, preference, proxy);
5330 } catch (RemoteException e) {
5331 throw e.rethrowFromSystemServer();
5332 }
5333 }
5334
lucaslin30e70a82021-03-12 00:46:33 +08005335 // The first network ID of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005336 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin30e70a82021-03-12 00:46:33 +08005337 // The network ID range of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005338 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin30e70a82021-03-12 00:46:33 +08005339
5340 /**
5341 * Get the network ID range reserved for IPSec tunnel interfaces.
5342 *
5343 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5344 * @hide
5345 */
5346 @SystemApi(client = MODULE_LIBRARIES)
5347 @NonNull
5348 public static Range<Integer> getIpSecNetIdRange() {
5349 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5350 }
lucaslin705c3332021-03-12 17:56:09 +08005351
5352 /**
5353 * Get private DNS mode from settings.
5354 *
lucaslin7abe7e02021-03-17 14:53:35 +08005355 * @param context The Context to query the private DNS mode from settings.
lucaslin705c3332021-03-12 17:56:09 +08005356 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5357 *
5358 * @hide
5359 */
5360 @SystemApi(client = MODULE_LIBRARIES)
5361 @NonNull
5362 @PrivateDnsMode
lucaslin20f04882021-03-16 17:11:14 +08005363 public static String getPrivateDnsMode(@NonNull Context context) {
5364 final ContentResolver cr = context.getContentResolver();
lucaslin705c3332021-03-12 17:56:09 +08005365 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5366 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5367 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5368 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5369 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5370 return mode;
5371 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005372}