blob: 1a5299bb00353d97d1803c6e2b1961bb7dd7e142 [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;
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +000077import com.android.internal.util.Preconditions;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070078
Paul Jensen3e2917c2014-08-27 12:38:45 -040079import libcore.net.event.NetworkEventDispatcher;
80
junyulai7e06ad42019-03-04 22:45:36 +080081import java.io.IOException;
82import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080083import java.lang.annotation.Retention;
84import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090085import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080086import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070087import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080088import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090089import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090090import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080091import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090092import java.util.List;
93import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080094import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080095import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080096import java.util.concurrent.ExecutorService;
97import java.util.concurrent.Executors;
98import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -080099
The Android Open Source Project28527d22009-03-03 19:31:44 -0800100/**
101 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600102 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800103 * <p>
104 * The primary responsibilities of this class are to:
105 * <ol>
106 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
107 * <li>Send broadcast intents when network connectivity changes</li>
108 * <li>Attempt to "fail over" to another network when connectivity to a network
109 * is lost</li>
110 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
111 * state of the available networks</li>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700112 * <li>Provide an API that allows applications to request and select networks for their data
113 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800114 * </ol>
115 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600116@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700117public class ConnectivityManager {
118 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900119 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700120
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700122 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800123 * been established or lost. The NetworkInfo for the affected network is
124 * sent as an extra; it should be consulted to see what kind of
125 * connectivity event occurred.
126 * <p/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800127 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
128 * broadcast if they declare the broadcast receiver in their manifest. Apps
129 * will still receive broadcasts if they register their
130 * {@link android.content.BroadcastReceiver} with
131 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
132 * and that context is still valid.
133 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800134 * If this is a connection that was the result of failing over from a
135 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
136 * set to true.
137 * <p/>
138 * For a loss of connectivity, if the connectivity manager is attempting
139 * to connect (or has already connected) to another network, the
140 * NetworkInfo for the new network is also passed as an extra. This lets
141 * any receivers of the broadcast know that they should not necessarily
142 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800143 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800144 * the failover attempt succeeded (and so there is still overall data
145 * connectivity), or that the failover attempt failed, meaning that all
146 * connectivity has been lost.
147 * <p/>
148 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
149 * is set to {@code true} if there are no connected networks at all.
Chalard Jean52e23962018-02-10 05:33:50 +0900150 *
151 * @deprecated apps should use the more versatile {@link #requestNetwork},
152 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
153 * functions instead for faster and more detailed updates about the network
154 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800156 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900157 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700159
The Android Open Source Project28527d22009-03-03 19:31:44 -0800160 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500161 * The device has connected to a network that has presented a captive
162 * portal, which is blocking Internet connectivity. The user was presented
163 * with a notification that network sign in is required,
164 * and the user invoked the notification's action indicating they
Paul Jensen75e0adb2015-05-22 10:50:39 -0400165 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500166 * facilitate signing in to the network. This action includes a
167 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
168 * the network presenting the captive portal; all communication with the
169 * captive portal must be done using this {@code Network} object.
170 * <p/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400171 * This activity includes a {@link CaptivePortal} extra named
172 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
173 * outcomes of the captive portal sign in to the system:
174 * <ul>
175 * <li> When the app handling this action believes the user has signed in to
176 * the network and the captive portal has been dismissed, the app should
177 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
178 * reevaluate the network. If reevaluation finds the network no longer
179 * subject to a captive portal, the network may become the default active
Chalard Jean9dd11612018-06-04 16:52:49 +0900180 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400181 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500182 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400183 * {@link CaptivePortal#ignoreNetwork}. </li>
184 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500185 */
186 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
187 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
188
189 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800190 * The lookup key for a {@link NetworkInfo} object. Retrieve with
191 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700192 *
Chalard Jean97021a12019-01-11 16:47:53 +0900193 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
194 * can't accurately represent modern network characteristics.
195 * Please obtain information about networks from the {@link NetworkCapabilities}
196 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800197 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700198 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800199 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700200
The Android Open Source Project28527d22009-03-03 19:31:44 -0800201 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700202 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700203 *
204 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900205 * @deprecated The network type is not rich enough to represent the characteristics
206 * of modern networks. Please use {@link NetworkCapabilities} instead,
207 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700208 */
Chalard Jean97021a12019-01-11 16:47:53 +0900209 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700210 public static final String EXTRA_NETWORK_TYPE = "networkType";
211
212 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800213 * The lookup key for a boolean that indicates whether a connect event
214 * is for a network to which the connectivity manager was failing over
215 * following a disconnect on another network.
216 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai9826e7f2018-12-13 12:47:51 +0800217 *
218 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800219 */
junyulai9826e7f2018-12-13 12:47:51 +0800220 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800221 public static final String EXTRA_IS_FAILOVER = "isFailover";
222 /**
223 * The lookup key for a {@link NetworkInfo} object. This is supplied when
224 * there is another network that it may be possible to connect to. Retrieve with
225 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800226 *
227 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800228 */
junyulai9826e7f2018-12-13 12:47:51 +0800229 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
231 /**
232 * The lookup key for a boolean that indicates whether there is a
233 * complete lack of connectivity, i.e., no network is available.
234 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
235 */
236 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
237 /**
238 * The lookup key for a string that indicates why an attempt to connect
239 * to a network failed. The string has no particular structure. It is
240 * intended to be used in notifications presented to users. Retrieve
241 * it with {@link android.content.Intent#getStringExtra(String)}.
242 */
243 public static final String EXTRA_REASON = "reason";
244 /**
245 * The lookup key for a string that provides optionally supplied
246 * extra information about the network state. The information
247 * may be passed up from the lower networking layers, and its
248 * meaning may be specific to a particular network type. Retrieve
249 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800250 *
251 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800252 */
junyulai9826e7f2018-12-13 12:47:51 +0800253 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800254 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700255 /**
256 * The lookup key for an int that provides information about
257 * our connection to the internet at large. 0 indicates no connection,
258 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700259 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700260 * {@hide}
261 */
262 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800263 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400264 * The lookup key for a {@link CaptivePortal} object included with the
265 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
266 * object can be used to either indicate to the system that the captive
267 * portal has been dismissed or that the user does not want to pursue
268 * signing in to captive portal. Retrieve it with
269 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500270 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400271 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700272
273 /**
274 * Key for passing a URL to the captive portal login activity.
275 */
276 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
277
Paul Jensen60df4aa2015-02-27 22:55:47 -0500278 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900279 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
280 * portal login activity.
281 * {@hide}
282 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900283 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900284 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
285 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
286
287 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900288 * Key for passing a user agent string to the captive portal login activity.
289 * {@hide}
290 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900291 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900292 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
293 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
294
295 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700296 * Broadcast action to indicate the change of data activity status
297 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800298 * The network becomes active when data transmission is started, or
299 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700300 * {@hide}
301 */
302 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900303 public static final String ACTION_DATA_ACTIVITY_CHANGE =
304 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700305 /**
306 * The lookup key for an enum that indicates the network device type on which this data activity
307 * change happens.
308 * {@hide}
309 */
310 public static final String EXTRA_DEVICE_TYPE = "deviceType";
311 /**
312 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
313 * it is actively sending or receiving data and {@code false} means it is idle.
314 * {@hide}
315 */
316 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700317 /**
318 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
319 * {@hide}
320 */
321 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700322
323 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800324 * Broadcast Action: The setting for background data usage has changed
325 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
326 * <p>
327 * If an application uses the network in the background, it should listen
328 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700329 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800330 * <p>
331 *
332 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
333 * of background data depends on several combined factors, and
334 * this broadcast is no longer sent. Instead, when background
335 * data is unavailable, {@link #getActiveNetworkInfo()} will now
336 * appear disconnected. During first boot after a platform
337 * upgrade, this broadcast will be sent once if
338 * {@link #getBackgroundDataSetting()} was {@code false} before
339 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800340 */
341 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800342 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800343 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
344 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
345
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700346 /**
347 * Broadcast Action: The network connection may not be good
348 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
349 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
350 * the network and it's condition.
351 * @hide
352 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800353 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100354 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700355 public static final String INET_CONDITION_ACTION =
356 "android.net.conn.INET_CONDITION_ACTION";
357
Robert Greenwalt2034b912009-08-12 16:08:25 -0700358 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800359 * Broadcast Action: A tetherable connection has come or gone.
360 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900361 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
362 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800363 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
364 * the current state of tethering. Each include a list of
365 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800366 * @hide
367 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800368 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000369 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800370 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800371 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800372
373 /**
374 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800375 * gives a String[] listing all the interfaces configured for
376 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800377 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000378 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800379 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800380
381 /**
382 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900383 * gives a String[] listing all the interfaces currently in local-only
384 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800385 */
markchiena0f8fd92019-12-25 19:40:32 +0800386 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900387
388 /**
389 * @hide
390 * gives a String[] listing all the interfaces currently tethered
391 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
392 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000393 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800394 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800395
396 /**
397 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800398 * gives a String[] listing all the interfaces we tried to tether and
399 * failed. Use {@link #getLastTetherError} to find the error code
400 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800401 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000402 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800403 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800404
405 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800406 * Broadcast Action: The captive portal tracker has finished its test.
407 * Sent only while running Setup Wizard, in lieu of showing a user
408 * notification.
409 * @hide
410 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800411 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800412 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
413 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
414 /**
415 * The lookup key for a boolean that indicates whether a captive portal was detected.
416 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
417 * @hide
418 */
419 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
420
421 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900422 * Action used to display a dialog that asks the user whether to connect to a network that is
423 * not validated. This intent is used to start the dialog in settings via startActivity.
424 *
425 * @hide
426 */
427 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
428
429 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900430 * Action used to display a dialog that asks the user whether to avoid a network that is no
431 * longer validated. This intent is used to start the dialog in settings via startActivity.
432 *
433 * @hide
434 */
435 public static final String ACTION_PROMPT_LOST_VALIDATION =
436 "android.net.conn.PROMPT_LOST_VALIDATION";
437
438 /**
lucaslin2240ef62019-03-12 13:08:03 +0800439 * Action used to display a dialog that asks the user whether to stay connected to a network
440 * that has not validated. This intent is used to start the dialog in settings via
441 * startActivity.
442 *
443 * @hide
444 */
445 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
446 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
447
448 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800449 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900450 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800451 * @hide
452 */
markchiena0f8fd92019-12-25 19:40:32 +0800453 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800454
455 /**
456 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900457 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800458 * @hide
459 */
460 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900461 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800462
463 /**
464 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900465 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800466 * @hide
467 */
468 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900469 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800470
471 /**
472 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900473 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800474 * @hide
475 */
476 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900477 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800478
479 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800480 * Wifi P2p tethering type.
481 * Wifi P2p tethering is set through events automatically, and don't
482 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
483 * @hide
484 */
markchiena0f8fd92019-12-25 19:40:32 +0800485 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800486
487 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800488 * Extra used for communicating with the TetherService. Includes the type of tethering to
489 * enable if any.
490 * @hide
491 */
markchien6ae63e52020-01-21 13:11:06 +0800492 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800493
494 /**
495 * Extra used for communicating with the TetherService. Includes the type of tethering for
496 * which to cancel provisioning.
497 * @hide
498 */
markchien6ae63e52020-01-21 13:11:06 +0800499 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800500
501 /**
502 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
503 * provisioning.
504 * @hide
505 */
markchien6ae63e52020-01-21 13:11:06 +0800506 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800507
508 /**
509 * Tells the TetherService to run a provision check now.
510 * @hide
511 */
markchien6ae63e52020-01-21 13:11:06 +0800512 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800513
514 /**
515 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
516 * which will receive provisioning results. Can be left empty.
517 * @hide
518 */
markchien6ae63e52020-01-21 13:11:06 +0800519 public static final String EXTRA_PROVISION_CALLBACK =
520 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800521
522 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800523 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700524 * @hide
525 */
paulhu74357e72020-01-13 16:46:45 +0800526 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700527 public static final int TYPE_NONE = -1;
528
529 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900530 * A Mobile data connection. Devices may support more than one.
531 *
532 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
533 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
534 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700535 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900536 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700537 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900538
Robert Greenwalt2034b912009-08-12 16:08:25 -0700539 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900540 * A WIFI data connection. Devices may support more than one.
541 *
542 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
543 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
544 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700545 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900546 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700547 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900548
Robert Greenwalt2034b912009-08-12 16:08:25 -0700549 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800550 * An MMS-specific Mobile data connection. This network type may use the
551 * same network interface as {@link #TYPE_MOBILE} or it may use a different
552 * one. This is used by applications needing to talk to the carrier's
553 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900554 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900555 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900556 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900557 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700558 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700559 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700560 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900561
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800563 * A SUPL-specific Mobile data connection. This network type may use the
564 * same network interface as {@link #TYPE_MOBILE} or it may use a different
565 * one. This is used by applications needing to talk to the carrier's
566 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900567 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900568 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900569 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900570 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700572 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700573 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900574
Robert Greenwalt2034b912009-08-12 16:08:25 -0700575 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800576 * A DUN-specific Mobile data connection. This network type may use the
577 * same network interface as {@link #TYPE_MOBILE} or it may use a different
578 * one. This is sometimes by the system when setting up an upstream connection
579 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900580 *
581 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
582 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
583 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900585 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700586 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900587
Robert Greenwalt2034b912009-08-12 16:08:25 -0700588 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800589 * A High Priority Mobile data connection. This network type uses the
590 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900591 * is different.
592 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900593 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
594 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
595 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700596 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700597 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700598 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900599
jshbfa81722010-03-11 15:04:43 -0800600 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900601 * A WiMAX data connection.
602 *
603 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
604 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
605 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800606 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900607 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800608 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800609
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800610 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900611 * A Bluetooth data connection.
612 *
613 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
614 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
615 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800616 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900617 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800618 public static final int TYPE_BLUETOOTH = 7;
619
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700620 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800621 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900622 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700623 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900624 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800625 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800626
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700627 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900628 * An Ethernet data connection.
629 *
630 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
631 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
632 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700633 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900634 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800635 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700636
Wink Savilleb7c92c72011-03-12 14:52:01 -0800637 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800638 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900639 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800640 * {@hide}
641 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900642 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900643 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800644 public static final int TYPE_MOBILE_FOTA = 10;
645
646 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800647 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900648 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800649 * {@hide}
650 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900651 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100652 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800653 public static final int TYPE_MOBILE_IMS = 11;
654
655 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800656 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900657 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800658 * {@hide}
659 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900660 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900661 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800662 public static final int TYPE_MOBILE_CBS = 12;
663
repo syncf5de5572011-07-29 23:55:49 -0700664 /**
665 * A Wi-Fi p2p connection. Only requesting processes will have access to
666 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900667 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700668 * {@hide}
669 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900670 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800671 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700672 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800673
Wink Saville512c2202013-07-29 15:00:57 -0700674 /**
675 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900676 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700677 * {@hide}
678 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900679 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100680 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700681 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700682
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900683 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700684 * Emergency PDN connection for emergency services. This
685 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900686 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700687 * {@hide}
688 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900689 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900690 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700691 public static final int TYPE_MOBILE_EMERGENCY = 15;
692
Hui Lu865b70d2014-01-15 11:05:36 -0500693 /**
694 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900695 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500696 * {@hide}
697 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900698 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900699 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500700 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700701
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700702 /**
703 * A virtual network using one or more native bearers.
704 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900705 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700706 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900707 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700708 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500709
Benedict Wongbdfaa482018-11-14 17:40:55 -0800710 /**
711 * A network that is exclusively meant to be used for testing
712 *
713 * @deprecated Use {@link NetworkCapabilities} instead.
714 * @hide
715 */
716 @Deprecated
717 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700718
Chalard Jeanaea539a2020-03-25 01:24:04 +0900719 /**
720 * @deprecated Use {@link NetworkCapabilities} instead.
721 * @hide
722 */
723 @Deprecated
724 @Retention(RetentionPolicy.SOURCE)
725 @IntDef(prefix = { "TYPE_" }, value = {
726 TYPE_NONE,
727 TYPE_MOBILE,
728 TYPE_WIFI,
729 TYPE_MOBILE_MMS,
730 TYPE_MOBILE_SUPL,
731 TYPE_MOBILE_DUN,
732 TYPE_MOBILE_HIPRI,
733 TYPE_WIMAX,
734 TYPE_BLUETOOTH,
735 TYPE_DUMMY,
736 TYPE_ETHERNET,
737 TYPE_MOBILE_FOTA,
738 TYPE_MOBILE_IMS,
739 TYPE_MOBILE_CBS,
740 TYPE_WIFI_P2P,
741 TYPE_MOBILE_IA,
742 TYPE_MOBILE_EMERGENCY,
743 TYPE_PROXY,
744 TYPE_VPN,
745 TYPE_TEST
746 })
747 public @interface LegacyNetworkType {}
748
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900749 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
750 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
751 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
752 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
753 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
754
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700755 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800756 public static final int MAX_RADIO_TYPE = TYPE_TEST;
757
758 /** {@hide} */
759 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800760
Hugo Benichiad353f42017-06-20 14:07:59 +0900761 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
762
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800763 /**
764 * If you want to set the default network preference,you can directly
765 * change the networkAttributes array in framework's config.xml.
766 *
767 * @deprecated Since we support so many more networks now, the single
768 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800769 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800770 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800771 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800772 * from an App.
773 */
774 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800775 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
776
Jeff Sharkey8c870452012-09-26 22:03:49 -0700777 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700778 * @hide
779 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900780 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700781
Paul Jensen5dea4352014-07-11 12:28:19 -0400782 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900783 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
784 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900785 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900786 * @hide
787 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900788 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900789 new NetworkRequest.Builder().clearCapabilities().build();
790
791 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400792 * A NetID indicating no Network is selected.
793 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
794 * @hide
795 */
796 public static final int NETID_UNSET = 0;
797
Erik Klineb0be3e62017-10-30 15:29:44 +0900798 /**
799 * Private DNS Mode values.
800 *
801 * The "private_dns_mode" global setting stores a String value which is
802 * expected to be one of the following.
803 */
804
805 /**
806 * @hide
807 */
lucaslin705c3332021-03-12 17:56:09 +0800808 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900809 public static final String PRIVATE_DNS_MODE_OFF = "off";
810 /**
811 * @hide
812 */
lucaslin705c3332021-03-12 17:56:09 +0800813 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900814 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
815 /**
816 * @hide
817 */
lucaslin705c3332021-03-12 17:56:09 +0800818 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900819 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin705c3332021-03-12 17:56:09 +0800820
821 /** @hide */
822 @Retention(RetentionPolicy.SOURCE)
823 @StringDef(value = {
824 PRIVATE_DNS_MODE_OFF,
825 PRIVATE_DNS_MODE_OPPORTUNISTIC,
826 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
827 })
828 public @interface PrivateDnsMode {}
Erik Klineb0be3e62017-10-30 15:29:44 +0900829
Chalard Jeana3b77512019-04-09 15:46:21 +0900830 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700831 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900832
Paul Jensenc0618a62014-12-10 15:12:18 -0500833 /**
834 * A kludge to facilitate static access where a Context pointer isn't available, like in the
835 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
836 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
837 * methods that take a Context argument.
838 */
839 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800840
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900841 private final Context mContext;
842
Amos Bianchia9b415a2020-03-04 11:07:38 -0800843 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800844
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800845 /**
846 * Tests if a given integer represents a valid network type.
847 * @param networkType the type to be tested
848 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400849 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
850 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800851 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700852 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700853 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900854 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800855 }
856
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800857 /**
858 * Returns a non-localized string representing a given network type.
859 * ONLY used for debugging output.
860 * @param type the type needing naming
861 * @return a String for the given type, or a string version of the type ("87")
862 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900863 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800864 * {@hide}
865 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900866 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000867 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700868 public static String getNetworkTypeName(int type) {
869 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900870 case TYPE_NONE:
871 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700872 case TYPE_MOBILE:
873 return "MOBILE";
874 case TYPE_WIFI:
875 return "WIFI";
876 case TYPE_MOBILE_MMS:
877 return "MOBILE_MMS";
878 case TYPE_MOBILE_SUPL:
879 return "MOBILE_SUPL";
880 case TYPE_MOBILE_DUN:
881 return "MOBILE_DUN";
882 case TYPE_MOBILE_HIPRI:
883 return "MOBILE_HIPRI";
884 case TYPE_WIMAX:
885 return "WIMAX";
886 case TYPE_BLUETOOTH:
887 return "BLUETOOTH";
888 case TYPE_DUMMY:
889 return "DUMMY";
890 case TYPE_ETHERNET:
891 return "ETHERNET";
892 case TYPE_MOBILE_FOTA:
893 return "MOBILE_FOTA";
894 case TYPE_MOBILE_IMS:
895 return "MOBILE_IMS";
896 case TYPE_MOBILE_CBS:
897 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700898 case TYPE_WIFI_P2P:
899 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700900 case TYPE_MOBILE_IA:
901 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700902 case TYPE_MOBILE_EMERGENCY:
903 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500904 case TYPE_PROXY:
905 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900906 case TYPE_VPN:
907 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700908 default:
909 return Integer.toString(type);
910 }
911 }
912
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800913 /**
Aaron Huang96011892020-06-27 07:18:23 +0800914 * @hide
Aaron Huang96011892020-06-27 07:18:23 +0800915 */
lucaslin7fc930b2021-03-17 14:16:01 +0800916 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huang96011892020-06-27 07:18:23 +0800917 public void systemReady() {
918 try {
919 mService.systemReady();
920 } catch (RemoteException e) {
921 throw e.rethrowFromSystemServer();
922 }
923 }
924
925 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800926 * Checks if a given type uses the cellular data connection.
927 * This should be replaced in the future by a network property.
928 * @param networkType the type to check
929 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900930 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800931 * {@hide}
932 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900933 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900934 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700935 public static boolean isNetworkTypeMobile(int networkType) {
936 switch (networkType) {
937 case TYPE_MOBILE:
938 case TYPE_MOBILE_MMS:
939 case TYPE_MOBILE_SUPL:
940 case TYPE_MOBILE_DUN:
941 case TYPE_MOBILE_HIPRI:
942 case TYPE_MOBILE_FOTA:
943 case TYPE_MOBILE_IMS:
944 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -0700945 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -0700946 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700947 return true;
948 default:
949 return false;
950 }
951 }
952
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800953 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700954 * Checks if the given network type is backed by a Wi-Fi radio.
955 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900956 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700957 * @hide
958 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900959 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700960 public static boolean isNetworkTypeWifi(int networkType) {
961 switch (networkType) {
962 case TYPE_WIFI:
963 case TYPE_WIFI_P2P:
964 return true;
965 default:
966 return false;
967 }
968 }
969
970 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +0900971 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
972 * Specify that the traffic for this user should by follow the default rules.
973 * @hide
974 */
Chalard Jeanb43f3962021-03-17 14:33:24 +0900975 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +0900976 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
977
978 /**
979 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
980 * Specify that the traffic for this user should by default go on a network with
981 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
982 * if no such network is available.
983 * @hide
984 */
Chalard Jeanb43f3962021-03-17 14:33:24 +0900985 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +0900986 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
987
988 /** @hide */
989 @Retention(RetentionPolicy.SOURCE)
990 @IntDef(value = {
991 PROFILE_NETWORK_PREFERENCE_DEFAULT,
992 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
993 })
994 public @interface ProfileNetworkPreference {
995 }
996
997 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800998 * Specifies the preferred network type. When the device has more
999 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001000 *
1001 * @param preference the network type to prefer over all others. It is
1002 * unspecified what happens to the old preferred network in the
1003 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001004 * @deprecated Functionality has been removed as it no longer makes sense,
1005 * with many more than two networks - we'd need an array to express
1006 * preference. Instead we use dynamic network properties of
1007 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001008 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001009 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001010 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001011 }
1012
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001013 /**
1014 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001015 *
1016 * @return an integer representing the preferred network type
1017 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001018 * @deprecated Functionality has been removed as it no longer makes sense,
1019 * with many more than two networks - we'd need an array to express
1020 * preference. Instead we use dynamic network properties of
1021 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001022 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001023 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001024 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001025 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001026 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001027 }
1028
Scott Mainf58b7d82011-10-06 19:02:28 -07001029 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001030 * Returns details about the currently active default data network. When
1031 * connected, this network is the default route for outgoing connections.
1032 * You should always check {@link NetworkInfo#isConnected()} before initiating
1033 * network traffic. This may return {@code null} when there is no default
1034 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001035 * Note that if the default network is a VPN, this method will return the
1036 * NetworkInfo for one of its underlying networks instead, or null if the
1037 * VPN agent did not specify any. Apps interested in learning about VPNs
1038 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001039 *
1040 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001041 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001042 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001043 */
junyulai9826e7f2018-12-13 12:47:51 +08001044 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001045 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001046 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001047 public NetworkInfo getActiveNetworkInfo() {
1048 try {
1049 return mService.getActiveNetworkInfo();
1050 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001051 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001052 }
1053 }
1054
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001055 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001056 * Returns a {@link Network} object corresponding to the currently active
1057 * default data network. In the event that the current active default data
1058 * network disconnects, the returned {@code Network} object will no longer
1059 * be usable. This will return {@code null} when there is no default
1060 * network.
1061 *
1062 * @return a {@link Network} object for the current default network or
1063 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001064 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001065 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001066 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001067 public Network getActiveNetwork() {
1068 try {
1069 return mService.getActiveNetwork();
1070 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001071 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001072 }
1073 }
1074
1075 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001076 * Returns a {@link Network} object corresponding to the currently active
1077 * default data network for a specific UID. In the event that the default data
1078 * network disconnects, the returned {@code Network} object will no longer
1079 * be usable. This will return {@code null} when there is no default
1080 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001081 *
1082 * @return a {@link Network} object for the current default network for the
1083 * given UID or {@code null} if no default network is currently active
1084 *
1085 * @hide
1086 */
paulhu8e96a752019-08-12 16:25:11 +08001087 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001088 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001089 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001090 return getActiveNetworkForUid(uid, false);
1091 }
1092
1093 /** {@hide} */
1094 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001095 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001096 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001097 } catch (RemoteException e) {
1098 throw e.rethrowFromSystemServer();
1099 }
1100 }
1101
1102 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001103 * Adds or removes a requirement for given UID ranges to use the VPN.
1104 *
1105 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1106 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1107 * otherwise have permission to bypass the VPN (e.g., because they have the
1108 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1109 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1110 * set to {@code false}, a previously-added restriction is removed.
1111 * <p>
1112 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1113 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1114 * remove a previously-added range, the exact range must be removed as is.
1115 * <p>
1116 * The changes are applied asynchronously and may not have been applied by the time the method
1117 * returns. Apps will be notified about any changes that apply to them via
1118 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1119 * effect.
1120 * <p>
1121 * This method should be called only by the VPN code.
1122 *
1123 * @param ranges the UID ranges to restrict
1124 * @param requireVpn whether the specified UID ranges must use a VPN
1125 *
1126 * TODO: expose as @SystemApi.
1127 * @hide
1128 */
1129 @RequiresPermission(anyOf = {
1130 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1131 android.Manifest.permission.NETWORK_STACK})
1132 public void setRequireVpnForUids(boolean requireVpn,
1133 @NonNull Collection<Range<Integer>> ranges) {
1134 Objects.requireNonNull(ranges);
1135 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1136 // This method is not necessarily expected to be used outside the system server, so
1137 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1138 // stack process, or by tests.
1139 UidRange[] rangesArray = new UidRange[ranges.size()];
1140 int index = 0;
1141 for (Range<Integer> range : ranges) {
1142 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1143 }
1144 try {
1145 mService.setRequireVpnForUids(requireVpn, rangesArray);
1146 } catch (RemoteException e) {
1147 throw e.rethrowFromSystemServer();
1148 }
1149 }
1150
1151 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001152 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1153 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1154 * but is still supported for backwards compatibility.
1155 * <p>
1156 * This type of VPN is assumed always to use the system default network, and must always declare
1157 * exactly one underlying network, which is the network that was the default when the VPN
1158 * connected.
1159 * <p>
1160 * Calling this method with {@code true} enables legacy behaviour, specifically:
1161 * <ul>
1162 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1163 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1164 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1165 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1166 * underlying the VPN.</li>
1167 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1168 * similarly replaced by the VPN network state.</li>
1169 * <li>Information on current network interfaces passed to NetworkStatsService will not
1170 * include any VPN interfaces.</li>
1171 * </ul>
1172 *
1173 * @param enabled whether legacy lockdown VPN is enabled or disabled
1174 *
1175 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1176 *
1177 * @hide
1178 */
1179 @RequiresPermission(anyOf = {
1180 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1181 android.Manifest.permission.NETWORK_SETTINGS})
1182 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1183 try {
1184 mService.setLegacyLockdownVpnEnabled(enabled);
1185 } catch (RemoteException e) {
1186 throw e.rethrowFromSystemServer();
1187 }
1188 }
1189
1190 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001191 * Returns details about the currently active default data network
1192 * for a given uid. This is for internal use only to avoid spying
1193 * other apps.
1194 *
1195 * @return a {@link NetworkInfo} object for the current default network
1196 * for the given uid or {@code null} if no default network is
1197 * available for the specified uid.
1198 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001199 * {@hide}
1200 */
paulhu8e96a752019-08-12 16:25:11 +08001201 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001202 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001203 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001204 return getActiveNetworkInfoForUid(uid, false);
1205 }
1206
1207 /** {@hide} */
1208 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001209 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001210 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001211 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001212 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001213 }
1214 }
1215
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001216 /**
1217 * Returns connection status information about a particular
1218 * network type.
1219 *
1220 * @param networkType integer specifying which networkType in
1221 * which you're interested.
1222 * @return a {@link NetworkInfo} object for the requested
1223 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001224 * supported by the device. If {@code networkType} is
1225 * TYPE_VPN and a VPN is active for the calling app,
1226 * then this method will try to return one of the
1227 * underlying networks for the VPN or null if the
1228 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001229 *
Paul Jensendda8e592015-03-18 12:23:02 -04001230 * @deprecated This method does not support multiple connected networks
1231 * of the same type. Use {@link #getAllNetworks} and
1232 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001233 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001234 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001235 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001236 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001237 public NetworkInfo getNetworkInfo(int networkType) {
1238 try {
1239 return mService.getNetworkInfo(networkType);
1240 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001241 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001242 }
1243 }
1244
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001245 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001246 * Returns connection status information about a particular
1247 * Network.
1248 *
1249 * @param network {@link Network} specifying which network
1250 * in which you're interested.
1251 * @return a {@link NetworkInfo} object for the requested
1252 * network or {@code null} if the {@code Network}
1253 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001254 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001255 */
junyulai9826e7f2018-12-13 12:47:51 +08001256 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001257 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001258 @Nullable
1259 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001260 return getNetworkInfoForUid(network, Process.myUid(), false);
1261 }
1262
1263 /** {@hide} */
1264 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001265 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001266 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001267 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001268 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001269 }
1270 }
1271
1272 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001273 * Returns connection status information about all network
1274 * types supported by the device.
1275 *
1276 * @return an array of {@link NetworkInfo} objects. Check each
1277 * {@link NetworkInfo#getType} for which type each applies.
1278 *
Paul Jensendda8e592015-03-18 12:23:02 -04001279 * @deprecated This method does not support multiple connected networks
1280 * of the same type. Use {@link #getAllNetworks} and
1281 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001282 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001283 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001284 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001285 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001286 public NetworkInfo[] getAllNetworkInfo() {
1287 try {
1288 return mService.getAllNetworkInfo();
1289 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001290 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001291 }
1292 }
1293
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001294 /**
junyulaiebd15162021-03-03 12:09:05 +08001295 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1296 * connected.
1297 * @hide
1298 */
1299 @SystemApi(client = MODULE_LIBRARIES)
1300 @RequiresPermission(anyOf = {
1301 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1302 android.Manifest.permission.NETWORK_STACK,
1303 android.Manifest.permission.NETWORK_SETTINGS})
1304 @NonNull
1305 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1306 try {
1307 return mService.getAllNetworkStateSnapshot();
1308 } catch (RemoteException e) {
1309 throw e.rethrowFromSystemServer();
1310 }
1311 }
1312
1313 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001314 * Returns the {@link Network} object currently serving a given type, or
1315 * null if the given type is not connected.
1316 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001317 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001318 * @deprecated This method does not support multiple connected networks
1319 * of the same type. Use {@link #getAllNetworks} and
1320 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001321 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001322 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001323 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001324 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001325 public Network getNetworkForType(int networkType) {
1326 try {
1327 return mService.getNetworkForType(networkType);
1328 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001329 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001330 }
1331 }
1332
1333 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001334 * Returns an array of all {@link Network} currently tracked by the
1335 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001336 *
1337 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001338 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001339 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001340 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001341 public Network[] getAllNetworks() {
1342 try {
1343 return mService.getAllNetworks();
1344 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001345 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001346 }
1347 }
1348
1349 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001350 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001351 * the Networks that applications run by the given user will use by default.
1352 * @hide
1353 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001354 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001355 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1356 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001357 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001358 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001359 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001360 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001361 }
1362 }
1363
1364 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001365 * Returns the IP information for the current default network.
1366 *
1367 * @return a {@link LinkProperties} object describing the IP info
1368 * for the current default network, or {@code null} if there
1369 * is no current default network.
1370 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001371 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001372 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1373 * value of {@link #getActiveNetwork()} instead. In particular,
1374 * this method will return non-null LinkProperties even if the
1375 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001376 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001377 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001378 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001379 public LinkProperties getActiveLinkProperties() {
1380 try {
1381 return mService.getActiveLinkProperties();
1382 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001383 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001384 }
1385 }
1386
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001387 /**
1388 * Returns the IP information for a given network type.
1389 *
1390 * @param networkType the network type of interest.
1391 * @return a {@link LinkProperties} object describing the IP info
1392 * for the given networkType, or {@code null} if there is
1393 * no current default network.
1394 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001395 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001396 * @deprecated This method does not support multiple connected networks
1397 * of the same type. Use {@link #getAllNetworks},
1398 * {@link #getNetworkInfo(android.net.Network)}, and
1399 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001400 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001401 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001402 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001403 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001404 public LinkProperties getLinkProperties(int networkType) {
1405 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001406 return mService.getLinkPropertiesForType(networkType);
1407 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001408 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001409 }
1410 }
1411
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001412 /**
1413 * Get the {@link LinkProperties} for the given {@link Network}. This
1414 * will return {@code null} if the network is unknown.
1415 *
1416 * @param network The {@link Network} object identifying the network in question.
1417 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001418 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001419 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001420 @Nullable
1421 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001422 try {
1423 return mService.getLinkProperties(network);
1424 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001425 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001426 }
1427 }
1428
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001429 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001430 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001431 * will return {@code null} if the network is unknown.
1432 *
Roshan Pius951c0032020-12-22 15:10:42 -08001433 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1434 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1435 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1436 * this location sensitive information (subject to app's location permissions) will be
1437 * noted by system. To include any location sensitive data in {@link TransportInfo},
1438 * use a {@link NetworkCallback} with
1439 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1440 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001441 * @param network The {@link Network} object identifying the network in question.
Roshan Pius951c0032020-12-22 15:10:42 -08001442 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001443 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001444 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001445 @Nullable
1446 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001447 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001448 return mService.getNetworkCapabilities(
1449 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001450 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001451 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001452 }
1453 }
1454
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001455 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001456 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001457 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1458 * portal is present.
1459 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1460 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1461 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001462 * The system network validation may be using different strategies to detect captive portals,
1463 * so this method does not necessarily return a URL used by the system. It only returns a URL
1464 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001465 *
Udam Sainicd645462016-01-04 12:16:14 -08001466 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001467 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1468 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001469 */
paulhu8e96a752019-08-12 16:25:11 +08001470 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001471 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001472 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001473 public String getCaptivePortalServerUrl() {
1474 try {
1475 return mService.getCaptivePortalServerUrl();
1476 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001477 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001478 }
1479 }
1480
1481 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001482 * Tells the underlying networking system that the caller wants to
1483 * begin using the named feature. The interpretation of {@code feature}
1484 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001485 *
1486 * <p>This method requires the caller to hold either the
1487 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1488 * or the ability to modify system settings as determined by
1489 * {@link android.provider.Settings.System#canWrite}.</p>
1490 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001491 * @param networkType specifies which network the request pertains to
1492 * @param feature the name of the feature to be used
1493 * @return an integer value representing the outcome of the request.
1494 * The interpretation of this value is specific to each networking
1495 * implementation+feature combination, except that the value {@code -1}
1496 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001497 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001498 * @deprecated Deprecated in favor of the cleaner
1499 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001500 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001501 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001502 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001503 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001504 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001505 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001506 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001507 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1508 if (netCap == null) {
1509 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1510 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001511 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001512 }
1513
1514 NetworkRequest request = null;
1515 synchronized (sLegacyRequests) {
1516 LegacyRequest l = sLegacyRequests.get(netCap);
1517 if (l != null) {
1518 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1519 renewRequestLocked(l);
1520 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001521 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001522 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001523 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001524 }
1525 }
1526
1527 request = requestNetworkForFeatureLocked(netCap);
1528 }
1529 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001530 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001531 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001532 } else {
1533 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001534 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001535 }
1536 }
1537
1538 /**
1539 * Tells the underlying networking system that the caller is finished
1540 * using the named feature. The interpretation of {@code feature}
1541 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001542 *
1543 * <p>This method requires the caller to hold either the
1544 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1545 * or the ability to modify system settings as determined by
1546 * {@link android.provider.Settings.System#canWrite}.</p>
1547 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001548 * @param networkType specifies which network the request pertains to
1549 * @param feature the name of the feature that is no longer needed
1550 * @return an integer value representing the outcome of the request.
1551 * The interpretation of this value is specific to each networking
1552 * implementation+feature combination, except that the value {@code -1}
1553 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001554 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001555 * @deprecated Deprecated in favor of the cleaner
1556 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001557 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001558 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001559 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001560 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001561 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001562 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001563 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001564 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1565 if (netCap == null) {
1566 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1567 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001568 return -1;
1569 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001570
Paul Jensen49f74a32014-12-17 10:39:34 -05001571 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001572 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001573 }
1574 return 1;
1575 }
1576
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001577 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001578 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1579 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001580 switch (feature) {
1581 case "enableCBS":
1582 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1583 case "enableDUN":
1584 case "enableDUNAlways":
1585 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1586 case "enableFOTA":
1587 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1588 case "enableHIPRI":
1589 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1590 case "enableIMS":
1591 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1592 case "enableMMS":
1593 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1594 case "enableSUPL":
1595 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1596 default:
1597 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001598 }
Erik Klinece55eb12017-01-26 18:08:28 +09001599 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1600 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001601 }
1602 return null;
1603 }
1604
Robert Greenwalt802c1102014-06-02 15:32:02 -07001605 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001606 if (netCap == null) return TYPE_NONE;
1607 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1608 return TYPE_MOBILE_CBS;
1609 }
1610 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1611 return TYPE_MOBILE_IMS;
1612 }
1613 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1614 return TYPE_MOBILE_FOTA;
1615 }
1616 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1617 return TYPE_MOBILE_DUN;
1618 }
1619 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1620 return TYPE_MOBILE_SUPL;
1621 }
1622 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1623 return TYPE_MOBILE_MMS;
1624 }
1625 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1626 return TYPE_MOBILE_HIPRI;
1627 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001628 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1629 return TYPE_WIFI_P2P;
1630 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001631 return TYPE_NONE;
1632 }
1633
1634 private static class LegacyRequest {
1635 NetworkCapabilities networkCapabilities;
1636 NetworkRequest networkRequest;
1637 int expireSequenceNumber;
1638 Network currentNetwork;
1639 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001640
1641 private void clearDnsBinding() {
1642 if (currentNetwork != null) {
1643 currentNetwork = null;
1644 setProcessDefaultNetworkForHostResolution(null);
1645 }
1646 }
1647
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001648 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001649 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001650 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001651 currentNetwork = network;
1652 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001653 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001654 }
1655 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001656 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001657 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001658 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1659 }
1660 };
1661 }
1662
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001663 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001664 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1665 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001666
1667 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1668 synchronized (sLegacyRequests) {
1669 LegacyRequest l = sLegacyRequests.get(netCap);
1670 if (l != null) return l.networkRequest;
1671 }
1672 return null;
1673 }
1674
1675 private void renewRequestLocked(LegacyRequest l) {
1676 l.expireSequenceNumber++;
1677 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1678 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1679 }
1680
1681 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1682 int ourSeqNum = -1;
1683 synchronized (sLegacyRequests) {
1684 LegacyRequest l = sLegacyRequests.get(netCap);
1685 if (l == null) return;
1686 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001687 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001688 }
1689 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1690 }
1691
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001692 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001693 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1694 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001695 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001696 try {
1697 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001698 } catch (RemoteException e) {
1699 throw e.rethrowFromSystemServer();
1700 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001701 LegacyRequest l = new LegacyRequest();
1702 l.networkCapabilities = netCap;
1703 l.delay = delay;
1704 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001705 l.networkRequest = sendRequestForNetwork(
1706 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001707 if (l.networkRequest == null) return null;
1708 sLegacyRequests.put(netCap, l);
1709 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1710 return l.networkRequest;
1711 }
1712
1713 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1714 if (delay >= 0) {
1715 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001716 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001717 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1718 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001719 }
1720 }
1721
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001722 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001723 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1724 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001725 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001726 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001727 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001728 if (l == null) return false;
1729 unregisterNetworkCallback(l.networkCallback);
1730 l.clearDnsBinding();
1731 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001732 }
1733
Erik Klinece55eb12017-01-26 18:08:28 +09001734 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1735 static {
1736 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1737 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1738 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1739 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1740 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1741 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1742 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1743 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1744 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1745 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1746 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1747 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1748 }
1749
1750 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1751 static {
1752 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1753 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1754 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1755 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1756 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1757 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1758 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1759 }
1760
1761 /**
1762 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1763 * instance suitable for registering a request or callback. Throws an
1764 * IllegalArgumentException if no mapping from the legacy type to
1765 * NetworkCapabilities is known.
1766 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001767 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1768 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001769 * @hide
1770 */
1771 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1772 final NetworkCapabilities nc = new NetworkCapabilities();
1773
1774 // Map from type to transports.
1775 final int NOT_FOUND = -1;
1776 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00001777 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001778 nc.addTransportType(transport);
1779
1780 // Map from type to capabilities.
1781 nc.addCapability(sLegacyTypeToCapability.get(
1782 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1783 nc.maybeMarkCapabilitiesRestricted();
1784 return nc;
1785 }
1786
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001787 /** @hide */
1788 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001789 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001790 public PacketKeepaliveCallback() {
1791 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001792 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001793 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001794 public void onStarted() {}
1795 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001796 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001797 public void onStopped() {}
1798 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001799 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001800 public void onError(int error) {}
1801 }
1802
1803 /**
1804 * Allows applications to request that the system periodically send specific packets on their
1805 * behalf, using hardware offload to save battery power.
1806 *
1807 * To request that the system send keepalives, call one of the methods that return a
1808 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1809 * passing in a non-null callback. If the callback is successfully started, the callback's
1810 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1811 * specifying one of the {@code ERROR_*} constants in this class.
1812 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001813 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1814 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1815 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001816 *
junyulai4c95b082018-12-27 17:25:29 +08001817 * @deprecated Use {@link SocketKeepalive} instead.
1818 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001819 * @hide
1820 */
1821 public class PacketKeepalive {
1822
1823 private static final String TAG = "PacketKeepalive";
1824
1825 /** @hide */
1826 public static final int SUCCESS = 0;
1827
1828 /** @hide */
1829 public static final int NO_KEEPALIVE = -1;
1830
1831 /** @hide */
1832 public static final int BINDER_DIED = -10;
1833
1834 /** The specified {@code Network} is not connected. */
1835 public static final int ERROR_INVALID_NETWORK = -20;
1836 /** The specified IP addresses are invalid. For example, the specified source IP address is
1837 * not configured on the specified {@code Network}. */
1838 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1839 /** The requested port is invalid. */
1840 public static final int ERROR_INVALID_PORT = -22;
1841 /** The packet length is invalid (e.g., too long). */
1842 public static final int ERROR_INVALID_LENGTH = -23;
1843 /** The packet transmission interval is invalid (e.g., too short). */
1844 public static final int ERROR_INVALID_INTERVAL = -24;
1845
1846 /** The hardware does not support this request. */
1847 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001848 /** The hardware returned an error. */
1849 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001850
Nathan Harold0990bc82018-02-14 13:09:45 -08001851 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001852 public static final int NATT_PORT = 4500;
1853
Nathan Harold0990bc82018-02-14 13:09:45 -08001854 /** The minimum interval in seconds between keepalive packet transmissions */
1855 public static final int MIN_INTERVAL = 10;
1856
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001857 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001858 private final ISocketKeepaliveCallback mCallback;
1859 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001860
1861 private volatile Integer mSlot;
1862
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001863 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001864 public void stop() {
1865 try {
junyulai070f9ff2019-01-16 20:23:34 +08001866 mExecutor.execute(() -> {
1867 try {
1868 if (mSlot != null) {
1869 mService.stopKeepalive(mNetwork, mSlot);
1870 }
1871 } catch (RemoteException e) {
1872 Log.e(TAG, "Error stopping packet keepalive: ", e);
1873 throw e.rethrowFromSystemServer();
1874 }
1875 });
1876 } catch (RejectedExecutionException e) {
1877 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001878 }
1879 }
1880
1881 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00001882 Preconditions.checkNotNull(network, "network cannot be null");
1883 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001884 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001885 mExecutor = Executors.newSingleThreadExecutor();
1886 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001887 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001888 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001889 final long token = Binder.clearCallingIdentity();
1890 try {
1891 mExecutor.execute(() -> {
1892 mSlot = slot;
1893 callback.onStarted();
1894 });
1895 } finally {
1896 Binder.restoreCallingIdentity(token);
1897 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001898 }
junyulai070f9ff2019-01-16 20:23:34 +08001899
1900 @Override
1901 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001902 final long token = Binder.clearCallingIdentity();
1903 try {
1904 mExecutor.execute(() -> {
1905 mSlot = null;
1906 callback.onStopped();
1907 });
1908 } finally {
1909 Binder.restoreCallingIdentity(token);
1910 }
junyulai070f9ff2019-01-16 20:23:34 +08001911 mExecutor.shutdown();
1912 }
1913
1914 @Override
1915 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001916 final long token = Binder.clearCallingIdentity();
1917 try {
1918 mExecutor.execute(() -> {
1919 mSlot = null;
1920 callback.onError(error);
1921 });
1922 } finally {
1923 Binder.restoreCallingIdentity(token);
1924 }
junyulai070f9ff2019-01-16 20:23:34 +08001925 mExecutor.shutdown();
1926 }
1927
1928 @Override
1929 public void onDataReceived() {
1930 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1931 // this callback when data is received.
1932 }
1933 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001934 }
1935 }
1936
1937 /**
1938 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1939 *
junyulai4c95b082018-12-27 17:25:29 +08001940 * @deprecated Use {@link #createSocketKeepalive} instead.
1941 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001942 * @hide
1943 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001944 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001945 public PacketKeepalive startNattKeepalive(
1946 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1947 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1948 final PacketKeepalive k = new PacketKeepalive(network, callback);
1949 try {
junyulai070f9ff2019-01-16 20:23:34 +08001950 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001951 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1952 } catch (RemoteException e) {
1953 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001954 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001955 }
1956 return k;
1957 }
1958
Chiachang Wang619319a2021-01-15 11:06:21 +08001959 // Construct an invalid fd.
1960 private ParcelFileDescriptor createInvalidFd() {
1961 final int invalidFd = -1;
1962 return ParcelFileDescriptor.adoptFd(invalidFd);
1963 }
1964
The Android Open Source Project28527d22009-03-03 19:31:44 -08001965 /**
junyulai4c95b082018-12-27 17:25:29 +08001966 * Request that keepalives be started on a IPsec NAT-T socket.
1967 *
1968 * @param network The {@link Network} the socket is on.
1969 * @param socket The socket that needs to be kept alive.
1970 * @param source The source address of the {@link UdpEncapsulationSocket}.
1971 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1972 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1973 * must run callback sequentially, otherwise the order of callbacks cannot be
1974 * guaranteed.
1975 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1976 * changes. Must be extended by applications that use this API.
1977 *
junyulai0835a1e2019-01-08 20:04:33 +08001978 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1979 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001980 **/
junyulai7e06ad42019-03-04 22:45:36 +08001981 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001982 @NonNull UdpEncapsulationSocket socket,
1983 @NonNull InetAddress source,
1984 @NonNull InetAddress destination,
1985 @NonNull @CallbackExecutor Executor executor,
1986 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001987 ParcelFileDescriptor dup;
1988 try {
junyulai828dad12019-03-27 11:00:37 +08001989 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1990 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001991 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1992 } catch (IOException ignored) {
1993 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1994 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001995 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001996 }
1997 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1998 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08001999 }
2000
2001 /**
2002 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2003 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2004 *
2005 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002006 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2007 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2008 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002009 * @param source The source address of the {@link UdpEncapsulationSocket}.
2010 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2011 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2012 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2013 * must run callback sequentially, otherwise the order of callbacks cannot be
2014 * guaranteed.
2015 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2016 * changes. Must be extended by applications that use this API.
2017 *
junyulai0835a1e2019-01-08 20:04:33 +08002018 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2019 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002020 * @hide
2021 */
2022 @SystemApi
2023 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002024 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2025 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002026 @NonNull InetAddress source,
2027 @NonNull InetAddress destination,
2028 @NonNull @CallbackExecutor Executor executor,
2029 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002030 ParcelFileDescriptor dup;
2031 try {
junyulai828dad12019-03-27 11:00:37 +08002032 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002033 dup = pfd.dup();
2034 } catch (IOException ignored) {
2035 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2036 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002037 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002038 }
2039 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANce355502021-03-11 10:56:49 +00002040 -1 /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002041 }
2042
2043 /**
junyulai0835a1e2019-01-08 20:04:33 +08002044 * Request that keepalives be started on a TCP socket.
2045 * The socket must be established.
2046 *
2047 * @param network The {@link Network} the socket is on.
2048 * @param socket The socket that needs to be kept alive.
2049 * @param executor The executor on which callback will be invoked. This implementation assumes
2050 * the provided {@link Executor} runs the callbacks in sequence with no
2051 * concurrency. Failing this, no guarantee of correctness can be made. It is
2052 * the responsibility of the caller to ensure the executor provides this
2053 * guarantee. A simple way of creating such an executor is with the standard
2054 * tool {@code Executors.newSingleThreadExecutor}.
2055 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2056 * changes. Must be extended by applications that use this API.
2057 *
2058 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2059 * given socket.
2060 * @hide
2061 */
2062 @SystemApi
2063 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002064 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002065 @NonNull Socket socket,
2066 @NonNull Executor executor,
2067 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002068 ParcelFileDescriptor dup;
2069 try {
2070 dup = ParcelFileDescriptor.fromSocket(socket);
2071 } catch (UncheckedIOException ignored) {
2072 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2073 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002074 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002075 }
2076 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002077 }
2078
2079 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002080 * Ensure that a network route exists to deliver traffic to the specified
2081 * host via the specified network interface. An attempt to add a route that
2082 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002083 *
2084 * <p>This method requires the caller to hold either the
2085 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2086 * or the ability to modify system settings as determined by
2087 * {@link android.provider.Settings.System#canWrite}.</p>
2088 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002089 * @param networkType the type of the network over which traffic to the specified
2090 * host is to be routed
2091 * @param hostAddress the IP address of the host to which the route is desired
2092 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002093 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002094 * @deprecated Deprecated in favor of the
2095 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2096 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002097 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002098 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002099 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002100 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002101 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002102 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002103 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002104 }
2105
2106 /**
2107 * Ensure that a network route exists to deliver traffic to the specified
2108 * host via the specified network interface. An attempt to add a route that
2109 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002110 *
2111 * <p>This method requires the caller to hold either the
2112 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2113 * or the ability to modify system settings as determined by
2114 * {@link android.provider.Settings.System#canWrite}.</p>
2115 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002116 * @param networkType the type of the network over which traffic to the specified
2117 * host is to be routed
2118 * @param hostAddress the IP address of the host to which the route is desired
2119 * @return {@code true} on success, {@code false} on failure
2120 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002121 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002122 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002123 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002124 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002125 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002126 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002127 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002128 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002129 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2130 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002131 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002132 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002133 }
2134 }
2135
2136 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002137 * @return the context's attribution tag
2138 */
2139 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2140 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002141 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002142 }
2143
2144 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002145 * Returns the value of the setting for background data usage. If false,
2146 * applications should not use the network if the application is not in the
2147 * foreground. Developers should respect this setting, and check the value
2148 * of this before performing any background data operations.
2149 * <p>
2150 * All applications that have background services that use the network
2151 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002152 * <p>
Scott Main50589142011-10-06 18:32:43 -07002153 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002154 * background data depends on several combined factors, and this method will
2155 * always return {@code true}. Instead, when background data is unavailable,
2156 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002157 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002158 * @return Whether background data usage is allowed.
2159 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002160 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002161 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002162 // assume that background data is allowed; final authority is
2163 // NetworkInfo which may be blocked.
2164 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002165 }
2166
2167 /**
2168 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002169 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002170 * @param allowBackgroundData Whether an application should use data while
2171 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002172 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002173 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2174 * @see #getBackgroundDataSetting()
2175 * @hide
2176 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002177 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002178 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002179 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002180 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002181 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002182
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002183 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002184 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002185 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002186 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002187 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002188 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002189 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002190 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2191 if (tm != null) {
2192 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2193 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2194 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2195 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2196 + " retVal=" + retVal);
2197 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002198 }
Wink Saville689f7042014-12-05 11:10:30 -08002199 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002200 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002201 }
2202
The Android Open Source Project28527d22009-03-03 19:31:44 -08002203 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002204 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002205 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002206 */
2207 public interface OnNetworkActiveListener {
2208 /**
2209 * Called on the main thread of the process to report that the current data network
2210 * has become active, and it is now a good time to perform any pending network
2211 * operations. Note that this listener only tells you when the network becomes
2212 * active; if at any other time you want to know whether it is active (and thus okay
2213 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002214 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002215 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002216 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002217 }
2218
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002219 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002220 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002221
2222 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002223 * Start listening to reports when the system's default data network is active, meaning it is
2224 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2225 * to determine the current state of the system's default network after registering the
2226 * listener.
2227 * <p>
2228 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002229 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002230 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002231 *
2232 * @param l The listener to be told when the network is active.
2233 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002234 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002235 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2236 @Override
2237 public void onNetworkActive() throws RemoteException {
2238 l.onNetworkActive();
2239 }
2240 };
2241
2242 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002243 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002244 mNetworkActivityListeners.put(l, rl);
2245 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002246 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002247 }
2248 }
2249
2250 /**
2251 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002252 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002253 *
2254 * @param l Previously registered listener.
2255 */
Chalard Jean158702d2019-01-07 19:26:34 +09002256 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002257 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002258 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002259 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002260 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002261 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002262 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002263 }
2264 }
2265
2266 /**
2267 * Return whether the data network is currently active. An active network means that
2268 * it is currently in a high power state for performing data transmission. On some
2269 * types of networks, it may be expensive to move and stay in such a state, so it is
2270 * more power efficient to batch network traffic together when the radio is already in
2271 * this state. This method tells you whether right now is currently a good time to
2272 * initiate network traffic, as the network is already active.
2273 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002274 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002275 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002276 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002277 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002278 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002279 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002280 }
2281
2282 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002283 * {@hide}
2284 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002285 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002286 mContext = Preconditions.checkNotNull(context, "missing context");
2287 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002288 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002289 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002290 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002291
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002292 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002293 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002294 public static ConnectivityManager from(Context context) {
2295 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2296 }
2297
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002298 /** @hide */
2299 public NetworkRequest getDefaultRequest() {
2300 try {
2301 // This is not racy as the default request is final in ConnectivityService.
2302 return mService.getDefaultRequest();
2303 } catch (RemoteException e) {
2304 throw e.rethrowFromSystemServer();
2305 }
2306 }
2307
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002308 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002309 * Check if the package is a allowed to write settings. This also accounts that such an access
2310 * happened.
2311 *
2312 * @return {@code true} iff the package is allowed to write settings.
2313 */
2314 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2315 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2316 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2317 boolean throwException) {
2318 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2319 throwException);
2320 }
2321
2322 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002323 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2324 * situations where a Context pointer is unavailable.
2325 * @hide
2326 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002327 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002328 static ConnectivityManager getInstanceOrNull() {
2329 return sInstance;
2330 }
2331
2332 /**
2333 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2334 * situations where a Context pointer is unavailable.
2335 * @hide
2336 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002337 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002338 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002339 private static ConnectivityManager getInstance() {
2340 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002341 throw new IllegalStateException("No ConnectivityManager yet constructed");
2342 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002343 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002344 }
2345
2346 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002347 * Get the set of tetherable, available interfaces. This list is limited by
2348 * device configuration and current interface existence.
2349 *
2350 * @return an array of 0 or more Strings of tetherable interface names.
2351 *
markchien6ae63e52020-01-21 13:11:06 +08002352 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002353 * {@hide}
2354 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002355 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002356 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002357 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002358 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002359 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002360 }
2361
2362 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002363 * Get the set of tethered interfaces.
2364 *
2365 * @return an array of 0 or more String of currently tethered interface names.
2366 *
markchien6ae63e52020-01-21 13:11:06 +08002367 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002368 * {@hide}
2369 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002370 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002371 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002372 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002373 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002374 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002375 }
2376
2377 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002378 * Get the set of interface names which attempted to tether but
2379 * failed. Re-attempting to tether may cause them to reset to the Tethered
2380 * state. Alternatively, causing the interface to be destroyed and recreated
2381 * may cause them to reset to the available state.
2382 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2383 * information on the cause of the errors.
2384 *
2385 * @return an array of 0 or more String indicating the interface names
2386 * which failed to tether.
2387 *
markchien6ae63e52020-01-21 13:11:06 +08002388 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002389 * {@hide}
2390 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002391 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002392 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002393 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002394 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002395 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002396 }
2397
2398 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002399 * Get the set of tethered dhcp ranges.
2400 *
markchien2e6ba522020-02-14 11:55:48 +08002401 * @deprecated This method is not supported.
2402 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002403 * {@hide}
2404 */
paulhu8e96a752019-08-12 16:25:11 +08002405 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002406 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002407 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002408 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002409 }
2410
2411 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002412 * Attempt to tether the named interface. This will setup a dhcp server
2413 * on the interface, forward and NAT IP packets and forward DNS requests
2414 * to the best active upstream network interface. Note that if no upstream
2415 * IP network interface is available, dhcp will still run and traffic will be
2416 * allowed between the tethered devices and this device, though upstream net
2417 * access will of course fail until an upstream network interface becomes
2418 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002419 *
2420 * <p>This method requires the caller to hold either the
2421 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2422 * or the ability to modify system settings as determined by
2423 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002424 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002425 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2426 * and WifiStateMachine which need direct access. All other clients should use
2427 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2428 * logic.</p>
2429 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002430 * @param iface the interface name to tether.
2431 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002432 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002433 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002434 * {@hide}
2435 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002436 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002437 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002438 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002439 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002440 }
2441
2442 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002443 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002444 *
2445 * <p>This method requires the caller to hold either the
2446 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2447 * or the ability to modify system settings as determined by
2448 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002449 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002450 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2451 * and WifiStateMachine which need direct access. All other clients should use
2452 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2453 * logic.</p>
2454 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002455 * @param iface the interface name to untether.
2456 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2457 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002458 * {@hide}
2459 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002460 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002461 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002462 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002463 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002464 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002465
2466 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002467 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002468 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002469 * due to device configuration.
2470 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002471 * <p>If this app does not have permission to use this API, it will always
2472 * return false rather than throw an exception.</p>
2473 *
2474 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2475 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2476 *
2477 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2478 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2479 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002480 * @return a boolean - {@code true} indicating Tethering is supported.
2481 *
markchien6ae63e52020-01-21 13:11:06 +08002482 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002483 * {@hide}
2484 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002485 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002486 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2487 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002488 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002489 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002490 }
2491
2492 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002493 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002494 *
2495 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002496 * @hide
2497 */
2498 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002499 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002500 public static abstract class OnStartTetheringCallback {
2501 /**
2502 * Called when tethering has been successfully started.
2503 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002504 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002505
2506 /**
2507 * Called when starting tethering failed.
2508 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002509 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002510 }
2511
2512 /**
2513 * Convenient overload for
2514 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2515 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002516 *
2517 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002518 * @hide
2519 */
2520 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002521 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002522 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002523 public void startTethering(int type, boolean showProvisioningUi,
2524 final OnStartTetheringCallback callback) {
2525 startTethering(type, showProvisioningUi, callback, null);
2526 }
2527
2528 /**
2529 * Runs tether provisioning for the given type if needed and then starts tethering if
2530 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2531 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2532 * schedules tether provisioning re-checks if appropriate.
2533 *
2534 * @param type The type of tethering to start. Must be one of
2535 * {@link ConnectivityManager.TETHERING_WIFI},
2536 * {@link ConnectivityManager.TETHERING_USB}, or
2537 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2538 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2539 * is one. This should be true the first time this function is called and also any time
2540 * the user can see this UI. It gives users information from their carrier about the
2541 * check failing and how they can sign up for tethering if possible.
2542 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2543 * of the result of trying to tether.
2544 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002545 *
2546 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002547 * @hide
2548 */
2549 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002550 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002551 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002552 public void startTethering(int type, boolean showProvisioningUi,
2553 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002554 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002555
markchien91c78e52020-01-20 19:31:56 +08002556 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002557 @Override
markchien91c78e52020-01-20 19:31:56 +08002558 public void execute(Runnable command) {
2559 if (handler == null) {
2560 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002561 } else {
markchien91c78e52020-01-20 19:31:56 +08002562 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002563 }
2564 }
2565 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002566
markchien91c78e52020-01-20 19:31:56 +08002567 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2568 @Override
2569 public void onTetheringStarted() {
2570 callback.onTetheringStarted();
2571 }
2572
2573 @Override
markchienf47d8342020-03-19 13:37:43 +08002574 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002575 callback.onTetheringFailed();
2576 }
2577 };
2578
2579 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002580 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002581
Amos Bianchia9b415a2020-03-04 11:07:38 -08002582 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002583 }
2584
2585 /**
2586 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2587 * applicable.
2588 *
2589 * @param type The type of tethering to stop. Must be one of
2590 * {@link ConnectivityManager.TETHERING_WIFI},
2591 * {@link ConnectivityManager.TETHERING_USB}, or
2592 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002593 *
2594 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002595 * @hide
2596 */
2597 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002598 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002599 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002600 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002601 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002602 }
2603
2604 /**
markchien4ef53e82019-02-27 14:56:11 +08002605 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2606 * upstream status.
2607 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002608 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002609 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002610 */
2611 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002612 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002613 public abstract static class OnTetheringEventCallback {
2614
2615 /**
2616 * Called when tethering upstream changed. This can be called multiple times and can be
2617 * called any time.
2618 *
2619 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2620 * have any upstream.
2621 */
2622 public void onUpstreamChanged(@Nullable Network network) {}
2623 }
2624
markchien6ae63e52020-01-21 13:11:06 +08002625 @GuardedBy("mTetheringEventCallbacks")
2626 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2627 mTetheringEventCallbacks = new ArrayMap<>();
2628
markchien4ef53e82019-02-27 14:56:11 +08002629 /**
2630 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002631 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002632 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2633 * with a null argument. The same callback object cannot be registered twice.
2634 *
2635 * @param executor the executor on which callback will be invoked.
2636 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002637 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002638 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002639 * @hide
2640 */
2641 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002642 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002643 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2644 public void registerTetheringEventCallback(
2645 @NonNull @CallbackExecutor Executor executor,
2646 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002647 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
markchien4ef53e82019-02-27 14:56:11 +08002648
markchien6ae63e52020-01-21 13:11:06 +08002649 final TetheringEventCallback tetherCallback =
2650 new TetheringEventCallback() {
2651 @Override
2652 public void onUpstreamChanged(@Nullable Network network) {
2653 callback.onUpstreamChanged(network);
2654 }
2655 };
2656
2657 synchronized (mTetheringEventCallbacks) {
2658 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002659 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002660 }
markchien4ef53e82019-02-27 14:56:11 +08002661 }
2662
2663 /**
2664 * Remove tethering event callback previously registered with
2665 * {@link #registerTetheringEventCallback}.
2666 *
2667 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002668 *
2669 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002670 * @hide
2671 */
2672 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002673 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002674 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2675 public void unregisterTetheringEventCallback(
2676 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002677 Objects.requireNonNull(callback, "The callback must be non-null");
2678 synchronized (mTetheringEventCallbacks) {
2679 final TetheringEventCallback tetherCallback =
2680 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002681 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002682 }
markchien4ef53e82019-02-27 14:56:11 +08002683 }
2684
2685
2686 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002687 * Get the list of regular expressions that define any tetherable
2688 * USB network interfaces. If USB tethering is not supported by the
2689 * device, this list should be empty.
2690 *
2691 * @return an array of 0 or more regular expression Strings defining
2692 * what interfaces are considered tetherable usb interfaces.
2693 *
markchien6ae63e52020-01-21 13:11:06 +08002694 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002695 * {@hide}
2696 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002697 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002698 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002699 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002700 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002701 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002702 }
2703
2704 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002705 * Get the list of regular expressions that define any tetherable
2706 * Wifi network interfaces. If Wifi tethering is not supported by the
2707 * device, this list should be empty.
2708 *
2709 * @return an array of 0 or more regular expression Strings defining
2710 * what interfaces are considered tetherable wifi interfaces.
2711 *
markchien6ae63e52020-01-21 13:11:06 +08002712 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002713 * {@hide}
2714 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002715 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002716 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002717 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002718 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002719 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002720 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002721
Danica Chang96567052010-08-11 14:54:43 -07002722 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002723 * Get the list of regular expressions that define any tetherable
2724 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2725 * device, this list should be empty.
2726 *
2727 * @return an array of 0 or more regular expression Strings defining
2728 * what interfaces are considered tetherable bluetooth interfaces.
2729 *
markchien6ae63e52020-01-21 13:11:06 +08002730 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2731 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002732 * {@hide}
2733 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002734 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002735 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002736 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002737 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002738 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002739 }
2740
Mike Lockwooded4a1742011-07-19 13:04:47 -07002741 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002742 * Attempt to both alter the mode of USB and Tethering of USB. A
2743 * utility method to deal with some of the complexity of USB - will
2744 * attempt to switch to Rndis and subsequently tether the resulting
2745 * interface on {@code true} or turn off tethering and switch off
2746 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002747 *
2748 * <p>This method requires the caller to hold either the
2749 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2750 * or the ability to modify system settings as determined by
2751 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002752 *
2753 * @param enable a boolean - {@code true} to enable tethering
2754 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002755 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002756 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002757 * {@hide}
2758 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002759 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002760 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002761 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002762 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002763 }
2764
markchien6ae63e52020-01-21 13:11:06 +08002765 /**
2766 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2767 * {@hide}
2768 */
markchien0f45bb92019-01-16 17:44:13 +08002769 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002770 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002771 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002772 /**
2773 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2774 * {@hide}
2775 */
2776 @Deprecated
2777 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2778 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2779 /**
2780 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2781 * {@hide}
2782 */
2783 @Deprecated
2784 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2785 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2786 /**
2787 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2788 * {@hide}
2789 */
2790 @Deprecated
2791 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2792 /**
2793 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2794 * {@hide}
2795 */
2796 @Deprecated
2797 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2798 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2799 /**
markchienf47d8342020-03-19 13:37:43 +08002800 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002801 * {@hide}
2802 */
2803 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002804 public static final int TETHER_ERROR_MASTER_ERROR =
2805 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002806 /**
2807 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2808 * {@hide}
2809 */
2810 @Deprecated
2811 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2812 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2813 /**
2814 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2815 * {@hide}
2816 */
2817 @Deprecated
2818 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2819 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2820 /**
markchienf47d8342020-03-19 13:37:43 +08002821 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002822 * {@hide}
2823 */
2824 @Deprecated
2825 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002826 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002827 /**
markchienf47d8342020-03-19 13:37:43 +08002828 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002829 * {@hide}
2830 */
2831 @Deprecated
2832 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002833 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002834 /**
2835 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2836 * {@hide}
2837 */
2838 @Deprecated
2839 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2840 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2841 /**
markchienf47d8342020-03-19 13:37:43 +08002842 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002843 * {@hide}
2844 */
markchien0f45bb92019-01-16 17:44:13 +08002845 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002846 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002847 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002848 /**
2849 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2850 * {@hide}
2851 */
2852 @Deprecated
2853 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2854 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2855 /**
2856 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2857 * {@hide}
2858 */
markchien0f45bb92019-01-16 17:44:13 +08002859 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002860 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002861 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002862
2863 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002864 * Get a more detailed error code after a Tethering or Untethering
2865 * request asynchronously failed.
2866 *
2867 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002868 * @return error The error code of the last error tethering or untethering the named
2869 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002870 *
markchien6ae63e52020-01-21 13:11:06 +08002871 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002872 * {@hide}
2873 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002874 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002875 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002876 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002877 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002878 int error = mTetheringManager.getLastTetherError(iface);
2879 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2880 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2881 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2882 // instead.
2883 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2884 }
2885 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002886 }
2887
markchienbf5ab012019-03-06 16:25:00 +08002888 /** @hide */
2889 @Retention(RetentionPolicy.SOURCE)
2890 @IntDef(value = {
2891 TETHER_ERROR_NO_ERROR,
2892 TETHER_ERROR_PROVISION_FAILED,
2893 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2894 })
2895 public @interface EntitlementResultCode {
2896 }
2897
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002898 /**
markchienbf5ab012019-03-06 16:25:00 +08002899 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002900 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002901 *
2902 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002903 * @hide
2904 */
2905 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002906 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002907 public interface OnTetheringEntitlementResultListener {
2908 /**
2909 * Called to notify entitlement result.
2910 *
2911 * @param resultCode an int value of entitlement result. It may be one of
2912 * {@link #TETHER_ERROR_NO_ERROR},
2913 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2914 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2915 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002916 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002917 }
2918
2919 /**
markchien0f45bb92019-01-16 17:44:13 +08002920 * Get the last value of the entitlement check on this downstream. If the cached value is
2921 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2922 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2923 * guaranteed that the UI-based entitlement check will complete in any specific time period
2924 * and may in fact never complete. Any successful entitlement check the platform performs for
2925 * any reason will update the cached value.
2926 *
2927 * @param type the downstream type of tethering. Must be one of
2928 * {@link #TETHERING_WIFI},
2929 * {@link #TETHERING_USB}, or
2930 * {@link #TETHERING_BLUETOOTH}.
2931 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002932 * @param executor the executor on which callback will be invoked.
2933 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2934 * notify the caller of the result of entitlement check. The listener may be called zero
2935 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002936 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002937 * {@hide}
2938 */
2939 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002940 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002941 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002942 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2943 @NonNull @CallbackExecutor Executor executor,
2944 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002945 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchienbf5ab012019-03-06 16:25:00 +08002946 ResultReceiver wrappedListener = new ResultReceiver(null) {
2947 @Override
2948 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08002949 final long token = Binder.clearCallingIdentity();
2950 try {
2951 executor.execute(() -> {
2952 listener.onTetheringEntitlementResult(resultCode);
2953 });
2954 } finally {
2955 Binder.restoreCallingIdentity(token);
2956 }
markchienbf5ab012019-03-06 16:25:00 +08002957 }
2958 };
2959
Amos Bianchia9b415a2020-03-04 11:07:38 -08002960 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002961 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002962 }
2963
2964 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002965 * Report network connectivity status. This is currently used only
2966 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002967 * <p>This method requires the caller to hold the permission
2968 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002969 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002970 * @param networkType The type of network you want to report on
2971 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002972 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002973 * {@hide}
2974 */
2975 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002976 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002977 try {
2978 mService.reportInetCondition(networkType, percentage);
2979 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002980 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002981 }
2982 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002983
2984 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002985 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07002986 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002987 * the framework to re-evaluate network connectivity and/or switch to another
2988 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002989 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002990 * @param network The {@link Network} the application was attempting to use
2991 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04002992 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2993 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002994 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002995 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09002996 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002997 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002998 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04002999 // One of these will be ignored because it matches system's current state.
3000 // The other will trigger the necessary reevaluation.
3001 mService.reportNetworkConnectivity(network, true);
3002 mService.reportNetworkConnectivity(network, false);
3003 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003004 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003005 }
3006 }
3007
3008 /**
3009 * Report to the framework whether a network has working connectivity.
3010 * This provides a hint to the system that a particular network is providing
3011 * working connectivity or not. In response the framework may re-evaluate
3012 * the network's connectivity and might take further action thereafter.
3013 *
3014 * @param network The {@link Network} the application was attempting to use
3015 * or {@code null} to indicate the current default network.
3016 * @param hasConnectivity {@code true} if the application was able to successfully access the
3017 * Internet using {@code network} or {@code false} if not.
3018 */
Chalard Jean158702d2019-01-07 19:26:34 +09003019 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003020 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003021 try {
3022 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003023 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003024 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003025 }
3026 }
3027
3028 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003029 * Set a network-independent global http proxy. This is not normally what you want
3030 * for typical HTTP proxies - they are general network dependent. However if you're
3031 * doing something unusual like general internal filtering this may be useful. On
3032 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003033 *
3034 * @param p A {@link ProxyInfo} object defining the new global
3035 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003036 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003037 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003038 @SystemApi(client = MODULE_LIBRARIES)
paulhu8e96a752019-08-12 16:25:11 +08003039 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang4d513572021-03-18 09:44:34 +08003040 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003041 try {
3042 mService.setGlobalProxy(p);
3043 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003044 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003045 }
3046 }
3047
3048 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003049 * Retrieve any network-independent global HTTP proxy.
3050 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003051 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003052 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003053 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003054 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003055 @SystemApi(client = MODULE_LIBRARIES)
3056 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04003057 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003058 try {
3059 return mService.getGlobalProxy();
3060 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003061 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003062 }
3063 }
3064
3065 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003066 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3067 * network-specific HTTP proxy. If {@code network} is null, the
3068 * network-specific proxy returned is the proxy of the default active
3069 * network.
3070 *
3071 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3072 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3073 * or when {@code network} is {@code null},
3074 * the {@code ProxyInfo} for the default active network. Returns
3075 * {@code null} when no proxy applies or the caller doesn't have
3076 * permission to use {@code network}.
3077 * @hide
3078 */
3079 public ProxyInfo getProxyForNetwork(Network network) {
3080 try {
3081 return mService.getProxyForNetwork(network);
3082 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003083 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003084 }
3085 }
3086
3087 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003088 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3089 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003090 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003091 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003092 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003093 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003094 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003095 */
Chalard Jean158702d2019-01-07 19:26:34 +09003096 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003097 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003098 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003099 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003100
3101 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003102 * Returns true if the hardware supports the given network type
3103 * else it returns false. This doesn't indicate we have coverage
3104 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003105 * hardware supports it. For example a GSM phone without a SIM
3106 * should still return {@code true} for mobile data, but a wifi only
3107 * tablet would return {@code false}.
3108 *
3109 * @param networkType The network type we'd like to check
3110 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003111 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003112 * @hide
3113 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003114 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003115 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003116 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003117 public boolean isNetworkSupported(int networkType) {
3118 try {
3119 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003120 } catch (RemoteException e) {
3121 throw e.rethrowFromSystemServer();
3122 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003123 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003124
3125 /**
3126 * Returns if the currently active data network is metered. A network is
3127 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003128 * that connection due to monetary costs, data limitations or
3129 * battery/performance issues. You should check this before doing large
3130 * data transfers, and warn the user or delay the operation until another
3131 * network is available.
3132 *
3133 * @return {@code true} if large transfers should be avoided, otherwise
3134 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003135 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003136 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003137 public boolean isActiveNetworkMetered() {
3138 try {
3139 return mService.isActiveNetworkMetered();
3140 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003141 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003142 }
3143 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003144
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003145 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003146 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003147 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003148 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003149 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003150 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003151 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003152 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003153 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003154 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003155 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003156 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003157 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003158 }
3159 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003160
3161 /**
3162 * Set the value for enabling/disabling airplane mode
3163 *
3164 * @param enable whether to enable airplane mode or not
3165 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003166 * @hide
3167 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003168 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003169 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003170 android.Manifest.permission.NETWORK_SETTINGS,
3171 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3172 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003173 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003174 public void setAirplaneMode(boolean enable) {
3175 try {
3176 mService.setAirplaneMode(enable);
3177 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003178 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003179 }
3180 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003181
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003182 /**
3183 * Registers the specified {@link NetworkProvider}.
3184 * Each listener must only be registered once. The listener can be unregistered with
3185 * {@link #unregisterNetworkProvider}.
3186 *
3187 * @param provider the provider to register
3188 * @return the ID of the provider. This ID must be used by the provider when registering
3189 * {@link android.net.NetworkAgent}s.
3190 * @hide
3191 */
3192 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003193 @RequiresPermission(anyOf = {
3194 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3195 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003196 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3197 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003198 throw new IllegalStateException("NetworkProviders can only be registered once");
3199 }
3200
3201 try {
3202 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3203 provider.getName());
3204 provider.setProviderId(providerId);
3205 } catch (RemoteException e) {
3206 throw e.rethrowFromSystemServer();
3207 }
3208 return provider.getProviderId();
3209 }
3210
3211 /**
3212 * Unregisters the specified NetworkProvider.
3213 *
3214 * @param provider the provider to unregister
3215 * @hide
3216 */
3217 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003218 @RequiresPermission(anyOf = {
3219 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3220 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003221 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3222 try {
3223 mService.unregisterNetworkProvider(provider.getMessenger());
3224 } catch (RemoteException e) {
3225 throw e.rethrowFromSystemServer();
3226 }
3227 provider.setProviderId(NetworkProvider.ID_NONE);
3228 }
3229
3230
3231 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003232 @RequiresPermission(anyOf = {
3233 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3234 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003235 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3236 try {
3237 mService.declareNetworkRequestUnfulfillable(request);
3238 } catch (RemoteException e) {
3239 throw e.rethrowFromSystemServer();
3240 }
3241 }
3242
Paul Jensen1f567382015-02-13 14:18:39 -05003243 /**
3244 * @hide
3245 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003246 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003247 */
paulhub6ba8e82020-03-04 09:43:41 +08003248 @RequiresPermission(anyOf = {
3249 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3250 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003251 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jean28018572020-12-21 18:36:52 +09003252 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3253 int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003254 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003255 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003256 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003257 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003258 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003259 }
3260
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003261 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003262 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3263 * changes. Should be extended by applications wanting notifications.
3264 *
3265 * A {@code NetworkCallback} is registered by calling
3266 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3267 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003268 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003269 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3270 * A {@code NetworkCallback} should be registered at most once at any time.
3271 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003272 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003273 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003274 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003275 * No flags associated with this callback.
3276 * @hide
3277 */
3278 public static final int FLAG_NONE = 0;
3279 /**
3280 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3281 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3282 * <p>
3283 * These include:
3284 * <li> Some transport info instances (retrieved via
3285 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3286 * contain location sensitive information.
3287 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3288 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3289 * </p>
3290 * <p>
3291 * Note:
3292 * <li> Retrieving this location sensitive information (subject to app's location
3293 * permissions) will be noted by system. </li>
3294 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3295 * not include location sensitive info.
3296 * </p>
3297 */
3298 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3299
3300 /** @hide */
3301 @Retention(RetentionPolicy.SOURCE)
3302 @IntDef(flag = true, prefix = "FLAG_", value = {
3303 FLAG_NONE,
3304 FLAG_INCLUDE_LOCATION_INFO
3305 })
3306 public @interface Flag { }
3307
3308 /**
3309 * All the valid flags for error checking.
3310 */
3311 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3312
3313 public NetworkCallback() {
3314 this(FLAG_NONE);
3315 }
3316
3317 public NetworkCallback(@Flag int flags) {
3318 Preconditions.checkArgument((flags & VALID_FLAGS) == flags);
3319 mFlags = flags;
3320 }
3321
3322 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003323 * Called when the framework connects to a new network to evaluate whether it satisfies this
3324 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3325 * callback. There is no guarantee that this new network will satisfy any requests, or that
3326 * the network will stay connected for longer than the time necessary to evaluate it.
3327 * <p>
3328 * Most applications <b>should not</b> act on this callback, and should instead use
3329 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3330 * the framework in properly evaluating the network &mdash; for example, an application that
3331 * can automatically log in to a captive portal without user intervention.
3332 *
3333 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003334 *
3335 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003336 */
paulhu1a407652019-03-22 16:35:06 +08003337 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003338
3339 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003340 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003341 * This callback may be called more than once if the {@link Network} that is
3342 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003343 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003344 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003345 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3346 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003347 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003348 * @hide
3349 */
paulhu1a407652019-03-22 16:35:06 +08003350 public void onAvailable(@NonNull Network network,
3351 @NonNull NetworkCapabilities networkCapabilities,
3352 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003353 // Internally only this method is called when a new network is available, and
3354 // it calls the callback in the same way and order that older versions used
3355 // to call so as not to change the behavior.
3356 onAvailable(network);
3357 if (!networkCapabilities.hasCapability(
3358 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3359 onNetworkSuspended(network);
3360 }
3361 onCapabilitiesChanged(network, networkCapabilities);
3362 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003363 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003364 }
3365
3366 /**
3367 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003368 *
3369 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3370 * be available at the same time, and onAvailable will be called for each of these as they
3371 * appear.
3372 *
3373 * <p>For callbacks registered with {@link #requestNetwork} and
3374 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3375 * is the new best network for this request and is now tracked by this callback ; this
3376 * callback will no longer receive method calls about other networks that may have been
3377 * passed to this method previously. The previously-best network may have disconnected, or
3378 * it may still be around and the newly-best network may simply be better.
3379 *
3380 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3381 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3382 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3383 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3384 *
3385 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3386 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3387 * this callback as this is prone to race conditions (there is no guarantee the objects
3388 * returned by these methods will be current). Instead, wait for a call to
3389 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3390 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3391 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003392 *
3393 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003394 */
paulhu1a407652019-03-22 16:35:06 +08003395 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003396
3397 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003398 * Called when the network is about to be lost, typically because there are no outstanding
3399 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3400 * with the new replacement network for graceful handover. This method is not guaranteed
3401 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3402 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003403 *
Chalard Jean01378b62019-08-30 16:27:28 +09003404 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3405 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3406 * this callback as this is prone to race conditions ; calling these methods while in a
3407 * callback may return an outdated or even a null object.
3408 *
3409 * @param network The {@link Network} that is about to be lost.
3410 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3411 * connected for graceful handover; note that the network may still
3412 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003413 */
paulhu1a407652019-03-22 16:35:06 +08003414 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003415
3416 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003417 * Called when a network disconnects or otherwise no longer satisfies this request or
3418 * callback.
3419 *
3420 * <p>If the callback was registered with requestNetwork() or
3421 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3422 * returned by onAvailable() when that network is lost and no other network satisfies
3423 * the criteria of the request.
3424 *
3425 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3426 * each network which no longer satisfies the criteria of the callback.
3427 *
3428 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3429 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3430 * this callback as this is prone to race conditions ; calling these methods while in a
3431 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003432 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003433 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003434 */
paulhu1a407652019-03-22 16:35:06 +08003435 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003436
3437 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003438 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003439 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3440 * requested network request cannot be fulfilled (whether or not a timeout was
3441 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003442 * {@link NetworkRequest} will have already been removed and released, as if
3443 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003444 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003445 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003446
3447 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003448 * Called when the network corresponding to this request changes capabilities but still
3449 * satisfies the requested criteria.
3450 *
3451 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3452 * to be called immediately after {@link #onAvailable}.
3453 *
3454 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3455 * ConnectivityManager methods in this callback as this is prone to race conditions :
3456 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003457 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003458 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius951c0032020-12-22 15:10:42 -08003459 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003460 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003461 */
paulhu1a407652019-03-22 16:35:06 +08003462 public void onCapabilitiesChanged(@NonNull Network network,
3463 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003464
3465 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003466 * Called when the network corresponding to this request changes {@link LinkProperties}.
3467 *
3468 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3469 * to be called immediately after {@link #onAvailable}.
3470 *
3471 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3472 * ConnectivityManager methods in this callback as this is prone to race conditions :
3473 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003474 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003475 * @param network The {@link Network} whose link properties have changed.
3476 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003477 */
paulhu1a407652019-03-22 16:35:06 +08003478 public void onLinkPropertiesChanged(@NonNull Network network,
3479 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003480
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003481 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003482 * Called when the network the framework connected to for this request suspends data
3483 * transmission temporarily.
3484 *
3485 * <p>This generally means that while the TCP connections are still live temporarily
3486 * network data fails to transfer. To give a specific example, this is used on cellular
3487 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3488 * means read operations on sockets on this network will block once the buffers are
3489 * drained, and write operations will block once the buffers are full.
3490 *
3491 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3492 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3493 * this callback as this is prone to race conditions (there is no guarantee the objects
3494 * returned by these methods will be current).
3495 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003496 * @hide
3497 */
paulhu1a407652019-03-22 16:35:06 +08003498 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003499
3500 /**
3501 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003502 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3503 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003504
3505 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3506 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3507 * this callback as this is prone to race conditions : calling these methods while in a
3508 * callback may return an outdated or even a null object.
3509 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003510 * @hide
3511 */
paulhu1a407652019-03-22 16:35:06 +08003512 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003513
junyulaif2c67e42018-08-07 19:50:45 +08003514 /**
3515 * Called when access to the specified network is blocked or unblocked.
3516 *
Chalard Jean01378b62019-08-30 16:27:28 +09003517 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3518 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3519 * this callback as this is prone to race conditions : calling these methods while in a
3520 * callback may return an outdated or even a null object.
3521 *
junyulaif2c67e42018-08-07 19:50:45 +08003522 * @param network The {@link Network} whose blocked status has changed.
3523 * @param blocked The blocked status of this {@link Network}.
3524 */
junyulai7e06ad42019-03-04 22:45:36 +08003525 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003526
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003527 private NetworkRequest networkRequest;
Roshan Pius951c0032020-12-22 15:10:42 -08003528 private final int mFlags;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003529 }
3530
Hugo Benichia590ab82017-05-11 13:16:17 +09003531 /**
3532 * Constant error codes used by ConnectivityService to communicate about failures and errors
3533 * across a Binder boundary.
3534 * @hide
3535 */
3536 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003537 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003538 }
3539
3540 /** @hide */
3541 public static class TooManyRequestsException extends RuntimeException {}
3542
3543 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3544 switch (e.errorCode) {
3545 case Errors.TOO_MANY_REQUESTS:
3546 return new TooManyRequestsException();
3547 default:
3548 Log.w(TAG, "Unknown service error code " + e.errorCode);
3549 return new RuntimeException(e);
3550 }
3551 }
3552
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003553 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003554 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003555 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003556 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003557 /** @hide arg1 = TTL */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003558 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003559 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003560 public static final int CALLBACK_LOST = 4;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003561 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003562 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003563 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003564 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003565 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003566 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003567 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003568 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003569 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003570 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003571 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003572 public static final int CALLBACK_RESUMED = 10;
junyulaif2c67e42018-08-07 19:50:45 +08003573 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003574 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003575
Erik Kline155a59a2015-11-25 12:49:38 +09003576 /** @hide */
3577 public static String getCallbackName(int whichCallback) {
3578 switch (whichCallback) {
3579 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3580 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3581 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3582 case CALLBACK_LOST: return "CALLBACK_LOST";
3583 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3584 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3585 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003586 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3587 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3588 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003589 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003590 default:
3591 return Integer.toString(whichCallback);
3592 }
3593 }
3594
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003595 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003596 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003597 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003598
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003599 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003600 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003601 }
3602
Hugo Benichifd44e912017-02-02 17:02:36 +09003603 CallbackHandler(Handler handler) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00003604 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003605 }
3606
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003607 @Override
3608 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003609 if (message.what == EXPIRE_LEGACY_REQUEST) {
3610 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3611 return;
3612 }
3613
3614 final NetworkRequest request = getObject(message, NetworkRequest.class);
3615 final Network network = getObject(message, Network.class);
3616 final NetworkCallback callback;
3617 synchronized (sCallbacks) {
3618 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003619 if (callback == null) {
3620 Log.w(TAG,
3621 "callback not found for " + getCallbackName(message.what) + " message");
3622 return;
3623 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003624 if (message.what == CALLBACK_UNAVAIL) {
3625 sCallbacks.remove(request);
3626 callback.networkRequest = ALREADY_UNREGISTERED;
3627 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003628 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003629 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003630 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003631 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003632
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003633 switch (message.what) {
3634 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003635 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003636 break;
3637 }
3638 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003639 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3640 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003641 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003642 break;
3643 }
3644 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003645 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003646 break;
3647 }
3648 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003649 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003650 break;
3651 }
3652 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003653 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003654 break;
3655 }
3656 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003657 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3658 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003659 break;
3660 }
3661 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003662 LinkProperties lp = getObject(message, LinkProperties.class);
3663 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003664 break;
3665 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003666 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003667 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003668 break;
3669 }
3670 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003671 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003672 break;
3673 }
junyulaif2c67e42018-08-07 19:50:45 +08003674 case CALLBACK_BLK_CHANGED: {
3675 boolean blocked = message.arg1 != 0;
3676 callback.onBlockedStatusChanged(network, blocked);
3677 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003678 }
3679 }
3680
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003681 private <T> T getObject(Message msg, Class<T> c) {
3682 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003683 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003684 }
3685
Hugo Benichifd44e912017-02-02 17:02:36 +09003686 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003687 synchronized (sCallbacks) {
3688 if (sCallbackHandler == null) {
3689 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003690 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003691 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003692 }
3693 }
3694
Hugo Benichibc4ac972017-02-03 14:18:44 +09003695 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3696 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003697
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003698 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3699 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3700 CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003701 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003702 checkCallbackNotNull(callback);
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00003703 Preconditions.checkArgument(
3704 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3705 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003706 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003707 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003708 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003709 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003710 if (callback.networkRequest != null
3711 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003712 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3713 // and requests (http://b/20701525).
3714 Log.e(TAG, "NetworkCallback was already registered");
3715 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003716 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003717 Binder binder = new Binder();
Roshan Pius951c0032020-12-22 15:10:42 -08003718 final int callbackFlags = callback.mFlags;
junyulaiad010792021-01-11 16:53:38 +08003719 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003720 request = mService.listenForNetwork(
Roshan Pius951c0032020-12-22 15:10:42 -08003721 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003722 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003723 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003724 request = mService.requestNetwork(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003725 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3726 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003727 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003728 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003729 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003730 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003731 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003732 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003733 } catch (RemoteException e) {
3734 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003735 } catch (ServiceSpecificException e) {
3736 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003737 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003738 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003739 }
3740
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003741 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3742 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3743 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3744 legacyType, handler);
3745 }
3746
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003747 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003748 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003749 *
markchienfac84a22020-03-18 21:16:15 +08003750 * This API is only for use in internal system code that requests networks with legacy type and
3751 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003752 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003753 *
markchiend6eeffd2020-01-14 00:55:21 +08003754 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003755 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3756 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3757 * be a positive value (i.e. >0).
3758 * @param legacyType to specify the network type(#TYPE_*).
3759 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003760 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3761 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003762 *
3763 * @hide
3764 */
markchiend6eeffd2020-01-14 00:55:21 +08003765 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003766 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003767 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003768 int timeoutMs, int legacyType, @NonNull Handler handler,
3769 @NonNull NetworkCallback networkCallback) {
3770 if (legacyType == TYPE_NONE) {
3771 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3772 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003773 CallbackHandler cbHandler = new CallbackHandler(handler);
3774 NetworkCapabilities nc = request.networkCapabilities;
3775 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003776 }
3777
3778 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003779 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003780 *
Chalard Jean01378b62019-08-30 16:27:28 +09003781 * <p>This method will attempt to find the best network that matches the passed
3782 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3783 * criteria. The platform will evaluate which network is the best at its own discretion.
3784 * Throughput, latency, cost per byte, policy, user preference and other considerations
3785 * may be factored in the decision of what is considered the best network.
3786 *
3787 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3788 * matching this request, while always attempting to match the request to a better network if
3789 * possible. If a better match is found, the platform will switch this request to the now-best
3790 * network and inform the app of the newly best network by invoking
3791 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3792 * will not try to maintain any other network than the best one currently matching the request:
3793 * a network not matching any network request may be disconnected at any time.
3794 *
3795 * <p>For example, an application could use this method to obtain a connected cellular network
3796 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3797 * radio to consume additional power. Or, an application could inform the system that it wants
3798 * a network supporting sending MMSes and have the system let it know about the currently best
3799 * MMS-supporting network through the provided {@link NetworkCallback}.
3800 *
3801 * <p>The status of the request can be followed by listening to the various callbacks described
3802 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3803 * used to direct traffic to the network (although accessing some networks may be subject to
3804 * holding specific permissions). Callers will learn about the specific characteristics of the
3805 * network through
3806 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3807 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3808 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3809 * matching the request at any given time; therefore when a better network matching the request
3810 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3811 * with the new network after which no further updates are given about the previously-best
3812 * network, unless it becomes the best again at some later time. All callbacks are invoked
3813 * in order on the same thread, which by default is a thread created by the framework running
3814 * in the app.
3815 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3816 * callbacks are invoked.
3817 *
3818 * <p>This{@link NetworkRequest} will live until released via
3819 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3820 * which point the system may let go of the network at any time.
3821 *
3822 * <p>A version of this method which takes a timeout is
3823 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3824 * wait for a limited amount of time for the network to become unavailable.
3825 *
Paul Jensenee52d232015-06-16 15:11:58 -04003826 * <p>It is presently unsupported to request a network with mutable
3827 * {@link NetworkCapabilities} such as
3828 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3829 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3830 * as these {@code NetworkCapabilities} represent states that a particular
3831 * network may never attain, and whether a network will attain these states
3832 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003833 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003834 *
3835 * <p>This method requires the caller to hold either the
3836 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3837 * or the ability to modify system settings as determined by
3838 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003839 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003840 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3841 * number of outstanding requests to 100 per app (identified by their UID), shared with
3842 * all variants of this method, of {@link #registerNetworkCallback} as well as
3843 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3844 * Requesting a network with this method will count toward this limit. If this limit is
3845 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3846 * make sure to unregister the callbacks with
3847 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3848 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003849 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003850 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3851 * the callback must not be shared - it uniquely specifies this request.
3852 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003853 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3854 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003855 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003856 */
Chalard Jean158702d2019-01-07 19:26:34 +09003857 public void requestNetwork(@NonNull NetworkRequest request,
3858 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003859 requestNetwork(request, networkCallback, getDefaultHandler());
3860 }
3861
3862 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003863 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichifd44e912017-02-02 17:02:36 +09003864 *
Chalard Jean01378b62019-08-30 16:27:28 +09003865 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3866 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003867 *
Chalard Jean01378b62019-08-30 16:27:28 +09003868 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003869 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3870 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003871 *
3872 * @param request {@link NetworkRequest} describing this request.
3873 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3874 * the callback must not be shared - it uniquely specifies this request.
3875 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003876 */
Chalard Jean158702d2019-01-07 19:26:34 +09003877 public void requestNetwork(@NonNull NetworkRequest request,
3878 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003879 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003880 NetworkCapabilities nc = request.networkCapabilities;
3881 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003882 }
3883
3884 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003885 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohenf67bde92017-03-01 12:47:28 -08003886 * by a timeout.
3887 *
3888 * This function behaves identically to the non-timed-out version
3889 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3890 * is not found within the given time (in milliseconds) the
3891 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3892 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3893 * not have to be released if timed-out (it is automatically released). Unregistering a
3894 * request that timed out is not an error.
3895 *
3896 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3897 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3898 * for that purpose. Calling this method will attempt to bring up the requested network.
3899 *
Chalard Jean01378b62019-08-30 16:27:28 +09003900 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003901 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3902 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003903 *
3904 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003905 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3906 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003907 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3908 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3909 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003910 */
Chalard Jean158702d2019-01-07 19:26:34 +09003911 public void requestNetwork(@NonNull NetworkRequest request,
3912 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003913 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003914 NetworkCapabilities nc = request.networkCapabilities;
3915 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3916 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003917 }
3918
Hugo Benichifd44e912017-02-02 17:02:36 +09003919 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003920 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichifd44e912017-02-02 17:02:36 +09003921 * by a timeout.
3922 *
Chalard Jean01378b62019-08-30 16:27:28 +09003923 * This method behaves identically to
3924 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3925 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003926 *
Chalard Jean01378b62019-08-30 16:27:28 +09003927 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003928 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3929 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003930 *
3931 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003932 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3933 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003934 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003935 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3936 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003937 */
Chalard Jean158702d2019-01-07 19:26:34 +09003938 public void requestNetwork(@NonNull NetworkRequest request,
3939 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003940 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003941 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003942 NetworkCapabilities nc = request.networkCapabilities;
3943 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003944 }
3945
3946 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003947 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003948 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003949 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003950 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003951 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3952 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003953 */
Erik Kline8a826212014-11-19 12:12:24 +09003954 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003955
3956 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003957 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003958 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003959 * {@link android.content.Intent#getParcelableExtra(String)}.
3960 */
Erik Kline8a826212014-11-19 12:12:24 +09003961 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003962
3963
3964 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003965 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003966 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003967 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003968 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003969 * the request may outlive the calling application and get called back when a suitable
3970 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003971 * <p>
3972 * The operation is an Intent broadcast that goes to a broadcast receiver that
3973 * you registered with {@link Context#registerReceiver} or through the
3974 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3975 * <p>
3976 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003977 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3978 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003979 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003980 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003981 * Intent to reserve the network or it will be released shortly after the Intent
3982 * is processed.
3983 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003984 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003985 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003986 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003987 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003988 * The request may be released normally by calling
3989 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003990 * <p>It is presently unsupported to request a network with either
3991 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3992 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3993 * as these {@code NetworkCapabilities} represent states that a particular
3994 * network may never attain, and whether a network will attain these states
3995 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003996 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003997 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003998 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3999 * number of outstanding requests to 100 per app (identified by their UID), shared with
4000 * all variants of this method, of {@link #registerNetworkCallback} as well as
4001 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4002 * Requesting a network with this method will count toward this limit. If this limit is
4003 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4004 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4005 * or {@link #releaseNetworkRequest(PendingIntent)}.
4006 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004007 * <p>This method requires the caller to hold either the
4008 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4009 * or the ability to modify system settings as determined by
4010 * {@link android.provider.Settings.System#canWrite}.</p>
4011 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004012 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004013 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004014 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004015 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004016 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4017 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004018 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004019 */
Chalard Jean158702d2019-01-07 19:26:34 +09004020 public void requestNetwork(@NonNull NetworkRequest request,
4021 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004022 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004023 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004024 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004025 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004026 request.networkCapabilities, operation, mContext.getOpPackageName(),
4027 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004028 } catch (RemoteException e) {
4029 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004030 } catch (ServiceSpecificException e) {
4031 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004032 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004033 }
4034
4035 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004036 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4037 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004038 * This method has the same behavior as
4039 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004040 * releasing network resources and disconnecting.
4041 *
4042 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4043 * PendingIntent passed to
4044 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4045 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4046 */
Chalard Jean158702d2019-01-07 19:26:34 +09004047 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004048 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004049 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004050 try {
4051 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004052 } catch (RemoteException e) {
4053 throw e.rethrowFromSystemServer();
4054 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004055 }
4056
Hugo Benichibc1104b2017-05-09 15:19:01 +09004057 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004058 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004059 }
4060
4061 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004062 Preconditions.checkNotNull(callback, "null NetworkCallback");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004063 }
4064
4065 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004066 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004067 }
4068
4069 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004070 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004071 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004072 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4073 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004074 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004075 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4076 * number of outstanding requests to 100 per app (identified by their UID), shared with
4077 * all variants of this method, of {@link #requestNetwork} as well as
4078 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4079 * Requesting a network with this method will count toward this limit. If this limit is
4080 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4081 * make sure to unregister the callbacks with
4082 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4083 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004084 * @param request {@link NetworkRequest} describing this request.
4085 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4086 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004087 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004088 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004089 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004090 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004091 public void registerNetworkCallback(@NonNull NetworkRequest request,
4092 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004093 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4094 }
4095
4096 /**
4097 * Registers to receive notifications about all networks which satisfy the given
4098 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004099 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4100 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004101 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004102 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4103 * number of outstanding requests to 100 per app (identified by their UID), shared with
4104 * all variants of this method, of {@link #requestNetwork} as well as
4105 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4106 * Requesting a network with this method will count toward this limit. If this limit is
4107 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4108 * make sure to unregister the callbacks with
4109 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4110 *
4111 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004112 * @param request {@link NetworkRequest} describing this request.
4113 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4114 * networks change state.
4115 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004116 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004117 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004118 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004119 public void registerNetworkCallback(@NonNull NetworkRequest request,
4120 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004121 CallbackHandler cbHandler = new CallbackHandler(handler);
4122 NetworkCapabilities nc = request.networkCapabilities;
4123 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004124 }
4125
4126 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004127 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4128 * {@link NetworkRequest}.
4129 *
4130 * This function behaves identically to the version that takes a NetworkCallback, but instead
4131 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4132 * the request may outlive the calling application and get called back when a suitable
4133 * network is found.
4134 * <p>
4135 * The operation is an Intent broadcast that goes to a broadcast receiver that
4136 * you registered with {@link Context#registerReceiver} or through the
4137 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4138 * <p>
4139 * The operation Intent is delivered with two extras, a {@link Network} typed
4140 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4141 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4142 * the original requests parameters.
4143 * <p>
4144 * If there is already a request for this Intent registered (with the equality of
4145 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4146 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4147 * <p>
4148 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004149 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004150 *
4151 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4152 * number of outstanding requests to 100 per app (identified by their UID), shared with
4153 * all variants of this method, of {@link #requestNetwork} as well as
4154 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4155 * Requesting a network with this method will count toward this limit. If this limit is
4156 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4157 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4158 * or {@link #releaseNetworkRequest(PendingIntent)}.
4159 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004160 * @param request {@link NetworkRequest} describing this request.
4161 * @param operation Action to perform when the network is available (corresponds
4162 * to the {@link NetworkCallback#onAvailable} call. Typically
4163 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004164 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004165 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004166 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004167 public void registerNetworkCallback(@NonNull NetworkRequest request,
4168 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004169 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004170 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004171 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004172 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004173 request.networkCapabilities, operation, mContext.getOpPackageName(),
4174 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004175 } catch (RemoteException e) {
4176 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004177 } catch (ServiceSpecificException e) {
4178 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004179 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004180 }
4181
4182 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004183 * Registers to receive notifications about changes in the application's default network. This
4184 * may be a physical network or a virtual network, such as a VPN that applies to the
4185 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004186 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004187 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004188 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4189 * number of outstanding requests to 100 per app (identified by their UID), shared with
4190 * all variants of this method, of {@link #requestNetwork} as well as
4191 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4192 * Requesting a network with this method will count toward this limit. If this limit is
4193 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4194 * make sure to unregister the callbacks with
4195 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4196 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004197 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004198 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004199 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004200 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004201 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004202 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004203 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004204 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4205 }
4206
4207 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004208 * Registers to receive notifications about changes in the application's default network. This
4209 * may be a physical network or a virtual network, such as a VPN that applies to the
4210 * application. The callbacks will continue to be called until either the application exits or
4211 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4212 *
4213 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4214 * number of outstanding requests to 100 per app (identified by their UID), shared with
4215 * all variants of this method, of {@link #requestNetwork} as well as
4216 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4217 * Requesting a network with this method will count toward this limit. If this limit is
4218 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4219 * make sure to unregister the callbacks with
4220 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4221 *
4222 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4223 * application's default network changes.
4224 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4225 * @throws RuntimeException if the app already has too many callbacks registered.
4226 */
4227 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4228 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4229 @NonNull Handler handler) {
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004230 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4231 }
4232
4233 /**
4234 * Registers to receive notifications about changes in the default network for the specified
4235 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4236 * UID. The callbacks will continue to be called until either the application exits or
4237 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4238 *
4239 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4240 * number of outstanding requests to 100 per app (identified by their UID), shared with
4241 * all variants of this method, of {@link #requestNetwork} as well as
4242 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4243 * Requesting a network with this method will count toward this limit. If this limit is
4244 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4245 * make sure to unregister the callbacks with
4246 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4247 *
4248 * @param uid the UID for which to track default network changes.
4249 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4250 * UID's default network changes.
4251 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4252 * @throws RuntimeException if the app already has too many callbacks registered.
4253 * @hide
4254 */
4255 // TODO: @SystemApi(client=MODULE_LIBRARIES)
4256 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4257 @RequiresPermission(anyOf = {
4258 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4259 android.Manifest.permission.NETWORK_SETTINGS})
4260 public void registerDefaultNetworkCallbackAsUid(int uid,
4261 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004262 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004263 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004264 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4265 }
4266
4267 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004268 * Registers to receive notifications about changes in the system default network. The callbacks
4269 * will continue to be called until either the application exits or
4270 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004271 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004272 * This method should not be used to determine networking state seen by applications, because in
4273 * many cases, most or even all application traffic may not use the default network directly,
4274 * and traffic from different applications may go on different networks by default. As an
4275 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4276 * and not onto the system default network. Applications or system components desiring to do
4277 * determine network state as seen by applications should use other methods such as
4278 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4279 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004280 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4281 * number of outstanding requests to 100 per app (identified by their UID), shared with
4282 * all variants of this method, of {@link #requestNetwork} as well as
4283 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4284 * Requesting a network with this method will count toward this limit. If this limit is
4285 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4286 * make sure to unregister the callbacks with
4287 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4288 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004289 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4290 * system default network changes.
4291 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004292 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004293 *
4294 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004295 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004296 @SystemApi(client = MODULE_LIBRARIES)
4297 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4298 @RequiresPermission(anyOf = {
4299 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4300 android.Manifest.permission.NETWORK_SETTINGS})
4301 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004302 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004303 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004304 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004305 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004306 }
4307
4308 /**
junyulai8eb13a22021-03-15 11:48:48 +08004309 * Registers to receive notifications about the best matching network which satisfy the given
4310 * {@link NetworkRequest}. The callbacks will continue to be called until
4311 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4312 * called.
4313 *
4314 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4315 * number of outstanding requests to 100 per app (identified by their UID), shared with
4316 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4317 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4318 * Requesting a network with this method will count toward this limit. If this limit is
4319 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4320 * make sure to unregister the callbacks with
4321 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4322 *
4323 *
4324 * @param request {@link NetworkRequest} describing this request.
4325 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4326 * networks change state.
4327 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4328 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai7514e312021-03-05 15:51:17 +08004329 */
junyulai7514e312021-03-05 15:51:17 +08004330 @SuppressLint("ExecutorRegistration")
4331 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4332 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4333 final NetworkCapabilities nc = request.networkCapabilities;
4334 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai1b1c8742021-03-12 20:05:08 +08004335 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai7514e312021-03-05 15:51:17 +08004336 }
4337
4338 /**
fenglub00f4882015-04-21 17:12:05 -07004339 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4340 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4341 * network connection for updated bandwidth information. The caller will be notified via
4342 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004343 * method assumes that the caller has previously called
4344 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4345 * changes.
fenglu3f357402015-03-20 11:29:56 -07004346 *
fengluea2d9282015-04-27 14:28:04 -07004347 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004348 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004349 */
Chalard Jean158702d2019-01-07 19:26:34 +09004350 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004351 try {
fenglub00f4882015-04-21 17:12:05 -07004352 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004353 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004354 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004355 }
4356 }
4357
4358 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004359 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004360 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4361 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4362 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004363 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4364 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004365 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004366 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4367 * triggering it as soon as this call returns.
4368 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004369 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004370 */
Chalard Jean158702d2019-01-07 19:26:34 +09004371 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004372 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004373 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004374 final List<NetworkRequest> reqs = new ArrayList<>();
4375 // Find all requests associated to this callback and stop callback triggers immediately.
4376 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4377 synchronized (sCallbacks) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004378 Preconditions.checkArgument(networkCallback.networkRequest != null,
4379 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004380 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4381 Log.d(TAG, "NetworkCallback was already unregistered");
4382 return;
4383 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004384 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4385 if (e.getValue() == networkCallback) {
4386 reqs.add(e.getKey());
4387 }
4388 }
4389 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4390 for (NetworkRequest r : reqs) {
4391 try {
4392 mService.releaseNetworkRequest(r);
4393 } catch (RemoteException e) {
4394 throw e.rethrowFromSystemServer();
4395 }
4396 // Only remove mapping if rpc was successful.
4397 sCallbacks.remove(r);
4398 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004399 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004400 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004401 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004402
4403 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004404 * Unregisters a callback previously registered via
4405 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4406 *
4407 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4408 * PendingIntent passed to
4409 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4410 * Cannot be null.
4411 */
Chalard Jean158702d2019-01-07 19:26:34 +09004412 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004413 releaseNetworkRequest(operation);
4414 }
4415
4416 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004417 * Informs the system whether it should switch to {@code network} regardless of whether it is
4418 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4419 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4420 * the system default network regardless of any other network that's currently connected. If
4421 * {@code always} is true, then the choice is remembered, so that the next time the user
4422 * connects to this network, the system will switch to it.
4423 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004424 * @param network The network to accept.
4425 * @param accept Whether to accept the network even if unvalidated.
4426 * @param always Whether to remember this choice in the future.
4427 *
4428 * @hide
4429 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004430 @SystemApi(client = MODULE_LIBRARIES)
4431 @RequiresPermission(anyOf = {
4432 android.Manifest.permission.NETWORK_SETTINGS,
4433 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4434 android.Manifest.permission.NETWORK_STACK,
4435 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4436 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004437 try {
4438 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004439 } catch (RemoteException e) {
4440 throw e.rethrowFromSystemServer();
4441 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004442 }
4443
4444 /**
lucaslin2240ef62019-03-12 13:08:03 +08004445 * Informs the system whether it should consider the network as validated even if it only has
4446 * partial connectivity. If {@code accept} is true, then the network will be considered as
4447 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4448 * is remembered, so that the next time the user connects to this network, the system will
4449 * switch to it.
4450 *
4451 * @param network The network to accept.
4452 * @param accept Whether to consider the network as validated even if it has partial
4453 * connectivity.
4454 * @param always Whether to remember this choice in the future.
4455 *
4456 * @hide
4457 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004458 @SystemApi(client = MODULE_LIBRARIES)
4459 @RequiresPermission(anyOf = {
4460 android.Manifest.permission.NETWORK_SETTINGS,
4461 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4462 android.Manifest.permission.NETWORK_STACK,
4463 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4464 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4465 boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004466 try {
4467 mService.setAcceptPartialConnectivity(network, accept, always);
4468 } catch (RemoteException e) {
4469 throw e.rethrowFromSystemServer();
4470 }
4471 }
4472
4473 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004474 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4475 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4476 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4477 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4478 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004479 * @param network The network to accept.
4480 *
4481 * @hide
4482 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004483 @SystemApi(client = MODULE_LIBRARIES)
4484 @RequiresPermission(anyOf = {
4485 android.Manifest.permission.NETWORK_SETTINGS,
4486 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4487 android.Manifest.permission.NETWORK_STACK,
4488 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4489 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004490 try {
4491 mService.setAvoidUnvalidated(network);
4492 } catch (RemoteException e) {
4493 throw e.rethrowFromSystemServer();
4494 }
4495 }
4496
4497 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004498 * Requests that the system open the captive portal app on the specified network.
4499 *
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004500 * <p>This is to be used on networks where a captive portal was detected, as per
4501 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4502 *
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004503 * @param network The network to log into.
4504 *
4505 * @hide
4506 */
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004507 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4508 @RequiresPermission(anyOf = {
4509 android.Manifest.permission.NETWORK_SETTINGS,
4510 android.Manifest.permission.NETWORK_STACK,
4511 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4512 })
4513 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004514 try {
4515 mService.startCaptivePortalApp(network);
4516 } catch (RemoteException e) {
4517 throw e.rethrowFromSystemServer();
4518 }
4519 }
4520
4521 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004522 * Requests that the system open the captive portal app with the specified extras.
4523 *
4524 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4525 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004526 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004527 * @param appExtras Extras to include in the app start intent.
4528 * @hide
4529 */
4530 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004531 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004532 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004533 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004534 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004535 } catch (RemoteException e) {
4536 throw e.rethrowFromSystemServer();
4537 }
4538 }
4539
4540 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004541 * Determine whether the device is configured to avoid bad wifi.
4542 * @hide
4543 */
4544 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004545 @RequiresPermission(anyOf = {
4546 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4547 android.Manifest.permission.NETWORK_STACK})
4548 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004549 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004550 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004551 } catch (RemoteException e) {
4552 throw e.rethrowFromSystemServer();
4553 }
4554 }
4555
4556 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004557 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4558 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004559 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4560 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004561 *
4562 * An example of such an operation might be a time-sensitive foreground activity, such as a
4563 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4564 */
4565 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4566
4567 /**
4568 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4569 * a backup channel for traffic that is primarily going over another network.
4570 *
4571 * An example might be maintaining backup connections to peers or servers for the purpose of
4572 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4573 * on backup paths should be negligible compared to the traffic on the main path.
4574 */
4575 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4576
4577 /**
4578 * It is acceptable to use metered data to improve network latency and performance.
4579 */
4580 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4581
4582 /**
4583 * Return value to use for unmetered networks. On such networks we currently set all the flags
4584 * to true.
4585 * @hide
4586 */
4587 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4588 MULTIPATH_PREFERENCE_HANDOVER |
4589 MULTIPATH_PREFERENCE_RELIABILITY |
4590 MULTIPATH_PREFERENCE_PERFORMANCE;
4591
4592 /** @hide */
4593 @Retention(RetentionPolicy.SOURCE)
4594 @IntDef(flag = true, value = {
4595 MULTIPATH_PREFERENCE_HANDOVER,
4596 MULTIPATH_PREFERENCE_RELIABILITY,
4597 MULTIPATH_PREFERENCE_PERFORMANCE,
4598 })
4599 public @interface MultipathPreference {
4600 }
4601
4602 /**
4603 * Provides a hint to the calling application on whether it is desirable to use the
4604 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4605 * for multipath data transfer on this network when it is not the system default network.
4606 * Applications desiring to use multipath network protocols should call this method before
4607 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004608 *
4609 * @param network The network on which the application desires to use multipath data.
4610 * If {@code null}, this method will return the a preference that will generally
4611 * apply to metered networks.
4612 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4613 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004614 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004615 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004616 try {
4617 return mService.getMultipathPreference(network);
4618 } catch (RemoteException e) {
4619 throw e.rethrowFromSystemServer();
4620 }
4621 }
4622
4623 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004624 * Resets all connectivity manager settings back to factory defaults.
4625 * @hide
4626 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004627 @SystemApi(client = MODULE_LIBRARIES)
4628 @RequiresPermission(anyOf = {
4629 android.Manifest.permission.NETWORK_SETTINGS,
4630 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scott0f835ac2015-03-30 13:17:11 -07004631 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004632 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004633 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004634 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004635 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004636 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004637 }
4638 }
4639
4640 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004641 * Binds the current process to {@code network}. All Sockets created in the future
4642 * (and not explicitly bound via a bound SocketFactory from
4643 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4644 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4645 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4646 * work and all host name resolutions will fail. This is by design so an application doesn't
4647 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4648 * To clear binding pass {@code null} for {@code network}. Using individually bound
4649 * Sockets created by Network.getSocketFactory().createSocket() and
4650 * performing network-specific host name resolutions via
4651 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004652 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004653 *
4654 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4655 * the current binding.
4656 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4657 */
Chalard Jean158702d2019-01-07 19:26:34 +09004658 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004659 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004660 // instantiated.
4661 return setProcessDefaultNetwork(network);
4662 }
4663
4664 /**
4665 * Binds the current process to {@code network}. All Sockets created in the future
4666 * (and not explicitly bound via a bound SocketFactory from
4667 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4668 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4669 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4670 * work and all host name resolutions will fail. This is by design so an application doesn't
4671 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4672 * To clear binding pass {@code null} for {@code network}. Using individually bound
4673 * Sockets created by Network.getSocketFactory().createSocket() and
4674 * performing network-specific host name resolutions via
4675 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4676 * {@code setProcessDefaultNetwork}.
4677 *
4678 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4679 * the current binding.
4680 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4681 * @deprecated This function can throw {@link IllegalStateException}. Use
4682 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4683 * is a direct replacement.
4684 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004685 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004686 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004687 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004688 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4689
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004690 if (netId != NETID_UNSET) {
4691 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004692 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004693
4694 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4695 return false;
4696 }
4697
4698 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004699 // Set HTTP proxy system properties to match network.
4700 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004701 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004702 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004703 } catch (SecurityException e) {
4704 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4705 Log.e(TAG, "Can't set proxy properties", e);
4706 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004707 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANe1b04f62021-03-18 23:27:19 +09004708 InetAddressCompat.clearDnsCache();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004709 // Must flush socket pool as idle sockets will be bound to previous network and may
4710 // cause subsequent fetches to be performed on old network.
4711 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004712 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004713
4714 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004715 }
4716
4717 /**
4718 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004719 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004720 *
4721 * @return {@code Network} to which this process is bound, or {@code null}.
4722 */
Chalard Jean158702d2019-01-07 19:26:34 +09004723 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004724 public Network getBoundNetworkForProcess() {
4725 // Forcing callers to call thru non-static function ensures ConnectivityManager
4726 // instantiated.
4727 return getProcessDefaultNetwork();
4728 }
4729
4730 /**
4731 * Returns the {@link Network} currently bound to this process via
4732 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4733 *
4734 * @return {@code Network} to which this process is bound, or {@code null}.
4735 * @deprecated Using this function can lead to other functions throwing
4736 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4737 * {@code getBoundNetworkForProcess} is a direct replacement.
4738 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004739 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004740 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004741 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004742 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004743 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004744 return new Network(netId);
4745 }
4746
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004747 private void unsupportedStartingFrom(int version) {
4748 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004749 // The getApplicationInfo() call we make below is not supported in system context. Let
4750 // the call through here, and rely on the fact that ConnectivityService will refuse to
4751 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004752 return;
4753 }
4754
4755 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4756 throw new UnsupportedOperationException(
4757 "This method is not supported in target SDK version " + version + " and above");
4758 }
4759 }
4760
4761 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4762 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004763 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004764 // remove these exemptions. Note that this check is not secure, and apps can still access these
4765 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4766 // so is unsupported and may break in the future. http://b/22728205
4767 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004768 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004769 }
4770
Paul Jensen8cdda642014-05-29 10:12:39 -04004771 /**
4772 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004773 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004774 *
4775 * @param network The {@link Network} to bind host resolutions from the current process to, or
4776 * {@code null} to clear the current binding.
4777 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4778 * @hide
4779 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4780 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004781 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004782 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004783 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004784 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004785 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004786 }
Felipe Leme30511352016-01-22 09:44:57 -08004787
4788 /**
4789 * Device is not restricting metered network activity while application is running on
4790 * background.
4791 */
4792 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4793
4794 /**
4795 * Device is restricting metered network activity while application is running on background,
4796 * but application is allowed to bypass it.
4797 * <p>
4798 * In this state, application should take action to mitigate metered network access.
4799 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4800 */
4801 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4802
4803 /**
4804 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004805 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004806 * In this state, application should not try to use the network while running on background,
4807 * because it would be denied.
4808 */
4809 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4810
Felipe Lemed34c9af2016-01-27 14:46:39 -08004811 /**
4812 * A change in the background metered network activity restriction has occurred.
4813 * <p>
4814 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4815 * applies to them.
4816 * <p>
4817 * This is only sent to registered receivers, not manifest receivers.
4818 */
4819 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4820 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4821 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4822
Felipe Leme7e4c1852016-01-25 11:48:04 -08004823 /** @hide */
4824 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004825 @IntDef(flag = false, value = {
4826 RESTRICT_BACKGROUND_STATUS_DISABLED,
4827 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4828 RESTRICT_BACKGROUND_STATUS_ENABLED,
4829 })
Felipe Leme30511352016-01-22 09:44:57 -08004830 public @interface RestrictBackgroundStatus {
4831 }
4832
Felipe Leme30511352016-01-22 09:44:57 -08004833 /**
4834 * Determines if the calling application is subject to metered network restrictions while
4835 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004836 *
4837 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4838 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4839 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004840 */
4841 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4842 try {
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004843 return mService.getRestrictBackgroundStatusByCaller();
Felipe Leme30511352016-01-22 09:44:57 -08004844 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004845 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004846 }
4847 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004848
4849 /**
4850 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004851 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4852 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004853 *
4854 * @return Hash of network watchlist config file. Null if config does not exist.
4855 */
Chalard Jean158702d2019-01-07 19:26:34 +09004856 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004857 public byte[] getNetworkWatchlistConfigHash() {
4858 try {
4859 return mService.getNetworkWatchlistConfigHash();
4860 } catch (RemoteException e) {
4861 Log.e(TAG, "Unable to get watchlist config hash");
4862 throw e.rethrowFromSystemServer();
4863 }
4864 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004865
4866 /**
4867 * Returns the {@code uid} of the owner of a network connection.
4868 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004869 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4870 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004871 * @param local The local {@link InetSocketAddress} of a connection.
4872 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004873 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004874 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4875 * android.os.Process#INVALID_UID} if the connection is not found.
4876 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4877 * user.
4878 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004879 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004880 public int getConnectionOwnerUid(
4881 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004882 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4883 try {
4884 return mService.getConnectionOwnerUid(connectionInfo);
4885 } catch (RemoteException e) {
4886 throw e.rethrowFromSystemServer();
4887 }
4888 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004889
4890 private void printStackTrace() {
4891 if (DEBUG) {
4892 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4893 final StringBuffer sb = new StringBuffer();
4894 for (int i = 3; i < callStack.length; i++) {
4895 final String stackTrace = callStack[i].toString();
4896 if (stackTrace == null || stackTrace.contains("android.os")) {
4897 break;
4898 }
4899 sb.append(" [").append(stackTrace).append("]");
4900 }
4901 Log.d(TAG, "StackLog:" + sb.toString());
4902 }
4903 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004904
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004905 /** @hide */
4906 public TestNetworkManager startOrGetTestNetworkManager() {
4907 final IBinder tnBinder;
4908 try {
4909 tnBinder = mService.startOrGetTestNetworkService();
4910 } catch (RemoteException e) {
4911 throw e.rethrowFromSystemServer();
4912 }
4913
4914 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4915 }
4916
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004917 /** @hide */
4918 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4919 return new ConnectivityDiagnosticsManager(mContext, mService);
4920 }
4921
Cody Kestingf53a0752020-04-15 12:33:28 -07004922 /**
4923 * Simulates a Data Stall for the specified Network.
4924 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004925 * <p>This method should only be used for tests.
4926 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004927 * <p>The caller must be the owner of the specified Network.
4928 *
4929 * @param detectionMethod The detection method used to identify the Data Stall.
4930 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4931 * @param network The Network for which a Data Stall is being simluated.
4932 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4933 * @throws SecurityException if the caller is not the owner of the given network.
4934 * @hide
4935 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004936 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004937 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4938 android.Manifest.permission.NETWORK_STACK})
4939 public void simulateDataStall(int detectionMethod, long timestampMillis,
4940 @NonNull Network network, @NonNull PersistableBundle extras) {
4941 try {
4942 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4943 } catch (RemoteException e) {
4944 e.rethrowFromSystemServer();
4945 }
4946 }
James Mattis356a8792020-10-28 21:48:54 -07004947
Daniel Brightf9e945b2020-06-15 16:10:01 -07004948 @NonNull
4949 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4950
4951 /**
4952 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4953 * receive available QoS events related to the {@link Network} and local ip + port
4954 * specified within socketInfo.
4955 * <p/>
4956 * The same {@link QosCallback} must be unregistered before being registered a second time,
4957 * otherwise {@link QosCallbackRegistrationException} is thrown.
4958 * <p/>
4959 * This API does not, in itself, require any permission if called with a network that is not
4960 * restricted. However, the underlying implementation currently only supports the IMS network,
4961 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4962 * useful, because they'd never be called back on networks that they would have access to.
4963 *
4964 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4965 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4966 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4967 * @throws RuntimeException if the app already has too many callbacks registered.
4968 *
4969 * Exceptions after the time of registration is passed through
4970 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4971 *
4972 * @param socketInfo the socket information used to match QoS events
4973 * @param callback receives qos events that satisfy socketInfo
4974 * @param executor The executor on which the callback will be invoked. The provided
4975 * {@link Executor} must run callback sequentially, otherwise the order of
4976 * callbacks cannot be guaranteed.
4977 *
4978 * @hide
4979 */
4980 @SystemApi
4981 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4982 @NonNull final QosCallback callback,
4983 @CallbackExecutor @NonNull final Executor executor) {
4984 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4985 Objects.requireNonNull(callback, "callback must be non-null");
4986 Objects.requireNonNull(executor, "executor must be non-null");
4987
4988 try {
4989 synchronized (mQosCallbackConnections) {
4990 if (getQosCallbackConnection(callback) == null) {
4991 final QosCallbackConnection connection =
4992 new QosCallbackConnection(this, callback, executor);
4993 mQosCallbackConnections.add(connection);
4994 mService.registerQosSocketCallback(socketInfo, connection);
4995 } else {
4996 Log.e(TAG, "registerQosCallback: Callback already registered");
4997 throw new QosCallbackRegistrationException();
4998 }
4999 }
5000 } catch (final RemoteException e) {
5001 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5002
5003 // The same unregister method method is called for consistency even though nothing
5004 // will be sent to the ConnectivityService since the callback was never successfully
5005 // registered.
5006 unregisterQosCallback(callback);
5007 e.rethrowFromSystemServer();
5008 } catch (final ServiceSpecificException e) {
5009 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5010 unregisterQosCallback(callback);
5011 throw convertServiceException(e);
5012 }
5013 }
5014
5015 /**
5016 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5017 * events once unregistered and can be registered a second time.
5018 * <p/>
5019 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5020 *
5021 * @param callback the callback being unregistered
5022 *
5023 * @hide
5024 */
5025 @SystemApi
5026 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5027 Objects.requireNonNull(callback, "The callback must be non-null");
5028 try {
5029 synchronized (mQosCallbackConnections) {
5030 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5031 if (connection != null) {
5032 connection.stopReceivingMessages();
5033 mService.unregisterQosCallback(connection);
5034 mQosCallbackConnections.remove(connection);
5035 } else {
5036 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5037 }
5038 }
5039 } catch (final RemoteException e) {
5040 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5041 e.rethrowFromSystemServer();
5042 }
5043 }
5044
5045 /**
5046 * Gets the connection related to the callback.
5047 *
5048 * @param callback the callback to look up
5049 * @return the related connection
5050 */
5051 @Nullable
5052 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5053 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5054 // Checking by reference here is intentional
5055 if (connection.getCallback() == callback) {
5056 return connection;
5057 }
5058 }
5059 return null;
5060 }
Junyu Laia62493f2021-01-19 11:10:56 +00005061
5062 /**
Roshan Pius951c0032020-12-22 15:10:42 -08005063 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Laia62493f2021-01-19 11:10:56 +00005064 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5065 * be used to request that the system provide a network without causing the network to be
5066 * in the foreground.
5067 *
5068 * <p>This method will attempt to find the best network that matches the passed
5069 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5070 * criteria. The platform will evaluate which network is the best at its own discretion.
5071 * Throughput, latency, cost per byte, policy, user preference and other considerations
5072 * may be factored in the decision of what is considered the best network.
5073 *
5074 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5075 * matching this request, while always attempting to match the request to a better network if
5076 * possible. If a better match is found, the platform will switch this request to the now-best
5077 * network and inform the app of the newly best network by invoking
5078 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5079 * will not try to maintain any other network than the best one currently matching the request:
5080 * a network not matching any network request may be disconnected at any time.
5081 *
5082 * <p>For example, an application could use this method to obtain a connected cellular network
5083 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5084 * radio to consume additional power. Or, an application could inform the system that it wants
5085 * a network supporting sending MMSes and have the system let it know about the currently best
5086 * MMS-supporting network through the provided {@link NetworkCallback}.
5087 *
5088 * <p>The status of the request can be followed by listening to the various callbacks described
5089 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5090 * used to direct traffic to the network (although accessing some networks may be subject to
5091 * holding specific permissions). Callers will learn about the specific characteristics of the
5092 * network through
5093 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5094 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5095 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5096 * matching the request at any given time; therefore when a better network matching the request
5097 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5098 * with the new network after which no further updates are given about the previously-best
5099 * network, unless it becomes the best again at some later time. All callbacks are invoked
5100 * in order on the same thread, which by default is a thread created by the framework running
5101 * in the app.
5102 *
5103 * <p>This{@link NetworkRequest} will live until released via
5104 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5105 * which point the system may let go of the network at any time.
5106 *
5107 * <p>It is presently unsupported to request a network with mutable
5108 * {@link NetworkCapabilities} such as
5109 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5110 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5111 * as these {@code NetworkCapabilities} represent states that a particular
5112 * network may never attain, and whether a network will attain these states
5113 * is unknown prior to bringing up the network so the framework does not
5114 * know how to go about satisfying a request with these capabilities.
5115 *
5116 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5117 * number of outstanding requests to 100 per app (identified by their UID), shared with
5118 * all variants of this method, of {@link #registerNetworkCallback} as well as
5119 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5120 * Requesting a network with this method will count toward this limit. If this limit is
5121 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5122 * make sure to unregister the callbacks with
5123 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5124 *
5125 * @param request {@link NetworkRequest} describing this request.
5126 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5127 * If null, the callback is invoked on the default internal Handler.
5128 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5129 * the callback must not be shared - it uniquely specifies this request.
5130 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5131 * @throws SecurityException if missing the appropriate permissions.
5132 * @throws RuntimeException if the app already has too many callbacks registered.
5133 *
5134 * @hide
5135 */
5136 @SystemApi(client = MODULE_LIBRARIES)
5137 @SuppressLint("ExecutorRegistration")
5138 @RequiresPermission(anyOf = {
5139 android.Manifest.permission.NETWORK_SETTINGS,
5140 android.Manifest.permission.NETWORK_STACK,
5141 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5142 })
5143 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai962bdb82021-03-09 20:49:48 +08005144 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Laia62493f2021-01-19 11:10:56 +00005145 final NetworkCapabilities nc = request.networkCapabilities;
5146 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulai962bdb82021-03-09 20:49:48 +08005147 TYPE_NONE, new CallbackHandler(handler));
Junyu Laia62493f2021-01-19 11:10:56 +00005148 }
James Mattis45d81842021-01-10 14:24:24 -08005149
5150 /**
James Mattis45d81842021-01-10 14:24:24 -08005151 * Used by automotive devices to set the network preferences used to direct traffic at an
5152 * application level as per the given OemNetworkPreferences. An example use-case would be an
5153 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5154 * vehicle via a particular network.
5155 *
5156 * Calling this will overwrite the existing preference.
5157 *
5158 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5159 * @param executor the executor on which listener will be invoked.
5160 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5161 * communicate completion of setOemNetworkPreference(). This will only be
5162 * called once upon successful completion of setOemNetworkPreference().
5163 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5164 * @throws SecurityException if missing the appropriate permissions.
5165 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005166 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005167 */
James Mattisda32cfe2021-01-26 16:23:52 -08005168 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005169 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005170 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005171 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean6010c002021-03-03 16:37:13 +09005172 @Nullable final Runnable listener) {
James Mattis45d81842021-01-10 14:24:24 -08005173 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5174 if (null != listener) {
5175 Objects.requireNonNull(executor, "Executor must be non-null");
5176 }
Chalard Jean6010c002021-03-03 16:37:13 +09005177 final IOnCompleteListener listenerInternal = listener == null ? null :
5178 new IOnCompleteListener.Stub() {
James Mattis45d81842021-01-10 14:24:24 -08005179 @Override
5180 public void onComplete() {
Chalard Jean6010c002021-03-03 16:37:13 +09005181 executor.execute(listener::run);
James Mattis45d81842021-01-10 14:24:24 -08005182 }
5183 };
5184
5185 try {
5186 mService.setOemNetworkPreference(preference, listenerInternal);
5187 } catch (RemoteException e) {
5188 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5189 throw e.rethrowFromSystemServer();
5190 }
5191 }
lucaslin30e70a82021-03-12 00:46:33 +08005192
Chalard Jeanfa45a682021-02-25 17:23:40 +09005193 /**
5194 * Request that a user profile is put by default on a network matching a given preference.
5195 *
5196 * See the documentation for the individual preferences for a description of the supported
5197 * behaviors.
5198 *
5199 * @param profile the profile concerned.
5200 * @param preference the preference for this profile.
5201 * @param executor an executor to execute the listener on. Optional if listener is null.
5202 * @param listener an optional listener to listen for completion of the operation.
5203 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5204 * @throws SecurityException if missing the appropriate permissions.
5205 * @hide
5206 */
Chalard Jean6010c002021-03-03 16:37:13 +09005207 // This function is for establishing per-profile default networking and can only be called by
5208 // the device policy manager, running as the system server. It would make no sense to call it
5209 // on a context for a user because it does not establish a setting on behalf of a user, rather
5210 // it establishes a setting for a user on behalf of the DPM.
5211 @SuppressLint({"UserHandle"})
5212 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09005213 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5214 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5215 @ProfileNetworkPreference final int preference,
5216 @Nullable @CallbackExecutor final Executor executor,
5217 @Nullable final Runnable listener) {
5218 if (null != listener) {
5219 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5220 }
5221 final IOnCompleteListener proxy;
5222 if (null == listener) {
5223 proxy = null;
5224 } else {
5225 proxy = new IOnCompleteListener.Stub() {
5226 @Override
5227 public void onComplete() {
5228 executor.execute(listener::run);
5229 }
5230 };
5231 }
5232 try {
5233 mService.setProfileNetworkPreference(profile, preference, proxy);
5234 } catch (RemoteException e) {
5235 throw e.rethrowFromSystemServer();
5236 }
5237 }
5238
lucaslin30e70a82021-03-12 00:46:33 +08005239 // The first network ID of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005240 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin30e70a82021-03-12 00:46:33 +08005241 // The network ID range of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005242 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin30e70a82021-03-12 00:46:33 +08005243
5244 /**
5245 * Get the network ID range reserved for IPSec tunnel interfaces.
5246 *
5247 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5248 * @hide
5249 */
5250 @SystemApi(client = MODULE_LIBRARIES)
5251 @NonNull
5252 public static Range<Integer> getIpSecNetIdRange() {
5253 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5254 }
lucaslin705c3332021-03-12 17:56:09 +08005255
5256 /**
5257 * Get private DNS mode from settings.
5258 *
lucaslin7abe7e02021-03-17 14:53:35 +08005259 * @param context The Context to query the private DNS mode from settings.
lucaslin705c3332021-03-12 17:56:09 +08005260 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5261 *
5262 * @hide
5263 */
5264 @SystemApi(client = MODULE_LIBRARIES)
5265 @NonNull
5266 @PrivateDnsMode
lucaslin20f04882021-03-16 17:11:14 +08005267 public static String getPrivateDnsMode(@NonNull Context context) {
5268 final ContentResolver cr = context.getContentResolver();
lucaslin705c3332021-03-12 17:56:09 +08005269 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5270 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5271 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5272 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5273 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5274 return mode;
5275 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005276}