blob: 93a84646a7ef2ca3554a12c53d6aa015857b15cf [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;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090041import android.app.admin.DevicePolicyManager;
Artur Satayev9c2add62019-12-10 17:47:52 +000042import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090043import android.content.ComponentName;
lucaslin705c3332021-03-12 17:56:09 +080044import android.content.ContentResolver;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070045import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070046import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080047import android.net.IpSecManager.UdpEncapsulationSocket;
48import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080049import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080050import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080051import android.net.TetheringManager.TetheringRequest;
Roshan Pius951c0032020-12-22 15:10:42 -080052import android.net.wifi.WifiNetworkSuggestion;
Robert Greenwalt2034b912009-08-12 16:08:25 -070053import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000054import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070055import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080056import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070057import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080058import android.os.IBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070059import android.os.Looper;
60import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070061import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080062import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070063import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090064import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080066import android.os.ResultReceiver;
Hugo Benichia590ab82017-05-11 13:16:17 +090067import android.os.ServiceSpecificException;
Chalard Jeanfa45a682021-02-25 17:23:40 +090068import android.os.UserHandle;
Jeff Sharkey971cd162011-08-29 16:02:57 -070069import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080070import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080071import android.telephony.TelephonyManager;
lucaslin705c3332021-03-12 17:56:09 +080072import android.text.TextUtils;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080073import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070074import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090075import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090076import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080077
markchien6ae63e52020-01-21 13:11:06 +080078import com.android.internal.annotations.GuardedBy;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070079
Paul Jensen3e2917c2014-08-27 12:38:45 -040080import libcore.net.event.NetworkEventDispatcher;
81
junyulai7e06ad42019-03-04 22:45:36 +080082import java.io.IOException;
83import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080084import java.lang.annotation.Retention;
85import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090086import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080087import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070088import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080089import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090090import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090091import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080092import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090093import java.util.List;
94import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080095import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080096import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080097import java.util.concurrent.ExecutorService;
98import java.util.concurrent.Executors;
99import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -0800100
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101/**
102 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600103 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800104 * <p>
105 * The primary responsibilities of this class are to:
106 * <ol>
107 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
108 * <li>Send broadcast intents when network connectivity changes</li>
109 * <li>Attempt to "fail over" to another network when connectivity to a network
110 * is lost</li>
111 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
112 * state of the available networks</li>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700113 * <li>Provide an API that allows applications to request and select networks for their data
114 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800115 * </ol>
116 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600117@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700118public class ConnectivityManager {
119 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900120 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700121
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700123 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800124 * been established or lost. The NetworkInfo for the affected network is
125 * sent as an extra; it should be consulted to see what kind of
126 * connectivity event occurred.
127 * <p/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800128 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
129 * broadcast if they declare the broadcast receiver in their manifest. Apps
130 * will still receive broadcasts if they register their
131 * {@link android.content.BroadcastReceiver} with
132 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
133 * and that context is still valid.
134 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135 * If this is a connection that was the result of failing over from a
136 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
137 * set to true.
138 * <p/>
139 * For a loss of connectivity, if the connectivity manager is attempting
140 * to connect (or has already connected) to another network, the
141 * NetworkInfo for the new network is also passed as an extra. This lets
142 * any receivers of the broadcast know that they should not necessarily
143 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800144 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145 * the failover attempt succeeded (and so there is still overall data
146 * connectivity), or that the failover attempt failed, meaning that all
147 * connectivity has been lost.
148 * <p/>
149 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
150 * is set to {@code true} if there are no connected networks at all.
Chalard Jean52e23962018-02-10 05:33:50 +0900151 *
152 * @deprecated apps should use the more versatile {@link #requestNetwork},
153 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
154 * functions instead for faster and more detailed updates about the network
155 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800157 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900158 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700160
The Android Open Source Project28527d22009-03-03 19:31:44 -0800161 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500162 * The device has connected to a network that has presented a captive
163 * portal, which is blocking Internet connectivity. The user was presented
164 * with a notification that network sign in is required,
165 * and the user invoked the notification's action indicating they
Paul Jensen75e0adb2015-05-22 10:50:39 -0400166 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500167 * facilitate signing in to the network. This action includes a
168 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
169 * the network presenting the captive portal; all communication with the
170 * captive portal must be done using this {@code Network} object.
171 * <p/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400172 * This activity includes a {@link CaptivePortal} extra named
173 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
174 * outcomes of the captive portal sign in to the system:
175 * <ul>
176 * <li> When the app handling this action believes the user has signed in to
177 * the network and the captive portal has been dismissed, the app should
178 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
179 * reevaluate the network. If reevaluation finds the network no longer
180 * subject to a captive portal, the network may become the default active
Chalard Jean9dd11612018-06-04 16:52:49 +0900181 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400182 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500183 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400184 * {@link CaptivePortal#ignoreNetwork}. </li>
185 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500186 */
187 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
188 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
189
190 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800191 * The lookup key for a {@link NetworkInfo} object. Retrieve with
192 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700193 *
Chalard Jean97021a12019-01-11 16:47:53 +0900194 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
195 * can't accurately represent modern network characteristics.
196 * Please obtain information about networks from the {@link NetworkCapabilities}
197 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700199 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800200 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700201
The Android Open Source Project28527d22009-03-03 19:31:44 -0800202 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700203 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700204 *
205 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900206 * @deprecated The network type is not rich enough to represent the characteristics
207 * of modern networks. Please use {@link NetworkCapabilities} instead,
208 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700209 */
Chalard Jean97021a12019-01-11 16:47:53 +0900210 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700211 public static final String EXTRA_NETWORK_TYPE = "networkType";
212
213 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214 * The lookup key for a boolean that indicates whether a connect event
215 * is for a network to which the connectivity manager was failing over
216 * following a disconnect on another network.
217 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai9826e7f2018-12-13 12:47:51 +0800218 *
219 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220 */
junyulai9826e7f2018-12-13 12:47:51 +0800221 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222 public static final String EXTRA_IS_FAILOVER = "isFailover";
223 /**
224 * The lookup key for a {@link NetworkInfo} object. This is supplied when
225 * there is another network that it may be possible to connect to. Retrieve with
226 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800227 *
228 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229 */
junyulai9826e7f2018-12-13 12:47:51 +0800230 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
232 /**
233 * The lookup key for a boolean that indicates whether there is a
234 * complete lack of connectivity, i.e., no network is available.
235 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
236 */
237 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
238 /**
239 * The lookup key for a string that indicates why an attempt to connect
240 * to a network failed. The string has no particular structure. It is
241 * intended to be used in notifications presented to users. Retrieve
242 * it with {@link android.content.Intent#getStringExtra(String)}.
243 */
244 public static final String EXTRA_REASON = "reason";
245 /**
246 * The lookup key for a string that provides optionally supplied
247 * extra information about the network state. The information
248 * may be passed up from the lower networking layers, and its
249 * meaning may be specific to a particular network type. Retrieve
250 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800251 *
252 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800253 */
junyulai9826e7f2018-12-13 12:47:51 +0800254 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800255 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700256 /**
257 * The lookup key for an int that provides information about
258 * our connection to the internet at large. 0 indicates no connection,
259 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700260 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700261 * {@hide}
262 */
263 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800264 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400265 * The lookup key for a {@link CaptivePortal} object included with the
266 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
267 * object can be used to either indicate to the system that the captive
268 * portal has been dismissed or that the user does not want to pursue
269 * signing in to captive portal. Retrieve it with
270 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500271 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400272 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700273
274 /**
275 * Key for passing a URL to the captive portal login activity.
276 */
277 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
278
Paul Jensen60df4aa2015-02-27 22:55:47 -0500279 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900280 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
281 * portal login activity.
282 * {@hide}
283 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900284 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900285 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
286 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
287
288 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900289 * Key for passing a user agent string to the captive portal login activity.
290 * {@hide}
291 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900292 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900293 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
294 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
295
296 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700297 * Broadcast action to indicate the change of data activity status
298 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800299 * The network becomes active when data transmission is started, or
300 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700301 * {@hide}
302 */
303 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900304 public static final String ACTION_DATA_ACTIVITY_CHANGE =
305 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700306 /**
307 * The lookup key for an enum that indicates the network device type on which this data activity
308 * change happens.
309 * {@hide}
310 */
311 public static final String EXTRA_DEVICE_TYPE = "deviceType";
312 /**
313 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
314 * it is actively sending or receiving data and {@code false} means it is idle.
315 * {@hide}
316 */
317 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700318 /**
319 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
320 * {@hide}
321 */
322 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700323
324 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800325 * Broadcast Action: The setting for background data usage has changed
326 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
327 * <p>
328 * If an application uses the network in the background, it should listen
329 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700330 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800331 * <p>
332 *
333 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
334 * of background data depends on several combined factors, and
335 * this broadcast is no longer sent. Instead, when background
336 * data is unavailable, {@link #getActiveNetworkInfo()} will now
337 * appear disconnected. During first boot after a platform
338 * upgrade, this broadcast will be sent once if
339 * {@link #getBackgroundDataSetting()} was {@code false} before
340 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800341 */
342 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800343 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800344 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
345 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
346
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700347 /**
348 * Broadcast Action: The network connection may not be good
349 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
350 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
351 * the network and it's condition.
352 * @hide
353 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800354 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100355 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700356 public static final String INET_CONDITION_ACTION =
357 "android.net.conn.INET_CONDITION_ACTION";
358
Robert Greenwalt2034b912009-08-12 16:08:25 -0700359 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800360 * Broadcast Action: A tetherable connection has come or gone.
361 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900362 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
363 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800364 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
365 * the current state of tethering. Each include a list of
366 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800367 * @hide
368 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800369 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000370 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800371 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800372 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800373
374 /**
375 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800376 * gives a String[] listing all the interfaces configured for
377 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800378 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000379 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800380 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800381
382 /**
383 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900384 * gives a String[] listing all the interfaces currently in local-only
385 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800386 */
markchiena0f8fd92019-12-25 19:40:32 +0800387 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900388
389 /**
390 * @hide
391 * gives a String[] listing all the interfaces currently tethered
392 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
393 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000394 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800395 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800396
397 /**
398 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800399 * gives a String[] listing all the interfaces we tried to tether and
400 * failed. Use {@link #getLastTetherError} to find the error code
401 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800402 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000403 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800404 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800405
406 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800407 * Broadcast Action: The captive portal tracker has finished its test.
408 * Sent only while running Setup Wizard, in lieu of showing a user
409 * notification.
410 * @hide
411 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800412 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800413 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
414 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
415 /**
416 * The lookup key for a boolean that indicates whether a captive portal was detected.
417 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
418 * @hide
419 */
420 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
421
422 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900423 * Action used to display a dialog that asks the user whether to connect to a network that is
424 * not validated. This intent is used to start the dialog in settings via startActivity.
425 *
426 * @hide
427 */
428 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
429
430 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900431 * Action used to display a dialog that asks the user whether to avoid a network that is no
432 * longer validated. This intent is used to start the dialog in settings via startActivity.
433 *
434 * @hide
435 */
436 public static final String ACTION_PROMPT_LOST_VALIDATION =
437 "android.net.conn.PROMPT_LOST_VALIDATION";
438
439 /**
lucaslin2240ef62019-03-12 13:08:03 +0800440 * Action used to display a dialog that asks the user whether to stay connected to a network
441 * that has not validated. This intent is used to start the dialog in settings via
442 * startActivity.
443 *
444 * @hide
445 */
446 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
447 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
448
449 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800450 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900451 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800452 * @hide
453 */
markchiena0f8fd92019-12-25 19:40:32 +0800454 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800455
456 /**
457 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900458 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800459 * @hide
460 */
461 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900462 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800463
464 /**
465 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900466 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800467 * @hide
468 */
469 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900470 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800471
472 /**
473 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900474 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800475 * @hide
476 */
477 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900478 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800479
480 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800481 * Wifi P2p tethering type.
482 * Wifi P2p tethering is set through events automatically, and don't
483 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
484 * @hide
485 */
markchiena0f8fd92019-12-25 19:40:32 +0800486 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800487
488 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800489 * Extra used for communicating with the TetherService. Includes the type of tethering to
490 * enable if any.
491 * @hide
492 */
markchien6ae63e52020-01-21 13:11:06 +0800493 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800494
495 /**
496 * Extra used for communicating with the TetherService. Includes the type of tethering for
497 * which to cancel provisioning.
498 * @hide
499 */
markchien6ae63e52020-01-21 13:11:06 +0800500 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800501
502 /**
503 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
504 * provisioning.
505 * @hide
506 */
markchien6ae63e52020-01-21 13:11:06 +0800507 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800508
509 /**
510 * Tells the TetherService to run a provision check now.
511 * @hide
512 */
markchien6ae63e52020-01-21 13:11:06 +0800513 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800514
515 /**
516 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
517 * which will receive provisioning results. Can be left empty.
518 * @hide
519 */
markchien6ae63e52020-01-21 13:11:06 +0800520 public static final String EXTRA_PROVISION_CALLBACK =
521 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800522
523 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800524 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700525 * @hide
526 */
paulhu74357e72020-01-13 16:46:45 +0800527 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700528 public static final int TYPE_NONE = -1;
529
530 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900531 * A Mobile data connection. Devices may support more than one.
532 *
533 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
534 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
535 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700536 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900537 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700538 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900539
Robert Greenwalt2034b912009-08-12 16:08:25 -0700540 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900541 * A WIFI data connection. Devices may support more than one.
542 *
543 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
544 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
545 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700546 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900547 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700548 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900549
Robert Greenwalt2034b912009-08-12 16:08:25 -0700550 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800551 * An MMS-specific Mobile data connection. This network type may use the
552 * same network interface as {@link #TYPE_MOBILE} or it may use a different
553 * one. This is used by applications needing to talk to the carrier's
554 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900555 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900556 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900557 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900558 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700559 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700560 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700561 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900562
Robert Greenwalt2034b912009-08-12 16:08:25 -0700563 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800564 * A SUPL-specific Mobile data connection. This network type may use the
565 * same network interface as {@link #TYPE_MOBILE} or it may use a different
566 * one. This is used by applications needing to talk to the carrier's
567 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900568 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900569 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900570 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900571 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700572 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700573 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700574 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900575
Robert Greenwalt2034b912009-08-12 16:08:25 -0700576 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800577 * A DUN-specific Mobile data connection. This network type may use the
578 * same network interface as {@link #TYPE_MOBILE} or it may use a different
579 * one. This is sometimes by the system when setting up an upstream connection
580 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900581 *
582 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
583 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
584 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700585 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900586 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700587 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900588
Robert Greenwalt2034b912009-08-12 16:08:25 -0700589 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800590 * A High Priority Mobile data connection. This network type uses the
591 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900592 * is different.
593 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900594 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
595 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
596 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700597 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700598 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700599 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900600
jshbfa81722010-03-11 15:04:43 -0800601 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900602 * A WiMAX data connection.
603 *
604 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
605 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
606 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800607 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900608 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800609 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800610
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800611 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900612 * A Bluetooth data connection.
613 *
614 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
615 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
616 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800617 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900618 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800619 public static final int TYPE_BLUETOOTH = 7;
620
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700621 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800622 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900623 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700624 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900625 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800626 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800627
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700628 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900629 * An Ethernet data connection.
630 *
631 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
632 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
633 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700634 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900635 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800636 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700637
Wink Savilleb7c92c72011-03-12 14:52:01 -0800638 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800639 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900640 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800641 * {@hide}
642 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900643 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900644 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800645 public static final int TYPE_MOBILE_FOTA = 10;
646
647 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800648 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900649 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800650 * {@hide}
651 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900652 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100653 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800654 public static final int TYPE_MOBILE_IMS = 11;
655
656 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800657 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900658 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800659 * {@hide}
660 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900661 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900662 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800663 public static final int TYPE_MOBILE_CBS = 12;
664
repo syncf5de5572011-07-29 23:55:49 -0700665 /**
666 * A Wi-Fi p2p connection. Only requesting processes will have access to
667 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900668 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700669 * {@hide}
670 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900671 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800672 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700673 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800674
Wink Saville512c2202013-07-29 15:00:57 -0700675 /**
676 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900677 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700678 * {@hide}
679 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900680 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100681 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700682 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700683
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900684 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700685 * Emergency PDN connection for emergency services. This
686 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900687 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700688 * {@hide}
689 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900690 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900691 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700692 public static final int TYPE_MOBILE_EMERGENCY = 15;
693
Hui Lu865b70d2014-01-15 11:05:36 -0500694 /**
695 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900696 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500697 * {@hide}
698 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900699 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900700 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500701 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700702
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700703 /**
704 * A virtual network using one or more native bearers.
705 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900706 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700707 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900708 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700709 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500710
Benedict Wongbdfaa482018-11-14 17:40:55 -0800711 /**
712 * A network that is exclusively meant to be used for testing
713 *
714 * @deprecated Use {@link NetworkCapabilities} instead.
715 * @hide
716 */
717 @Deprecated
718 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700719
Chalard Jeanaea539a2020-03-25 01:24:04 +0900720 /**
721 * @deprecated Use {@link NetworkCapabilities} instead.
722 * @hide
723 */
724 @Deprecated
725 @Retention(RetentionPolicy.SOURCE)
726 @IntDef(prefix = { "TYPE_" }, value = {
727 TYPE_NONE,
728 TYPE_MOBILE,
729 TYPE_WIFI,
730 TYPE_MOBILE_MMS,
731 TYPE_MOBILE_SUPL,
732 TYPE_MOBILE_DUN,
733 TYPE_MOBILE_HIPRI,
734 TYPE_WIMAX,
735 TYPE_BLUETOOTH,
736 TYPE_DUMMY,
737 TYPE_ETHERNET,
738 TYPE_MOBILE_FOTA,
739 TYPE_MOBILE_IMS,
740 TYPE_MOBILE_CBS,
741 TYPE_WIFI_P2P,
742 TYPE_MOBILE_IA,
743 TYPE_MOBILE_EMERGENCY,
744 TYPE_PROXY,
745 TYPE_VPN,
746 TYPE_TEST
747 })
748 public @interface LegacyNetworkType {}
749
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900750 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
751 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
752 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
753 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
754 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
755
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700756 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800757 public static final int MAX_RADIO_TYPE = TYPE_TEST;
758
759 /** {@hide} */
760 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800761
Hugo Benichiad353f42017-06-20 14:07:59 +0900762 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
763
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800764 /**
765 * If you want to set the default network preference,you can directly
766 * change the networkAttributes array in framework's config.xml.
767 *
768 * @deprecated Since we support so many more networks now, the single
769 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800770 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800771 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800772 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800773 * from an App.
774 */
775 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800776 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
777
Jeff Sharkey8c870452012-09-26 22:03:49 -0700778 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700779 * @hide
780 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900781 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700782
Paul Jensen5dea4352014-07-11 12:28:19 -0400783 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900784 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
785 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900786 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900787 * @hide
788 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900789 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900790 new NetworkRequest.Builder().clearCapabilities().build();
791
792 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400793 * A NetID indicating no Network is selected.
794 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
795 * @hide
796 */
797 public static final int NETID_UNSET = 0;
798
Erik Klineb0be3e62017-10-30 15:29:44 +0900799 /**
800 * Private DNS Mode values.
801 *
802 * The "private_dns_mode" global setting stores a String value which is
803 * expected to be one of the following.
804 */
805
806 /**
807 * @hide
808 */
lucaslin705c3332021-03-12 17:56:09 +0800809 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900810 public static final String PRIVATE_DNS_MODE_OFF = "off";
811 /**
812 * @hide
813 */
lucaslin705c3332021-03-12 17:56:09 +0800814 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900815 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
816 /**
817 * @hide
818 */
lucaslin705c3332021-03-12 17:56:09 +0800819 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900820 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin705c3332021-03-12 17:56:09 +0800821
822 /** @hide */
823 @Retention(RetentionPolicy.SOURCE)
824 @StringDef(value = {
825 PRIVATE_DNS_MODE_OFF,
826 PRIVATE_DNS_MODE_OPPORTUNISTIC,
827 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
828 })
829 public @interface PrivateDnsMode {}
Erik Klineb0be3e62017-10-30 15:29:44 +0900830
Sudheer Shanka98215562021-03-23 08:12:28 +0000831 /**
832 * Flag to indicate that an app is not subject to any restrictions that could result in its
833 * network access blocked.
834 *
835 * @hide
836 */
837 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
838 public static final int BLOCKED_REASON_NONE = 0;
839
840 /**
841 * Flag to indicate that an app is subject to Battery saver restrictions that would
842 * result in its network access being blocked.
843 *
844 * @hide
845 */
846 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
847 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
848
849 /**
850 * Flag to indicate that an app is subject to Doze restrictions that would
851 * result in its network access being blocked.
852 *
853 * @hide
854 */
855 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
856 public static final int BLOCKED_REASON_DOZE = 1 << 1;
857
858 /**
859 * Flag to indicate that an app is subject to App Standby restrictions that would
860 * result in its network access being blocked.
861 *
862 * @hide
863 */
864 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
865 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
866
867 /**
868 * Flag to indicate that an app is subject to Restricted mode restrictions that would
869 * result in its network access being blocked.
870 *
871 * @hide
872 */
873 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
874 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
875
876 /**
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900877 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
878 * is not currently connected.
879 *
880 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
881 *
882 * @hide
883 */
884 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
885 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
886
887 /**
Sudheer Shanka98215562021-03-23 08:12:28 +0000888 * Flag to indicate that an app is subject to Data saver restrictions that would
889 * result in its metered network access being blocked.
890 *
891 * @hide
892 */
893 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
894 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
895
896 /**
897 * Flag to indicate that an app is subject to user restrictions that would
898 * result in its metered network access being blocked.
899 *
900 * @hide
901 */
902 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
903 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
904
905 /**
906 * Flag to indicate that an app is subject to Device admin restrictions that would
907 * result in its metered network access being blocked.
908 *
909 * @hide
910 */
911 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
912 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
913
914 /**
915 * @hide
916 */
917 @Retention(RetentionPolicy.SOURCE)
918 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
919 BLOCKED_REASON_NONE,
920 BLOCKED_REASON_BATTERY_SAVER,
921 BLOCKED_REASON_DOZE,
922 BLOCKED_REASON_APP_STANDBY,
923 BLOCKED_REASON_RESTRICTED_MODE,
924 BLOCKED_METERED_REASON_DATA_SAVER,
925 BLOCKED_METERED_REASON_USER_RESTRICTED,
926 BLOCKED_METERED_REASON_ADMIN_DISABLED,
927 })
928 public @interface BlockedReason {}
929
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900930 /**
931 * Set of blocked reasons that are only applicable on metered networks.
932 *
933 * @hide
934 */
935 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
936 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
937
Chalard Jeana3b77512019-04-09 15:46:21 +0900938 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700939 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900940
Paul Jensenc0618a62014-12-10 15:12:18 -0500941 /**
942 * A kludge to facilitate static access where a Context pointer isn't available, like in the
943 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
944 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
945 * methods that take a Context argument.
946 */
947 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800948
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900949 private final Context mContext;
950
Amos Bianchia9b415a2020-03-04 11:07:38 -0800951 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800952
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800953 /**
954 * Tests if a given integer represents a valid network type.
955 * @param networkType the type to be tested
956 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400957 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
958 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800959 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700960 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700961 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900962 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800963 }
964
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800965 /**
966 * Returns a non-localized string representing a given network type.
967 * ONLY used for debugging output.
968 * @param type the type needing naming
969 * @return a String for the given type, or a string version of the type ("87")
970 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900971 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800972 * {@hide}
973 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900974 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000975 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700976 public static String getNetworkTypeName(int type) {
977 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900978 case TYPE_NONE:
979 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700980 case TYPE_MOBILE:
981 return "MOBILE";
982 case TYPE_WIFI:
983 return "WIFI";
984 case TYPE_MOBILE_MMS:
985 return "MOBILE_MMS";
986 case TYPE_MOBILE_SUPL:
987 return "MOBILE_SUPL";
988 case TYPE_MOBILE_DUN:
989 return "MOBILE_DUN";
990 case TYPE_MOBILE_HIPRI:
991 return "MOBILE_HIPRI";
992 case TYPE_WIMAX:
993 return "WIMAX";
994 case TYPE_BLUETOOTH:
995 return "BLUETOOTH";
996 case TYPE_DUMMY:
997 return "DUMMY";
998 case TYPE_ETHERNET:
999 return "ETHERNET";
1000 case TYPE_MOBILE_FOTA:
1001 return "MOBILE_FOTA";
1002 case TYPE_MOBILE_IMS:
1003 return "MOBILE_IMS";
1004 case TYPE_MOBILE_CBS:
1005 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -07001006 case TYPE_WIFI_P2P:
1007 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -07001008 case TYPE_MOBILE_IA:
1009 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -07001010 case TYPE_MOBILE_EMERGENCY:
1011 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -05001012 case TYPE_PROXY:
1013 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +09001014 case TYPE_VPN:
1015 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -07001016 default:
1017 return Integer.toString(type);
1018 }
1019 }
1020
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001021 /**
Aaron Huang96011892020-06-27 07:18:23 +08001022 * @hide
Aaron Huang96011892020-06-27 07:18:23 +08001023 */
lucaslin7fc930b2021-03-17 14:16:01 +08001024 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huang96011892020-06-27 07:18:23 +08001025 public void systemReady() {
1026 try {
1027 mService.systemReady();
1028 } catch (RemoteException e) {
1029 throw e.rethrowFromSystemServer();
1030 }
1031 }
1032
1033 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001034 * Checks if a given type uses the cellular data connection.
1035 * This should be replaced in the future by a network property.
1036 * @param networkType the type to check
1037 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001038 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001039 * {@hide}
1040 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001041 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +09001042 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001043 public static boolean isNetworkTypeMobile(int networkType) {
1044 switch (networkType) {
1045 case TYPE_MOBILE:
1046 case TYPE_MOBILE_MMS:
1047 case TYPE_MOBILE_SUPL:
1048 case TYPE_MOBILE_DUN:
1049 case TYPE_MOBILE_HIPRI:
1050 case TYPE_MOBILE_FOTA:
1051 case TYPE_MOBILE_IMS:
1052 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -07001053 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -07001054 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -07001055 return true;
1056 default:
1057 return false;
1058 }
1059 }
1060
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001061 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001062 * Checks if the given network type is backed by a Wi-Fi radio.
1063 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001064 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001065 * @hide
1066 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001067 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001068 public static boolean isNetworkTypeWifi(int networkType) {
1069 switch (networkType) {
1070 case TYPE_WIFI:
1071 case TYPE_WIFI_P2P:
1072 return true;
1073 default:
1074 return false;
1075 }
1076 }
1077
1078 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +09001079 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1080 * Specify that the traffic for this user should by follow the default rules.
1081 * @hide
1082 */
Chalard Jeanb43f3962021-03-17 14:33:24 +09001083 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09001084 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1085
1086 /**
1087 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1088 * Specify that the traffic for this user should by default go on a network with
1089 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1090 * if no such network is available.
1091 * @hide
1092 */
Chalard Jeanb43f3962021-03-17 14:33:24 +09001093 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09001094 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1095
1096 /** @hide */
1097 @Retention(RetentionPolicy.SOURCE)
1098 @IntDef(value = {
1099 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1100 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1101 })
1102 public @interface ProfileNetworkPreference {
1103 }
1104
1105 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001106 * Specifies the preferred network type. When the device has more
1107 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001108 *
1109 * @param preference the network type to prefer over all others. It is
1110 * unspecified what happens to the old preferred network in the
1111 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001112 * @deprecated Functionality has been removed as it no longer makes sense,
1113 * with many more than two networks - we'd need an array to express
1114 * preference. Instead we use dynamic network properties of
1115 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001116 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001117 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001118 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001119 }
1120
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001121 /**
1122 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001123 *
1124 * @return an integer representing the preferred network type
1125 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001126 * @deprecated Functionality has been removed as it no longer makes sense,
1127 * with many more than two networks - we'd need an array to express
1128 * preference. Instead we use dynamic network properties of
1129 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001130 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001131 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001132 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001133 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001134 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001135 }
1136
Scott Mainf58b7d82011-10-06 19:02:28 -07001137 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001138 * Returns details about the currently active default data network. When
1139 * connected, this network is the default route for outgoing connections.
1140 * You should always check {@link NetworkInfo#isConnected()} before initiating
1141 * network traffic. This may return {@code null} when there is no default
1142 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001143 * Note that if the default network is a VPN, this method will return the
1144 * NetworkInfo for one of its underlying networks instead, or null if the
1145 * VPN agent did not specify any. Apps interested in learning about VPNs
1146 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001147 *
1148 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001149 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001150 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001151 */
junyulai9826e7f2018-12-13 12:47:51 +08001152 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001153 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001154 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001155 public NetworkInfo getActiveNetworkInfo() {
1156 try {
1157 return mService.getActiveNetworkInfo();
1158 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001159 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001160 }
1161 }
1162
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001163 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001164 * Returns a {@link Network} object corresponding to the currently active
1165 * default data network. In the event that the current active default data
1166 * network disconnects, the returned {@code Network} object will no longer
1167 * be usable. This will return {@code null} when there is no default
1168 * network.
1169 *
1170 * @return a {@link Network} object for the current default network or
1171 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001172 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001173 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001174 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001175 public Network getActiveNetwork() {
1176 try {
1177 return mService.getActiveNetwork();
1178 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001179 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001180 }
1181 }
1182
1183 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001184 * Returns a {@link Network} object corresponding to the currently active
1185 * default data network for a specific UID. In the event that the default data
1186 * network disconnects, the returned {@code Network} object will no longer
1187 * be usable. This will return {@code null} when there is no default
1188 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001189 *
1190 * @return a {@link Network} object for the current default network for the
1191 * given UID or {@code null} if no default network is currently active
lifr42a60c22021-03-11 20:11:09 +08001192 * TODO: b/183465229 Cleanup getActiveNetworkForUid once b/165835257 is fixed
Robin Lee5b52bef2016-03-24 12:07:00 +00001193 */
paulhu8e96a752019-08-12 16:25:11 +08001194 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001195 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001196 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001197 return getActiveNetworkForUid(uid, false);
1198 }
1199
1200 /** {@hide} */
1201 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001202 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001203 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001204 } catch (RemoteException e) {
1205 throw e.rethrowFromSystemServer();
1206 }
1207 }
1208
1209 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001210 * Adds or removes a requirement for given UID ranges to use the VPN.
1211 *
1212 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1213 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1214 * otherwise have permission to bypass the VPN (e.g., because they have the
1215 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1216 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1217 * set to {@code false}, a previously-added restriction is removed.
1218 * <p>
1219 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1220 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1221 * remove a previously-added range, the exact range must be removed as is.
1222 * <p>
1223 * The changes are applied asynchronously and may not have been applied by the time the method
1224 * returns. Apps will be notified about any changes that apply to them via
1225 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1226 * effect.
1227 * <p>
1228 * This method should be called only by the VPN code.
1229 *
1230 * @param ranges the UID ranges to restrict
1231 * @param requireVpn whether the specified UID ranges must use a VPN
1232 *
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001233 * @hide
1234 */
1235 @RequiresPermission(anyOf = {
1236 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucasline257bce2021-03-22 11:51:27 +08001237 android.Manifest.permission.NETWORK_STACK,
1238 android.Manifest.permission.NETWORK_SETTINGS})
1239 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001240 public void setRequireVpnForUids(boolean requireVpn,
1241 @NonNull Collection<Range<Integer>> ranges) {
1242 Objects.requireNonNull(ranges);
1243 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1244 // This method is not necessarily expected to be used outside the system server, so
1245 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1246 // stack process, or by tests.
1247 UidRange[] rangesArray = new UidRange[ranges.size()];
1248 int index = 0;
1249 for (Range<Integer> range : ranges) {
1250 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1251 }
1252 try {
1253 mService.setRequireVpnForUids(requireVpn, rangesArray);
1254 } catch (RemoteException e) {
1255 throw e.rethrowFromSystemServer();
1256 }
1257 }
1258
1259 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001260 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1261 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1262 * but is still supported for backwards compatibility.
1263 * <p>
1264 * This type of VPN is assumed always to use the system default network, and must always declare
1265 * exactly one underlying network, which is the network that was the default when the VPN
1266 * connected.
1267 * <p>
1268 * Calling this method with {@code true} enables legacy behaviour, specifically:
1269 * <ul>
1270 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1271 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1272 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1273 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1274 * underlying the VPN.</li>
1275 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1276 * similarly replaced by the VPN network state.</li>
1277 * <li>Information on current network interfaces passed to NetworkStatsService will not
1278 * include any VPN interfaces.</li>
1279 * </ul>
1280 *
1281 * @param enabled whether legacy lockdown VPN is enabled or disabled
1282 *
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001283 * @hide
1284 */
1285 @RequiresPermission(anyOf = {
1286 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucasline257bce2021-03-22 11:51:27 +08001287 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001288 android.Manifest.permission.NETWORK_SETTINGS})
lucasline257bce2021-03-22 11:51:27 +08001289 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001290 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1291 try {
1292 mService.setLegacyLockdownVpnEnabled(enabled);
1293 } catch (RemoteException e) {
1294 throw e.rethrowFromSystemServer();
1295 }
1296 }
1297
1298 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001299 * Returns details about the currently active default data network
1300 * for a given uid. This is for internal use only to avoid spying
1301 * other apps.
1302 *
1303 * @return a {@link NetworkInfo} object for the current default network
1304 * for the given uid or {@code null} if no default network is
1305 * available for the specified uid.
1306 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001307 * {@hide}
1308 */
paulhu8e96a752019-08-12 16:25:11 +08001309 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001310 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001311 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001312 return getActiveNetworkInfoForUid(uid, false);
1313 }
1314
1315 /** {@hide} */
1316 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001317 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001318 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001319 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001320 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001321 }
1322 }
1323
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001324 /**
1325 * Returns connection status information about a particular
1326 * network type.
1327 *
1328 * @param networkType integer specifying which networkType in
1329 * which you're interested.
1330 * @return a {@link NetworkInfo} object for the requested
1331 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001332 * supported by the device. If {@code networkType} is
1333 * TYPE_VPN and a VPN is active for the calling app,
1334 * then this method will try to return one of the
1335 * underlying networks for the VPN or null if the
1336 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001337 *
Paul Jensendda8e592015-03-18 12:23:02 -04001338 * @deprecated This method does not support multiple connected networks
1339 * of the same type. Use {@link #getAllNetworks} and
1340 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001341 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001342 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001343 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001344 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001345 public NetworkInfo getNetworkInfo(int networkType) {
1346 try {
1347 return mService.getNetworkInfo(networkType);
1348 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001349 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001350 }
1351 }
1352
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001353 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001354 * Returns connection status information about a particular
1355 * Network.
1356 *
1357 * @param network {@link Network} specifying which network
1358 * in which you're interested.
1359 * @return a {@link NetworkInfo} object for the requested
1360 * network or {@code null} if the {@code Network}
1361 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001362 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001363 */
junyulai9826e7f2018-12-13 12:47:51 +08001364 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001365 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001366 @Nullable
1367 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001368 return getNetworkInfoForUid(network, Process.myUid(), false);
1369 }
1370
1371 /** {@hide} */
1372 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001373 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001374 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001375 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001376 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001377 }
1378 }
1379
1380 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001381 * Returns connection status information about all network
1382 * types supported by the device.
1383 *
1384 * @return an array of {@link NetworkInfo} objects. Check each
1385 * {@link NetworkInfo#getType} for which type each applies.
1386 *
Paul Jensendda8e592015-03-18 12:23:02 -04001387 * @deprecated This method does not support multiple connected networks
1388 * of the same type. Use {@link #getAllNetworks} and
1389 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001390 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001391 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001392 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001393 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001394 public NetworkInfo[] getAllNetworkInfo() {
1395 try {
1396 return mService.getAllNetworkInfo();
1397 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001398 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001399 }
1400 }
1401
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001402 /**
junyulaiebd15162021-03-03 12:09:05 +08001403 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1404 * connected.
1405 * @hide
1406 */
1407 @SystemApi(client = MODULE_LIBRARIES)
1408 @RequiresPermission(anyOf = {
1409 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1410 android.Manifest.permission.NETWORK_STACK,
1411 android.Manifest.permission.NETWORK_SETTINGS})
1412 @NonNull
1413 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1414 try {
1415 return mService.getAllNetworkStateSnapshot();
1416 } catch (RemoteException e) {
1417 throw e.rethrowFromSystemServer();
1418 }
1419 }
1420
1421 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001422 * Returns the {@link Network} object currently serving a given type, or
1423 * null if the given type is not connected.
1424 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001425 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001426 * @deprecated This method does not support multiple connected networks
1427 * of the same type. Use {@link #getAllNetworks} and
1428 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001429 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001430 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001431 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001432 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001433 public Network getNetworkForType(int networkType) {
1434 try {
1435 return mService.getNetworkForType(networkType);
1436 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001437 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001438 }
1439 }
1440
1441 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001442 * Returns an array of all {@link Network} currently tracked by the
1443 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001444 *
1445 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001446 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001447 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001448 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001449 public Network[] getAllNetworks() {
1450 try {
1451 return mService.getAllNetworks();
1452 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001453 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001454 }
1455 }
1456
1457 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001458 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001459 * the Networks that applications run by the given user will use by default.
1460 * @hide
1461 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001462 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001463 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1464 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001465 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001466 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001467 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001468 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001469 }
1470 }
1471
1472 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001473 * Returns the IP information for the current default network.
1474 *
1475 * @return a {@link LinkProperties} object describing the IP info
1476 * for the current default network, or {@code null} if there
1477 * is no current default network.
1478 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001479 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001480 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1481 * value of {@link #getActiveNetwork()} instead. In particular,
1482 * this method will return non-null LinkProperties even if the
1483 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001484 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001485 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001486 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001487 public LinkProperties getActiveLinkProperties() {
1488 try {
1489 return mService.getActiveLinkProperties();
1490 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001491 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001492 }
1493 }
1494
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001495 /**
1496 * Returns the IP information for a given network type.
1497 *
1498 * @param networkType the network type of interest.
1499 * @return a {@link LinkProperties} object describing the IP info
1500 * for the given networkType, or {@code null} if there is
1501 * no current default network.
1502 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001503 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001504 * @deprecated This method does not support multiple connected networks
1505 * of the same type. Use {@link #getAllNetworks},
1506 * {@link #getNetworkInfo(android.net.Network)}, and
1507 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001508 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001509 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001510 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001511 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001512 public LinkProperties getLinkProperties(int networkType) {
1513 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001514 return mService.getLinkPropertiesForType(networkType);
1515 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001516 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001517 }
1518 }
1519
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001520 /**
1521 * Get the {@link LinkProperties} for the given {@link Network}. This
1522 * will return {@code null} if the network is unknown.
1523 *
1524 * @param network The {@link Network} object identifying the network in question.
1525 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001526 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001527 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001528 @Nullable
1529 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001530 try {
1531 return mService.getLinkProperties(network);
1532 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001533 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001534 }
1535 }
1536
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001537 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001538 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001539 * will return {@code null} if the network is unknown.
1540 *
Roshan Pius951c0032020-12-22 15:10:42 -08001541 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1542 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1543 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1544 * this location sensitive information (subject to app's location permissions) will be
1545 * noted by system. To include any location sensitive data in {@link TransportInfo},
1546 * use a {@link NetworkCallback} with
1547 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1548 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001549 * @param network The {@link Network} object identifying the network in question.
Roshan Pius951c0032020-12-22 15:10:42 -08001550 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001551 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001552 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001553 @Nullable
1554 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001555 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001556 return mService.getNetworkCapabilities(
1557 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001558 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001559 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001560 }
1561 }
1562
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001563 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001564 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001565 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1566 * portal is present.
1567 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1568 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1569 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001570 * The system network validation may be using different strategies to detect captive portals,
1571 * so this method does not necessarily return a URL used by the system. It only returns a URL
1572 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001573 *
Udam Sainicd645462016-01-04 12:16:14 -08001574 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001575 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1576 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001577 */
paulhu8e96a752019-08-12 16:25:11 +08001578 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001579 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001580 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001581 public String getCaptivePortalServerUrl() {
1582 try {
1583 return mService.getCaptivePortalServerUrl();
1584 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001585 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001586 }
1587 }
1588
1589 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001590 * Tells the underlying networking system that the caller wants to
1591 * begin using the named feature. The interpretation of {@code feature}
1592 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001593 *
1594 * <p>This method requires the caller to hold either the
1595 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1596 * or the ability to modify system settings as determined by
1597 * {@link android.provider.Settings.System#canWrite}.</p>
1598 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001599 * @param networkType specifies which network the request pertains to
1600 * @param feature the name of the feature to be used
1601 * @return an integer value representing the outcome of the request.
1602 * The interpretation of this value is specific to each networking
1603 * implementation+feature combination, except that the value {@code -1}
1604 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001605 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001606 * @deprecated Deprecated in favor of the cleaner
1607 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001608 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001609 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001610 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001611 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001612 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001613 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001614 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001615 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1616 if (netCap == null) {
1617 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1618 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001619 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001620 }
1621
1622 NetworkRequest request = null;
1623 synchronized (sLegacyRequests) {
1624 LegacyRequest l = sLegacyRequests.get(netCap);
1625 if (l != null) {
1626 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1627 renewRequestLocked(l);
1628 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001629 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001630 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001631 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001632 }
1633 }
1634
1635 request = requestNetworkForFeatureLocked(netCap);
1636 }
1637 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001638 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001639 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001640 } else {
1641 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001642 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001643 }
1644 }
1645
1646 /**
1647 * Tells the underlying networking system that the caller is finished
1648 * using the named feature. The interpretation of {@code feature}
1649 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001650 *
1651 * <p>This method requires the caller to hold either the
1652 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1653 * or the ability to modify system settings as determined by
1654 * {@link android.provider.Settings.System#canWrite}.</p>
1655 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001656 * @param networkType specifies which network the request pertains to
1657 * @param feature the name of the feature that is no longer needed
1658 * @return an integer value representing the outcome of the request.
1659 * The interpretation of this value is specific to each networking
1660 * implementation+feature combination, except that the value {@code -1}
1661 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001662 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001663 * @deprecated Deprecated in favor of the cleaner
1664 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001665 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001666 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001667 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001668 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001669 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001670 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001671 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001672 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1673 if (netCap == null) {
1674 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1675 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001676 return -1;
1677 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001678
Paul Jensen49f74a32014-12-17 10:39:34 -05001679 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001680 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001681 }
1682 return 1;
1683 }
1684
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001685 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001686 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1687 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001688 switch (feature) {
1689 case "enableCBS":
1690 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1691 case "enableDUN":
1692 case "enableDUNAlways":
1693 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1694 case "enableFOTA":
1695 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1696 case "enableHIPRI":
1697 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1698 case "enableIMS":
1699 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1700 case "enableMMS":
1701 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1702 case "enableSUPL":
1703 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1704 default:
1705 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001706 }
Erik Klinece55eb12017-01-26 18:08:28 +09001707 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1708 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001709 }
1710 return null;
1711 }
1712
Robert Greenwalt802c1102014-06-02 15:32:02 -07001713 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001714 if (netCap == null) return TYPE_NONE;
1715 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1716 return TYPE_MOBILE_CBS;
1717 }
1718 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1719 return TYPE_MOBILE_IMS;
1720 }
1721 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1722 return TYPE_MOBILE_FOTA;
1723 }
1724 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1725 return TYPE_MOBILE_DUN;
1726 }
1727 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1728 return TYPE_MOBILE_SUPL;
1729 }
1730 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1731 return TYPE_MOBILE_MMS;
1732 }
1733 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1734 return TYPE_MOBILE_HIPRI;
1735 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001736 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1737 return TYPE_WIFI_P2P;
1738 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001739 return TYPE_NONE;
1740 }
1741
1742 private static class LegacyRequest {
1743 NetworkCapabilities networkCapabilities;
1744 NetworkRequest networkRequest;
1745 int expireSequenceNumber;
1746 Network currentNetwork;
1747 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001748
1749 private void clearDnsBinding() {
1750 if (currentNetwork != null) {
1751 currentNetwork = null;
1752 setProcessDefaultNetworkForHostResolution(null);
1753 }
1754 }
1755
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001756 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001757 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001758 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001759 currentNetwork = network;
1760 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001761 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001762 }
1763 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001764 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001765 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001766 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1767 }
1768 };
1769 }
1770
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001771 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001772 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1773 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001774
1775 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1776 synchronized (sLegacyRequests) {
1777 LegacyRequest l = sLegacyRequests.get(netCap);
1778 if (l != null) return l.networkRequest;
1779 }
1780 return null;
1781 }
1782
1783 private void renewRequestLocked(LegacyRequest l) {
1784 l.expireSequenceNumber++;
1785 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1786 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1787 }
1788
1789 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1790 int ourSeqNum = -1;
1791 synchronized (sLegacyRequests) {
1792 LegacyRequest l = sLegacyRequests.get(netCap);
1793 if (l == null) return;
1794 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001795 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001796 }
1797 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1798 }
1799
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001800 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001801 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1802 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001803 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001804 try {
1805 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001806 } catch (RemoteException e) {
1807 throw e.rethrowFromSystemServer();
1808 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001809 LegacyRequest l = new LegacyRequest();
1810 l.networkCapabilities = netCap;
1811 l.delay = delay;
1812 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001813 l.networkRequest = sendRequestForNetwork(
1814 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001815 if (l.networkRequest == null) return null;
1816 sLegacyRequests.put(netCap, l);
1817 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1818 return l.networkRequest;
1819 }
1820
1821 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1822 if (delay >= 0) {
1823 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001824 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001825 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1826 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001827 }
1828 }
1829
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001830 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001831 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1832 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001833 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001834 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001835 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001836 if (l == null) return false;
1837 unregisterNetworkCallback(l.networkCallback);
1838 l.clearDnsBinding();
1839 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001840 }
1841
Erik Klinece55eb12017-01-26 18:08:28 +09001842 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1843 static {
1844 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1845 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1846 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1847 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1848 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1849 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1850 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1851 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1852 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1853 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1854 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1855 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1856 }
1857
1858 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1859 static {
1860 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1861 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1862 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1863 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1864 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1865 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1866 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1867 }
1868
1869 /**
1870 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1871 * instance suitable for registering a request or callback. Throws an
1872 * IllegalArgumentException if no mapping from the legacy type to
1873 * NetworkCapabilities is known.
1874 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001875 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1876 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001877 * @hide
1878 */
1879 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1880 final NetworkCapabilities nc = new NetworkCapabilities();
1881
1882 // Map from type to transports.
1883 final int NOT_FOUND = -1;
1884 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00001885 if (transport == NOT_FOUND) {
1886 throw new IllegalArgumentException("unknown legacy type: " + type);
1887 }
Erik Klinece55eb12017-01-26 18:08:28 +09001888 nc.addTransportType(transport);
1889
1890 // Map from type to capabilities.
1891 nc.addCapability(sLegacyTypeToCapability.get(
1892 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1893 nc.maybeMarkCapabilitiesRestricted();
1894 return nc;
1895 }
1896
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001897 /** @hide */
1898 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001899 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001900 public PacketKeepaliveCallback() {
1901 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001902 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001903 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001904 public void onStarted() {}
1905 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001906 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001907 public void onStopped() {}
1908 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001909 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001910 public void onError(int error) {}
1911 }
1912
1913 /**
1914 * Allows applications to request that the system periodically send specific packets on their
1915 * behalf, using hardware offload to save battery power.
1916 *
1917 * To request that the system send keepalives, call one of the methods that return a
1918 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1919 * passing in a non-null callback. If the callback is successfully started, the callback's
1920 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1921 * specifying one of the {@code ERROR_*} constants in this class.
1922 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001923 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1924 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1925 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001926 *
junyulai4c95b082018-12-27 17:25:29 +08001927 * @deprecated Use {@link SocketKeepalive} instead.
1928 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001929 * @hide
1930 */
1931 public class PacketKeepalive {
1932
1933 private static final String TAG = "PacketKeepalive";
1934
1935 /** @hide */
1936 public static final int SUCCESS = 0;
1937
1938 /** @hide */
1939 public static final int NO_KEEPALIVE = -1;
1940
1941 /** @hide */
1942 public static final int BINDER_DIED = -10;
1943
1944 /** The specified {@code Network} is not connected. */
1945 public static final int ERROR_INVALID_NETWORK = -20;
1946 /** The specified IP addresses are invalid. For example, the specified source IP address is
1947 * not configured on the specified {@code Network}. */
1948 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1949 /** The requested port is invalid. */
1950 public static final int ERROR_INVALID_PORT = -22;
1951 /** The packet length is invalid (e.g., too long). */
1952 public static final int ERROR_INVALID_LENGTH = -23;
1953 /** The packet transmission interval is invalid (e.g., too short). */
1954 public static final int ERROR_INVALID_INTERVAL = -24;
1955
1956 /** The hardware does not support this request. */
1957 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001958 /** The hardware returned an error. */
1959 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001960
Nathan Harold0990bc82018-02-14 13:09:45 -08001961 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001962 public static final int NATT_PORT = 4500;
1963
Nathan Harold0990bc82018-02-14 13:09:45 -08001964 /** The minimum interval in seconds between keepalive packet transmissions */
1965 public static final int MIN_INTERVAL = 10;
1966
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001967 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001968 private final ISocketKeepaliveCallback mCallback;
1969 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001970
1971 private volatile Integer mSlot;
1972
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001973 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001974 public void stop() {
1975 try {
junyulai070f9ff2019-01-16 20:23:34 +08001976 mExecutor.execute(() -> {
1977 try {
1978 if (mSlot != null) {
1979 mService.stopKeepalive(mNetwork, mSlot);
1980 }
1981 } catch (RemoteException e) {
1982 Log.e(TAG, "Error stopping packet keepalive: ", e);
1983 throw e.rethrowFromSystemServer();
1984 }
1985 });
1986 } catch (RejectedExecutionException e) {
1987 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001988 }
1989 }
1990
1991 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00001992 Objects.requireNonNull(network, "network cannot be null");
1993 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001994 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001995 mExecutor = Executors.newSingleThreadExecutor();
1996 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001997 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001998 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001999 final long token = Binder.clearCallingIdentity();
2000 try {
2001 mExecutor.execute(() -> {
2002 mSlot = slot;
2003 callback.onStarted();
2004 });
2005 } finally {
2006 Binder.restoreCallingIdentity(token);
2007 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002008 }
junyulai070f9ff2019-01-16 20:23:34 +08002009
2010 @Override
2011 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08002012 final long token = Binder.clearCallingIdentity();
2013 try {
2014 mExecutor.execute(() -> {
2015 mSlot = null;
2016 callback.onStopped();
2017 });
2018 } finally {
2019 Binder.restoreCallingIdentity(token);
2020 }
junyulai070f9ff2019-01-16 20:23:34 +08002021 mExecutor.shutdown();
2022 }
2023
2024 @Override
2025 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08002026 final long token = Binder.clearCallingIdentity();
2027 try {
2028 mExecutor.execute(() -> {
2029 mSlot = null;
2030 callback.onError(error);
2031 });
2032 } finally {
2033 Binder.restoreCallingIdentity(token);
2034 }
junyulai070f9ff2019-01-16 20:23:34 +08002035 mExecutor.shutdown();
2036 }
2037
2038 @Override
2039 public void onDataReceived() {
2040 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2041 // this callback when data is received.
2042 }
2043 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002044 }
2045 }
2046
2047 /**
2048 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2049 *
junyulai4c95b082018-12-27 17:25:29 +08002050 * @deprecated Use {@link #createSocketKeepalive} instead.
2051 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002052 * @hide
2053 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002054 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002055 public PacketKeepalive startNattKeepalive(
2056 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2057 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2058 final PacketKeepalive k = new PacketKeepalive(network, callback);
2059 try {
junyulai070f9ff2019-01-16 20:23:34 +08002060 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002061 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2062 } catch (RemoteException e) {
2063 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08002064 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002065 }
2066 return k;
2067 }
2068
Chiachang Wang619319a2021-01-15 11:06:21 +08002069 // Construct an invalid fd.
2070 private ParcelFileDescriptor createInvalidFd() {
2071 final int invalidFd = -1;
2072 return ParcelFileDescriptor.adoptFd(invalidFd);
2073 }
2074
The Android Open Source Project28527d22009-03-03 19:31:44 -08002075 /**
junyulai4c95b082018-12-27 17:25:29 +08002076 * Request that keepalives be started on a IPsec NAT-T socket.
2077 *
2078 * @param network The {@link Network} the socket is on.
2079 * @param socket The socket that needs to be kept alive.
2080 * @param source The source address of the {@link UdpEncapsulationSocket}.
2081 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2082 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2083 * must run callback sequentially, otherwise the order of callbacks cannot be
2084 * guaranteed.
2085 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2086 * changes. Must be extended by applications that use this API.
2087 *
junyulai0835a1e2019-01-08 20:04:33 +08002088 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2089 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08002090 **/
junyulai7e06ad42019-03-04 22:45:36 +08002091 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08002092 @NonNull UdpEncapsulationSocket socket,
2093 @NonNull InetAddress source,
2094 @NonNull InetAddress destination,
2095 @NonNull @CallbackExecutor Executor executor,
2096 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002097 ParcelFileDescriptor dup;
2098 try {
junyulai828dad12019-03-27 11:00:37 +08002099 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2100 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08002101 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2102 } catch (IOException ignored) {
2103 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2104 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002105 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002106 }
2107 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2108 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002109 }
2110
2111 /**
2112 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2113 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2114 *
2115 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002116 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2117 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2118 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002119 * @param source The source address of the {@link UdpEncapsulationSocket}.
2120 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2121 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2122 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2123 * must run callback sequentially, otherwise the order of callbacks cannot be
2124 * guaranteed.
2125 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2126 * changes. Must be extended by applications that use this API.
2127 *
junyulai0835a1e2019-01-08 20:04:33 +08002128 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2129 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002130 * @hide
2131 */
2132 @SystemApi
2133 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002134 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2135 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002136 @NonNull InetAddress source,
2137 @NonNull InetAddress destination,
2138 @NonNull @CallbackExecutor Executor executor,
2139 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002140 ParcelFileDescriptor dup;
2141 try {
junyulai828dad12019-03-27 11:00:37 +08002142 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002143 dup = pfd.dup();
2144 } catch (IOException ignored) {
2145 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2146 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002147 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002148 }
2149 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANce355502021-03-11 10:56:49 +00002150 -1 /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002151 }
2152
2153 /**
junyulai0835a1e2019-01-08 20:04:33 +08002154 * Request that keepalives be started on a TCP socket.
2155 * The socket must be established.
2156 *
2157 * @param network The {@link Network} the socket is on.
2158 * @param socket The socket that needs to be kept alive.
2159 * @param executor The executor on which callback will be invoked. This implementation assumes
2160 * the provided {@link Executor} runs the callbacks in sequence with no
2161 * concurrency. Failing this, no guarantee of correctness can be made. It is
2162 * the responsibility of the caller to ensure the executor provides this
2163 * guarantee. A simple way of creating such an executor is with the standard
2164 * tool {@code Executors.newSingleThreadExecutor}.
2165 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2166 * changes. Must be extended by applications that use this API.
2167 *
2168 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2169 * given socket.
2170 * @hide
2171 */
2172 @SystemApi
2173 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002174 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002175 @NonNull Socket socket,
2176 @NonNull Executor executor,
2177 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002178 ParcelFileDescriptor dup;
2179 try {
2180 dup = ParcelFileDescriptor.fromSocket(socket);
2181 } catch (UncheckedIOException ignored) {
2182 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2183 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002184 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002185 }
2186 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002187 }
2188
2189 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002190 * Ensure that a network route exists to deliver traffic to the specified
2191 * host via the specified network interface. An attempt to add a route that
2192 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002193 *
2194 * <p>This method requires the caller to hold either the
2195 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2196 * or the ability to modify system settings as determined by
2197 * {@link android.provider.Settings.System#canWrite}.</p>
2198 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002199 * @param networkType the type of the network over which traffic to the specified
2200 * host is to be routed
2201 * @param hostAddress the IP address of the host to which the route is desired
2202 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002203 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002204 * @deprecated Deprecated in favor of the
2205 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2206 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002207 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002208 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002209 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002210 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002211 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002212 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002213 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002214 }
2215
2216 /**
2217 * Ensure that a network route exists to deliver traffic to the specified
2218 * host via the specified network interface. An attempt to add a route that
2219 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002220 *
2221 * <p>This method requires the caller to hold either the
2222 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2223 * or the ability to modify system settings as determined by
2224 * {@link android.provider.Settings.System#canWrite}.</p>
2225 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002226 * @param networkType the type of the network over which traffic to the specified
2227 * host is to be routed
2228 * @param hostAddress the IP address of the host to which the route is desired
2229 * @return {@code true} on success, {@code false} on failure
2230 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002231 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002232 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002233 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002234 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002235 @UnsupportedAppUsage
lucasline257bce2021-03-22 11:51:27 +08002236 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002237 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002238 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002239 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002240 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2241 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002243 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002244 }
2245 }
2246
2247 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002248 * @return the context's attribution tag
2249 */
2250 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2251 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002252 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002253 }
2254
2255 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002256 * Returns the value of the setting for background data usage. If false,
2257 * applications should not use the network if the application is not in the
2258 * foreground. Developers should respect this setting, and check the value
2259 * of this before performing any background data operations.
2260 * <p>
2261 * All applications that have background services that use the network
2262 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002263 * <p>
Scott Main50589142011-10-06 18:32:43 -07002264 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002265 * background data depends on several combined factors, and this method will
2266 * always return {@code true}. Instead, when background data is unavailable,
2267 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002268 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002269 * @return Whether background data usage is allowed.
2270 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002271 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002272 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002273 // assume that background data is allowed; final authority is
2274 // NetworkInfo which may be blocked.
2275 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002276 }
2277
2278 /**
2279 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002280 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002281 * @param allowBackgroundData Whether an application should use data while
2282 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002283 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002284 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2285 * @see #getBackgroundDataSetting()
2286 * @hide
2287 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002288 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002289 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002290 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002291 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002292 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002293
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002294 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002295 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002296 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002297 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002298 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002299 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002300 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002301 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2302 if (tm != null) {
2303 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2304 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2305 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2306 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2307 + " retVal=" + retVal);
2308 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002309 }
Wink Saville689f7042014-12-05 11:10:30 -08002310 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002311 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002312 }
2313
The Android Open Source Project28527d22009-03-03 19:31:44 -08002314 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002315 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002316 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002317 */
2318 public interface OnNetworkActiveListener {
2319 /**
2320 * Called on the main thread of the process to report that the current data network
2321 * has become active, and it is now a good time to perform any pending network
2322 * operations. Note that this listener only tells you when the network becomes
2323 * active; if at any other time you want to know whether it is active (and thus okay
2324 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002325 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002326 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002327 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002328 }
2329
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002330 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002331 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002332
2333 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002334 * Start listening to reports when the system's default data network is active, meaning it is
2335 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2336 * to determine the current state of the system's default network after registering the
2337 * listener.
2338 * <p>
2339 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002340 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002341 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002342 *
2343 * @param l The listener to be told when the network is active.
2344 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002345 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002346 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2347 @Override
2348 public void onNetworkActive() throws RemoteException {
2349 l.onNetworkActive();
2350 }
2351 };
2352
2353 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002354 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002355 mNetworkActivityListeners.put(l, rl);
2356 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002357 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002358 }
2359 }
2360
2361 /**
2362 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002363 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002364 *
2365 * @param l Previously registered listener.
2366 */
Chalard Jean158702d2019-01-07 19:26:34 +09002367 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002368 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002369 if (rl == null) {
2370 throw new IllegalArgumentException("Listener was not registered.");
2371 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002372 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002373 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002374 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002375 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002376 }
2377 }
2378
2379 /**
2380 * Return whether the data network is currently active. An active network means that
2381 * it is currently in a high power state for performing data transmission. On some
2382 * types of networks, it may be expensive to move and stay in such a state, so it is
2383 * more power efficient to batch network traffic together when the radio is already in
2384 * this state. This method tells you whether right now is currently a good time to
2385 * initiate network traffic, as the network is already active.
2386 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002387 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002388 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002389 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002390 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002391 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002392 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002393 }
2394
2395 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002396 * {@hide}
2397 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002398 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002399 mContext = Objects.requireNonNull(context, "missing context");
2400 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002401 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002402 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002403 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002404
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002405 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002406 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002407 public static ConnectivityManager from(Context context) {
2408 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2409 }
2410
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002411 /** @hide */
2412 public NetworkRequest getDefaultRequest() {
2413 try {
2414 // This is not racy as the default request is final in ConnectivityService.
2415 return mService.getDefaultRequest();
2416 } catch (RemoteException e) {
2417 throw e.rethrowFromSystemServer();
2418 }
2419 }
2420
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002421 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002422 * Check if the package is a allowed to write settings. This also accounts that such an access
2423 * happened.
2424 *
2425 * @return {@code true} iff the package is allowed to write settings.
2426 */
2427 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2428 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2429 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2430 boolean throwException) {
2431 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2432 throwException);
2433 }
2434
2435 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002436 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2437 * situations where a Context pointer is unavailable.
2438 * @hide
2439 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002440 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002441 static ConnectivityManager getInstanceOrNull() {
2442 return sInstance;
2443 }
2444
2445 /**
2446 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2447 * situations where a Context pointer is unavailable.
2448 * @hide
2449 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002450 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002451 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002452 private static ConnectivityManager getInstance() {
2453 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002454 throw new IllegalStateException("No ConnectivityManager yet constructed");
2455 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002456 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002457 }
2458
2459 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002460 * Get the set of tetherable, available interfaces. This list is limited by
2461 * device configuration and current interface existence.
2462 *
2463 * @return an array of 0 or more Strings of tetherable interface names.
2464 *
markchien6ae63e52020-01-21 13:11:06 +08002465 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002466 * {@hide}
2467 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002468 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002469 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002470 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002471 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002472 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002473 }
2474
2475 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002476 * Get the set of tethered interfaces.
2477 *
2478 * @return an array of 0 or more String of currently tethered interface names.
2479 *
markchien6ae63e52020-01-21 13:11:06 +08002480 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002481 * {@hide}
2482 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002483 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002484 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002485 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002486 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002487 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002488 }
2489
2490 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002491 * Get the set of interface names which attempted to tether but
2492 * failed. Re-attempting to tether may cause them to reset to the Tethered
2493 * state. Alternatively, causing the interface to be destroyed and recreated
2494 * may cause them to reset to the available state.
2495 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2496 * information on the cause of the errors.
2497 *
2498 * @return an array of 0 or more String indicating the interface names
2499 * which failed to tether.
2500 *
markchien6ae63e52020-01-21 13:11:06 +08002501 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002502 * {@hide}
2503 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002504 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002505 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002506 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002507 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002508 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002509 }
2510
2511 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002512 * Get the set of tethered dhcp ranges.
2513 *
markchien2e6ba522020-02-14 11:55:48 +08002514 * @deprecated This method is not supported.
2515 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002516 * {@hide}
2517 */
paulhu8e96a752019-08-12 16:25:11 +08002518 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002519 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002520 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002521 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002522 }
2523
2524 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002525 * Attempt to tether the named interface. This will setup a dhcp server
2526 * on the interface, forward and NAT IP packets and forward DNS requests
2527 * to the best active upstream network interface. Note that if no upstream
2528 * IP network interface is available, dhcp will still run and traffic will be
2529 * allowed between the tethered devices and this device, though upstream net
2530 * access will of course fail until an upstream network interface becomes
2531 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002532 *
2533 * <p>This method requires the caller to hold either the
2534 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2535 * or the ability to modify system settings as determined by
2536 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002537 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002538 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2539 * and WifiStateMachine which need direct access. All other clients should use
2540 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2541 * logic.</p>
2542 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002543 * @param iface the interface name to tether.
2544 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002545 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002546 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002547 * {@hide}
2548 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002549 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002550 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002551 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002552 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002553 }
2554
2555 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002556 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002557 *
2558 * <p>This method requires the caller to hold either the
2559 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2560 * or the ability to modify system settings as determined by
2561 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002562 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002563 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2564 * and WifiStateMachine which need direct access. All other clients should use
2565 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2566 * logic.</p>
2567 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002568 * @param iface the interface name to untether.
2569 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2570 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002571 * {@hide}
2572 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002573 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002574 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002575 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002576 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002577 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002578
2579 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002580 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002581 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002582 * due to device configuration.
2583 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002584 * <p>If this app does not have permission to use this API, it will always
2585 * return false rather than throw an exception.</p>
2586 *
2587 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2588 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2589 *
2590 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2591 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2592 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002593 * @return a boolean - {@code true} indicating Tethering is supported.
2594 *
markchien6ae63e52020-01-21 13:11:06 +08002595 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002596 * {@hide}
2597 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002598 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002599 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2600 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002601 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002602 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002603 }
2604
2605 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002606 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002607 *
2608 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002609 * @hide
2610 */
2611 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002612 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002613 public static abstract class OnStartTetheringCallback {
2614 /**
2615 * Called when tethering has been successfully started.
2616 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002617 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002618
2619 /**
2620 * Called when starting tethering failed.
2621 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002622 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002623 }
2624
2625 /**
2626 * Convenient overload for
2627 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2628 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002629 *
2630 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002631 * @hide
2632 */
2633 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002634 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002635 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002636 public void startTethering(int type, boolean showProvisioningUi,
2637 final OnStartTetheringCallback callback) {
2638 startTethering(type, showProvisioningUi, callback, null);
2639 }
2640
2641 /**
2642 * Runs tether provisioning for the given type if needed and then starts tethering if
2643 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2644 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2645 * schedules tether provisioning re-checks if appropriate.
2646 *
2647 * @param type The type of tethering to start. Must be one of
2648 * {@link ConnectivityManager.TETHERING_WIFI},
2649 * {@link ConnectivityManager.TETHERING_USB}, or
2650 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2651 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2652 * is one. This should be true the first time this function is called and also any time
2653 * the user can see this UI. It gives users information from their carrier about the
2654 * check failing and how they can sign up for tethering if possible.
2655 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2656 * of the result of trying to tether.
2657 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002658 *
2659 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002660 * @hide
2661 */
2662 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002663 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002664 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002665 public void startTethering(int type, boolean showProvisioningUi,
2666 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002667 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002668
markchien91c78e52020-01-20 19:31:56 +08002669 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002670 @Override
markchien91c78e52020-01-20 19:31:56 +08002671 public void execute(Runnable command) {
2672 if (handler == null) {
2673 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002674 } else {
markchien91c78e52020-01-20 19:31:56 +08002675 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002676 }
2677 }
2678 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002679
markchien91c78e52020-01-20 19:31:56 +08002680 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2681 @Override
2682 public void onTetheringStarted() {
2683 callback.onTetheringStarted();
2684 }
2685
2686 @Override
markchienf47d8342020-03-19 13:37:43 +08002687 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002688 callback.onTetheringFailed();
2689 }
2690 };
2691
2692 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002693 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002694
Amos Bianchia9b415a2020-03-04 11:07:38 -08002695 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002696 }
2697
2698 /**
2699 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2700 * applicable.
2701 *
2702 * @param type The type of tethering to stop. Must be one of
2703 * {@link ConnectivityManager.TETHERING_WIFI},
2704 * {@link ConnectivityManager.TETHERING_USB}, or
2705 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002706 *
2707 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002708 * @hide
2709 */
2710 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002711 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002712 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002713 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002714 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002715 }
2716
2717 /**
markchien4ef53e82019-02-27 14:56:11 +08002718 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2719 * upstream status.
2720 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002721 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002722 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002723 */
2724 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002725 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002726 public abstract static class OnTetheringEventCallback {
2727
2728 /**
2729 * Called when tethering upstream changed. This can be called multiple times and can be
2730 * called any time.
2731 *
2732 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2733 * have any upstream.
2734 */
2735 public void onUpstreamChanged(@Nullable Network network) {}
2736 }
2737
markchien6ae63e52020-01-21 13:11:06 +08002738 @GuardedBy("mTetheringEventCallbacks")
2739 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2740 mTetheringEventCallbacks = new ArrayMap<>();
2741
markchien4ef53e82019-02-27 14:56:11 +08002742 /**
2743 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002744 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002745 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2746 * with a null argument. The same callback object cannot be registered twice.
2747 *
2748 * @param executor the executor on which callback will be invoked.
2749 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002750 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002751 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002752 * @hide
2753 */
2754 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002755 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002756 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2757 public void registerTetheringEventCallback(
2758 @NonNull @CallbackExecutor Executor executor,
2759 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002760 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchien4ef53e82019-02-27 14:56:11 +08002761
markchien6ae63e52020-01-21 13:11:06 +08002762 final TetheringEventCallback tetherCallback =
2763 new TetheringEventCallback() {
2764 @Override
2765 public void onUpstreamChanged(@Nullable Network network) {
2766 callback.onUpstreamChanged(network);
2767 }
2768 };
2769
2770 synchronized (mTetheringEventCallbacks) {
2771 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002772 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002773 }
markchien4ef53e82019-02-27 14:56:11 +08002774 }
2775
2776 /**
2777 * Remove tethering event callback previously registered with
2778 * {@link #registerTetheringEventCallback}.
2779 *
2780 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002781 *
2782 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002783 * @hide
2784 */
2785 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002786 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002787 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2788 public void unregisterTetheringEventCallback(
2789 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002790 Objects.requireNonNull(callback, "The callback must be non-null");
2791 synchronized (mTetheringEventCallbacks) {
2792 final TetheringEventCallback tetherCallback =
2793 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002794 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002795 }
markchien4ef53e82019-02-27 14:56:11 +08002796 }
2797
2798
2799 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002800 * Get the list of regular expressions that define any tetherable
2801 * USB network interfaces. If USB tethering is not supported by the
2802 * device, this list should be empty.
2803 *
2804 * @return an array of 0 or more regular expression Strings defining
2805 * what interfaces are considered tetherable usb interfaces.
2806 *
markchien6ae63e52020-01-21 13:11:06 +08002807 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002808 * {@hide}
2809 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002810 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002811 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002812 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002813 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002814 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002815 }
2816
2817 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002818 * Get the list of regular expressions that define any tetherable
2819 * Wifi network interfaces. If Wifi tethering is not supported by the
2820 * device, this list should be empty.
2821 *
2822 * @return an array of 0 or more regular expression Strings defining
2823 * what interfaces are considered tetherable wifi interfaces.
2824 *
markchien6ae63e52020-01-21 13:11:06 +08002825 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002826 * {@hide}
2827 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002828 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002829 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002830 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002831 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002832 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002833 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002834
Danica Chang96567052010-08-11 14:54:43 -07002835 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002836 * Get the list of regular expressions that define any tetherable
2837 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2838 * device, this list should be empty.
2839 *
2840 * @return an array of 0 or more regular expression Strings defining
2841 * what interfaces are considered tetherable bluetooth interfaces.
2842 *
markchien6ae63e52020-01-21 13:11:06 +08002843 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2844 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002845 * {@hide}
2846 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002847 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002848 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002849 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002850 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002851 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002852 }
2853
Mike Lockwooded4a1742011-07-19 13:04:47 -07002854 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002855 * Attempt to both alter the mode of USB and Tethering of USB. A
2856 * utility method to deal with some of the complexity of USB - will
2857 * attempt to switch to Rndis and subsequently tether the resulting
2858 * interface on {@code true} or turn off tethering and switch off
2859 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002860 *
2861 * <p>This method requires the caller to hold either the
2862 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2863 * or the ability to modify system settings as determined by
2864 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002865 *
2866 * @param enable a boolean - {@code true} to enable tethering
2867 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002868 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002869 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002870 * {@hide}
2871 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002872 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002873 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002874 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002875 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002876 }
2877
markchien6ae63e52020-01-21 13:11:06 +08002878 /**
2879 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2880 * {@hide}
2881 */
markchien0f45bb92019-01-16 17:44:13 +08002882 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002883 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002884 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002885 /**
2886 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2887 * {@hide}
2888 */
2889 @Deprecated
2890 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2891 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2892 /**
2893 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2894 * {@hide}
2895 */
2896 @Deprecated
2897 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2898 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2899 /**
2900 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2901 * {@hide}
2902 */
2903 @Deprecated
2904 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2905 /**
2906 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2907 * {@hide}
2908 */
2909 @Deprecated
2910 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2911 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2912 /**
markchienf47d8342020-03-19 13:37:43 +08002913 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002914 * {@hide}
2915 */
2916 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002917 public static final int TETHER_ERROR_MASTER_ERROR =
2918 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002919 /**
2920 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2921 * {@hide}
2922 */
2923 @Deprecated
2924 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2925 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2926 /**
2927 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2928 * {@hide}
2929 */
2930 @Deprecated
2931 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2932 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2933 /**
markchienf47d8342020-03-19 13:37:43 +08002934 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002935 * {@hide}
2936 */
2937 @Deprecated
2938 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002939 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002940 /**
markchienf47d8342020-03-19 13:37:43 +08002941 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002942 * {@hide}
2943 */
2944 @Deprecated
2945 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002946 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002947 /**
2948 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2949 * {@hide}
2950 */
2951 @Deprecated
2952 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2953 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2954 /**
markchienf47d8342020-03-19 13:37:43 +08002955 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002956 * {@hide}
2957 */
markchien0f45bb92019-01-16 17:44:13 +08002958 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002959 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002960 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002961 /**
2962 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2963 * {@hide}
2964 */
2965 @Deprecated
2966 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2967 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2968 /**
2969 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2970 * {@hide}
2971 */
markchien0f45bb92019-01-16 17:44:13 +08002972 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002973 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002974 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002975
2976 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002977 * Get a more detailed error code after a Tethering or Untethering
2978 * request asynchronously failed.
2979 *
2980 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002981 * @return error The error code of the last error tethering or untethering the named
2982 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002983 *
markchien6ae63e52020-01-21 13:11:06 +08002984 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002985 * {@hide}
2986 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002987 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002988 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002989 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002990 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002991 int error = mTetheringManager.getLastTetherError(iface);
2992 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2993 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2994 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2995 // instead.
2996 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2997 }
2998 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002999 }
3000
markchienbf5ab012019-03-06 16:25:00 +08003001 /** @hide */
3002 @Retention(RetentionPolicy.SOURCE)
3003 @IntDef(value = {
3004 TETHER_ERROR_NO_ERROR,
3005 TETHER_ERROR_PROVISION_FAILED,
3006 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3007 })
3008 public @interface EntitlementResultCode {
3009 }
3010
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003011 /**
markchienbf5ab012019-03-06 16:25:00 +08003012 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08003013 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08003014 *
3015 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08003016 * @hide
3017 */
3018 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08003019 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08003020 public interface OnTetheringEntitlementResultListener {
3021 /**
3022 * Called to notify entitlement result.
3023 *
3024 * @param resultCode an int value of entitlement result. It may be one of
3025 * {@link #TETHER_ERROR_NO_ERROR},
3026 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3027 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3028 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07003029 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08003030 }
3031
3032 /**
markchien0f45bb92019-01-16 17:44:13 +08003033 * Get the last value of the entitlement check on this downstream. If the cached value is
3034 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3035 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3036 * guaranteed that the UI-based entitlement check will complete in any specific time period
3037 * and may in fact never complete. Any successful entitlement check the platform performs for
3038 * any reason will update the cached value.
3039 *
3040 * @param type the downstream type of tethering. Must be one of
3041 * {@link #TETHERING_WIFI},
3042 * {@link #TETHERING_USB}, or
3043 * {@link #TETHERING_BLUETOOTH}.
3044 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08003045 * @param executor the executor on which callback will be invoked.
3046 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3047 * notify the caller of the result of entitlement check. The listener may be called zero
3048 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08003049 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08003050 * {@hide}
3051 */
3052 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08003053 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08003054 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08003055 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3056 @NonNull @CallbackExecutor Executor executor,
3057 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003058 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchienbf5ab012019-03-06 16:25:00 +08003059 ResultReceiver wrappedListener = new ResultReceiver(null) {
3060 @Override
3061 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08003062 final long token = Binder.clearCallingIdentity();
3063 try {
3064 executor.execute(() -> {
3065 listener.onTetheringEntitlementResult(resultCode);
3066 });
3067 } finally {
3068 Binder.restoreCallingIdentity(token);
3069 }
markchienbf5ab012019-03-06 16:25:00 +08003070 }
3071 };
3072
Amos Bianchia9b415a2020-03-04 11:07:38 -08003073 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08003074 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08003075 }
3076
3077 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003078 * Report network connectivity status. This is currently used only
3079 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003080 * <p>This method requires the caller to hold the permission
3081 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003082 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003083 * @param networkType The type of network you want to report on
3084 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003085 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003086 * {@hide}
3087 */
3088 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003089 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003090 try {
3091 mService.reportInetCondition(networkType, percentage);
3092 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003093 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003094 }
3095 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003096
3097 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003098 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003099 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003100 * the framework to re-evaluate network connectivity and/or switch to another
3101 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003102 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003103 * @param network The {@link Network} the application was attempting to use
3104 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003105 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3106 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003107 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003108 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003109 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003110 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003111 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003112 // One of these will be ignored because it matches system's current state.
3113 // The other will trigger the necessary reevaluation.
3114 mService.reportNetworkConnectivity(network, true);
3115 mService.reportNetworkConnectivity(network, false);
3116 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003117 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003118 }
3119 }
3120
3121 /**
3122 * Report to the framework whether a network has working connectivity.
3123 * This provides a hint to the system that a particular network is providing
3124 * working connectivity or not. In response the framework may re-evaluate
3125 * the network's connectivity and might take further action thereafter.
3126 *
3127 * @param network The {@link Network} the application was attempting to use
3128 * or {@code null} to indicate the current default network.
3129 * @param hasConnectivity {@code true} if the application was able to successfully access the
3130 * Internet using {@code network} or {@code false} if not.
3131 */
Chalard Jean158702d2019-01-07 19:26:34 +09003132 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003133 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003134 try {
3135 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003136 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003137 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003138 }
3139 }
3140
3141 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003142 * Set a network-independent global http proxy. This is not normally what you want
3143 * for typical HTTP proxies - they are general network dependent. However if you're
3144 * doing something unusual like general internal filtering this may be useful. On
3145 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003146 *
3147 * @param p A {@link ProxyInfo} object defining the new global
3148 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003149 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003150 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003151 @SystemApi(client = MODULE_LIBRARIES)
paulhu8e96a752019-08-12 16:25:11 +08003152 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang4d513572021-03-18 09:44:34 +08003153 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003154 try {
3155 mService.setGlobalProxy(p);
3156 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003157 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003158 }
3159 }
3160
3161 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003162 * Retrieve any network-independent global HTTP proxy.
3163 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003164 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003165 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003166 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003167 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003168 @SystemApi(client = MODULE_LIBRARIES)
3169 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04003170 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003171 try {
3172 return mService.getGlobalProxy();
3173 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003174 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003175 }
3176 }
3177
3178 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003179 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3180 * network-specific HTTP proxy. If {@code network} is null, the
3181 * network-specific proxy returned is the proxy of the default active
3182 * network.
3183 *
3184 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3185 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3186 * or when {@code network} is {@code null},
3187 * the {@code ProxyInfo} for the default active network. Returns
3188 * {@code null} when no proxy applies or the caller doesn't have
3189 * permission to use {@code network}.
3190 * @hide
3191 */
3192 public ProxyInfo getProxyForNetwork(Network network) {
3193 try {
3194 return mService.getProxyForNetwork(network);
3195 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003196 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003197 }
3198 }
3199
3200 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003201 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3202 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003203 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003204 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003205 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003206 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003207 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003208 */
Chalard Jean158702d2019-01-07 19:26:34 +09003209 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003210 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003211 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003212 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003213
3214 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003215 * Returns true if the hardware supports the given network type
3216 * else it returns false. This doesn't indicate we have coverage
3217 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003218 * hardware supports it. For example a GSM phone without a SIM
3219 * should still return {@code true} for mobile data, but a wifi only
3220 * tablet would return {@code false}.
3221 *
3222 * @param networkType The network type we'd like to check
3223 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003224 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003225 * @hide
3226 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003227 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003228 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003229 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003230 public boolean isNetworkSupported(int networkType) {
3231 try {
3232 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003233 } catch (RemoteException e) {
3234 throw e.rethrowFromSystemServer();
3235 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003236 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003237
3238 /**
3239 * Returns if the currently active data network is metered. A network is
3240 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003241 * that connection due to monetary costs, data limitations or
3242 * battery/performance issues. You should check this before doing large
3243 * data transfers, and warn the user or delay the operation until another
3244 * network is available.
3245 *
3246 * @return {@code true} if large transfers should be avoided, otherwise
3247 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003248 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003249 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003250 public boolean isActiveNetworkMetered() {
3251 try {
3252 return mService.isActiveNetworkMetered();
3253 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003254 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003255 }
3256 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003257
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003258 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003259 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003260 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003261 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003262 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003263 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003264 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003265 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003266 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003267 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003268 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003269 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003270 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003271 }
3272 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003273
3274 /**
3275 * Set the value for enabling/disabling airplane mode
3276 *
3277 * @param enable whether to enable airplane mode or not
3278 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003279 * @hide
3280 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003281 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003282 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003283 android.Manifest.permission.NETWORK_SETTINGS,
3284 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3285 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003286 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003287 public void setAirplaneMode(boolean enable) {
3288 try {
3289 mService.setAirplaneMode(enable);
3290 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003291 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003292 }
3293 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003294
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003295 /**
3296 * Registers the specified {@link NetworkProvider}.
3297 * Each listener must only be registered once. The listener can be unregistered with
3298 * {@link #unregisterNetworkProvider}.
3299 *
3300 * @param provider the provider to register
3301 * @return the ID of the provider. This ID must be used by the provider when registering
3302 * {@link android.net.NetworkAgent}s.
3303 * @hide
3304 */
3305 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003306 @RequiresPermission(anyOf = {
3307 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3308 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003309 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3310 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003311 throw new IllegalStateException("NetworkProviders can only be registered once");
3312 }
3313
3314 try {
3315 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3316 provider.getName());
3317 provider.setProviderId(providerId);
3318 } catch (RemoteException e) {
3319 throw e.rethrowFromSystemServer();
3320 }
3321 return provider.getProviderId();
3322 }
3323
3324 /**
3325 * Unregisters the specified NetworkProvider.
3326 *
3327 * @param provider the provider to unregister
3328 * @hide
3329 */
3330 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003331 @RequiresPermission(anyOf = {
3332 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3333 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003334 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3335 try {
3336 mService.unregisterNetworkProvider(provider.getMessenger());
3337 } catch (RemoteException e) {
3338 throw e.rethrowFromSystemServer();
3339 }
3340 provider.setProviderId(NetworkProvider.ID_NONE);
3341 }
3342
3343
3344 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003345 @RequiresPermission(anyOf = {
3346 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3347 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003348 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3349 try {
3350 mService.declareNetworkRequestUnfulfillable(request);
3351 } catch (RemoteException e) {
3352 throw e.rethrowFromSystemServer();
3353 }
3354 }
3355
Paul Jensen1f567382015-02-13 14:18:39 -05003356 /**
3357 * @hide
3358 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003359 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003360 */
paulhub6ba8e82020-03-04 09:43:41 +08003361 @RequiresPermission(anyOf = {
3362 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3363 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003364 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jean28018572020-12-21 18:36:52 +09003365 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3366 int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003367 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003368 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003369 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003370 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003371 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003372 }
3373
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003374 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003375 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3376 * changes. Should be extended by applications wanting notifications.
3377 *
3378 * A {@code NetworkCallback} is registered by calling
3379 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3380 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003381 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003382 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3383 * A {@code NetworkCallback} should be registered at most once at any time.
3384 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003385 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003386 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003387 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003388 * No flags associated with this callback.
3389 * @hide
3390 */
3391 public static final int FLAG_NONE = 0;
3392 /**
3393 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3394 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3395 * <p>
3396 * These include:
3397 * <li> Some transport info instances (retrieved via
3398 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3399 * contain location sensitive information.
3400 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3401 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3402 * </p>
3403 * <p>
3404 * Note:
3405 * <li> Retrieving this location sensitive information (subject to app's location
3406 * permissions) will be noted by system. </li>
3407 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3408 * not include location sensitive info.
3409 * </p>
3410 */
3411 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3412
3413 /** @hide */
3414 @Retention(RetentionPolicy.SOURCE)
3415 @IntDef(flag = true, prefix = "FLAG_", value = {
3416 FLAG_NONE,
3417 FLAG_INCLUDE_LOCATION_INFO
3418 })
3419 public @interface Flag { }
3420
3421 /**
3422 * All the valid flags for error checking.
3423 */
3424 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3425
3426 public NetworkCallback() {
3427 this(FLAG_NONE);
3428 }
3429
3430 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003431 if ((flags & VALID_FLAGS) != flags) {
3432 throw new IllegalArgumentException("Invalid flags");
3433 }
Roshan Pius951c0032020-12-22 15:10:42 -08003434 mFlags = flags;
3435 }
3436
3437 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003438 * Called when the framework connects to a new network to evaluate whether it satisfies this
3439 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3440 * callback. There is no guarantee that this new network will satisfy any requests, or that
3441 * the network will stay connected for longer than the time necessary to evaluate it.
3442 * <p>
3443 * Most applications <b>should not</b> act on this callback, and should instead use
3444 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3445 * the framework in properly evaluating the network &mdash; for example, an application that
3446 * can automatically log in to a captive portal without user intervention.
3447 *
3448 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003449 *
3450 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003451 */
paulhu1a407652019-03-22 16:35:06 +08003452 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003453
3454 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003455 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003456 * This callback may be called more than once if the {@link Network} that is
3457 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003458 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003459 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003460 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3461 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003462 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003463 * @hide
3464 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003465 public final void onAvailable(@NonNull Network network,
paulhu1a407652019-03-22 16:35:06 +08003466 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003467 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003468 // Internally only this method is called when a new network is available, and
3469 // it calls the callback in the same way and order that older versions used
3470 // to call so as not to change the behavior.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003471 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3472 onBlockedStatusChanged(network, blocked);
3473 }
3474
3475 /**
3476 * Legacy variant of onAvailable that takes a boolean blocked reason.
3477 *
3478 * This method has never been public API, but it's not final, so there may be apps that
3479 * implemented it and rely on it being called. Do our best not to break them.
3480 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3481 * this method is called. There does not seem to be a way to avoid this.
3482 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3483 *
3484 * @hide
3485 */
3486 public void onAvailable(@NonNull Network network,
3487 @NonNull NetworkCapabilities networkCapabilities,
3488 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003489 onAvailable(network);
3490 if (!networkCapabilities.hasCapability(
3491 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3492 onNetworkSuspended(network);
3493 }
3494 onCapabilitiesChanged(network, networkCapabilities);
3495 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003496 // No call to onBlockedStatusChanged here. That is done by the caller.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003497 }
3498
3499 /**
3500 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003501 *
3502 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3503 * be available at the same time, and onAvailable will be called for each of these as they
3504 * appear.
3505 *
3506 * <p>For callbacks registered with {@link #requestNetwork} and
3507 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3508 * is the new best network for this request and is now tracked by this callback ; this
3509 * callback will no longer receive method calls about other networks that may have been
3510 * passed to this method previously. The previously-best network may have disconnected, or
3511 * it may still be around and the newly-best network may simply be better.
3512 *
3513 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3514 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3515 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3516 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3517 *
3518 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3519 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3520 * this callback as this is prone to race conditions (there is no guarantee the objects
3521 * returned by these methods will be current). Instead, wait for a call to
3522 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3523 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3524 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003525 *
3526 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003527 */
paulhu1a407652019-03-22 16:35:06 +08003528 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003529
3530 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003531 * Called when the network is about to be lost, typically because there are no outstanding
3532 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3533 * with the new replacement network for graceful handover. This method is not guaranteed
3534 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3535 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003536 *
Chalard Jean01378b62019-08-30 16:27:28 +09003537 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3538 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3539 * this callback as this is prone to race conditions ; calling these methods while in a
3540 * callback may return an outdated or even a null object.
3541 *
3542 * @param network The {@link Network} that is about to be lost.
3543 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3544 * connected for graceful handover; note that the network may still
3545 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003546 */
paulhu1a407652019-03-22 16:35:06 +08003547 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003548
3549 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003550 * Called when a network disconnects or otherwise no longer satisfies this request or
3551 * callback.
3552 *
3553 * <p>If the callback was registered with requestNetwork() or
3554 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3555 * returned by onAvailable() when that network is lost and no other network satisfies
3556 * the criteria of the request.
3557 *
3558 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3559 * each network which no longer satisfies the criteria of the callback.
3560 *
3561 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3562 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3563 * this callback as this is prone to race conditions ; calling these methods while in a
3564 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003565 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003566 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003567 */
paulhu1a407652019-03-22 16:35:06 +08003568 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003569
3570 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003571 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003572 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3573 * requested network request cannot be fulfilled (whether or not a timeout was
3574 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003575 * {@link NetworkRequest} will have already been removed and released, as if
3576 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003577 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003578 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003579
3580 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003581 * Called when the network corresponding to this request changes capabilities but still
3582 * satisfies the requested criteria.
3583 *
3584 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3585 * to be called immediately after {@link #onAvailable}.
3586 *
3587 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3588 * ConnectivityManager methods in this callback as this is prone to race conditions :
3589 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003590 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003591 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius951c0032020-12-22 15:10:42 -08003592 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003593 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003594 */
paulhu1a407652019-03-22 16:35:06 +08003595 public void onCapabilitiesChanged(@NonNull Network network,
3596 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003597
3598 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003599 * Called when the network corresponding to this request changes {@link LinkProperties}.
3600 *
3601 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3602 * to be called immediately after {@link #onAvailable}.
3603 *
3604 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3605 * ConnectivityManager methods in this callback as this is prone to race conditions :
3606 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003607 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003608 * @param network The {@link Network} whose link properties have changed.
3609 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003610 */
paulhu1a407652019-03-22 16:35:06 +08003611 public void onLinkPropertiesChanged(@NonNull Network network,
3612 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003613
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003614 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003615 * Called when the network the framework connected to for this request suspends data
3616 * transmission temporarily.
3617 *
3618 * <p>This generally means that while the TCP connections are still live temporarily
3619 * network data fails to transfer. To give a specific example, this is used on cellular
3620 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3621 * means read operations on sockets on this network will block once the buffers are
3622 * drained, and write operations will block once the buffers are full.
3623 *
3624 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3625 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3626 * this callback as this is prone to race conditions (there is no guarantee the objects
3627 * returned by these methods will be current).
3628 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003629 * @hide
3630 */
paulhu1a407652019-03-22 16:35:06 +08003631 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003632
3633 /**
3634 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003635 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3636 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003637
3638 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3639 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3640 * this callback as this is prone to race conditions : calling these methods while in a
3641 * callback may return an outdated or even a null object.
3642 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003643 * @hide
3644 */
paulhu1a407652019-03-22 16:35:06 +08003645 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003646
junyulaif2c67e42018-08-07 19:50:45 +08003647 /**
3648 * Called when access to the specified network is blocked or unblocked.
3649 *
Chalard Jean01378b62019-08-30 16:27:28 +09003650 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3651 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3652 * this callback as this is prone to race conditions : calling these methods while in a
3653 * callback may return an outdated or even a null object.
3654 *
junyulaif2c67e42018-08-07 19:50:45 +08003655 * @param network The {@link Network} whose blocked status has changed.
3656 * @param blocked The blocked status of this {@link Network}.
3657 */
junyulai7e06ad42019-03-04 22:45:36 +08003658 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003659
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003660 /**
3661 * Called when access to the specified network is blocked or unblocked.
3662 *
3663 * If a NetworkCallback object implements this method,
3664 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3665 *
3666 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3667 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3668 * this callback as this is prone to race conditions : calling these methods while in a
3669 * callback may return an outdated or even a null object.
3670 *
3671 * @param network The {@link Network} whose blocked status has changed.
3672 * @param blocked The blocked status of this {@link Network}.
3673 * @hide
3674 */
3675 @SystemApi(client = MODULE_LIBRARIES)
3676 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3677 onBlockedStatusChanged(network, blocked != 0);
3678 }
3679
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003680 private NetworkRequest networkRequest;
Roshan Pius951c0032020-12-22 15:10:42 -08003681 private final int mFlags;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003682 }
3683
Hugo Benichia590ab82017-05-11 13:16:17 +09003684 /**
3685 * Constant error codes used by ConnectivityService to communicate about failures and errors
3686 * across a Binder boundary.
3687 * @hide
3688 */
3689 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003690 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003691 }
3692
3693 /** @hide */
3694 public static class TooManyRequestsException extends RuntimeException {}
3695
3696 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3697 switch (e.errorCode) {
3698 case Errors.TOO_MANY_REQUESTS:
3699 return new TooManyRequestsException();
3700 default:
3701 Log.w(TAG, "Unknown service error code " + e.errorCode);
3702 return new RuntimeException(e);
3703 }
3704 }
3705
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003706 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003707 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003708 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003709 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003710 /** @hide arg1 = TTL */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003711 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003712 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003713 public static final int CALLBACK_LOST = 4;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003714 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003715 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003716 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003717 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003718 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003719 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003720 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003721 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003722 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003723 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003724 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003725 public static final int CALLBACK_RESUMED = 10;
junyulaif2c67e42018-08-07 19:50:45 +08003726 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003727 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003728
Erik Kline155a59a2015-11-25 12:49:38 +09003729 /** @hide */
3730 public static String getCallbackName(int whichCallback) {
3731 switch (whichCallback) {
3732 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3733 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3734 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3735 case CALLBACK_LOST: return "CALLBACK_LOST";
3736 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3737 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3738 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003739 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3740 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3741 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003742 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003743 default:
3744 return Integer.toString(whichCallback);
3745 }
3746 }
3747
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003748 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003749 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003750 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003751
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003752 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003753 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003754 }
3755
Hugo Benichifd44e912017-02-02 17:02:36 +09003756 CallbackHandler(Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003757 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003758 }
3759
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003760 @Override
3761 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003762 if (message.what == EXPIRE_LEGACY_REQUEST) {
3763 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3764 return;
3765 }
3766
3767 final NetworkRequest request = getObject(message, NetworkRequest.class);
3768 final Network network = getObject(message, Network.class);
3769 final NetworkCallback callback;
3770 synchronized (sCallbacks) {
3771 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003772 if (callback == null) {
3773 Log.w(TAG,
3774 "callback not found for " + getCallbackName(message.what) + " message");
3775 return;
3776 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003777 if (message.what == CALLBACK_UNAVAIL) {
3778 sCallbacks.remove(request);
3779 callback.networkRequest = ALREADY_UNREGISTERED;
3780 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003781 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003782 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003783 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003784 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003785
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003786 switch (message.what) {
3787 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003788 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003789 break;
3790 }
3791 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003792 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3793 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003794 callback.onAvailable(network, cap, lp, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003795 break;
3796 }
3797 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003798 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003799 break;
3800 }
3801 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003802 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003803 break;
3804 }
3805 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003806 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003807 break;
3808 }
3809 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003810 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3811 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003812 break;
3813 }
3814 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003815 LinkProperties lp = getObject(message, LinkProperties.class);
3816 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003817 break;
3818 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003819 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003820 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003821 break;
3822 }
3823 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003824 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003825 break;
3826 }
junyulaif2c67e42018-08-07 19:50:45 +08003827 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003828 callback.onBlockedStatusChanged(network, message.arg1);
junyulaif2c67e42018-08-07 19:50:45 +08003829 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003830 }
3831 }
3832
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003833 private <T> T getObject(Message msg, Class<T> c) {
3834 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003835 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003836 }
3837
Hugo Benichifd44e912017-02-02 17:02:36 +09003838 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003839 synchronized (sCallbacks) {
3840 if (sCallbackHandler == null) {
3841 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003842 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003843 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003844 }
3845 }
3846
Hugo Benichibc4ac972017-02-03 14:18:44 +09003847 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3848 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003849
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003850 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3851 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3852 CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003853 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003854 checkCallbackNotNull(callback);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003855 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3856 throw new IllegalArgumentException("null NetworkCapabilities");
3857 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003858 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003859 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003860 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003861 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003862 if (callback.networkRequest != null
3863 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003864 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3865 // and requests (http://b/20701525).
3866 Log.e(TAG, "NetworkCallback was already registered");
3867 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003868 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003869 Binder binder = new Binder();
Roshan Pius951c0032020-12-22 15:10:42 -08003870 final int callbackFlags = callback.mFlags;
junyulaiad010792021-01-11 16:53:38 +08003871 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003872 request = mService.listenForNetwork(
Roshan Pius951c0032020-12-22 15:10:42 -08003873 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003874 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003875 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003876 request = mService.requestNetwork(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003877 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3878 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003879 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003880 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003881 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003882 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003883 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003884 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003885 } catch (RemoteException e) {
3886 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003887 } catch (ServiceSpecificException e) {
3888 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003889 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003890 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003891 }
3892
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003893 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3894 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3895 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3896 legacyType, handler);
3897 }
3898
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003899 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003900 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003901 *
markchienfac84a22020-03-18 21:16:15 +08003902 * This API is only for use in internal system code that requests networks with legacy type and
3903 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003904 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003905 *
markchiend6eeffd2020-01-14 00:55:21 +08003906 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +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).
3910 * @param legacyType to specify the network type(#TYPE_*).
3911 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003912 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3913 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003914 *
3915 * @hide
3916 */
markchiend6eeffd2020-01-14 00:55:21 +08003917 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003918 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003919 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003920 int timeoutMs, int legacyType, @NonNull Handler handler,
3921 @NonNull NetworkCallback networkCallback) {
3922 if (legacyType == TYPE_NONE) {
3923 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3924 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003925 CallbackHandler cbHandler = new CallbackHandler(handler);
3926 NetworkCapabilities nc = request.networkCapabilities;
3927 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003928 }
3929
3930 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003931 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003932 *
Chalard Jean01378b62019-08-30 16:27:28 +09003933 * <p>This method will attempt to find the best network that matches the passed
3934 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3935 * criteria. The platform will evaluate which network is the best at its own discretion.
3936 * Throughput, latency, cost per byte, policy, user preference and other considerations
3937 * may be factored in the decision of what is considered the best network.
3938 *
3939 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3940 * matching this request, while always attempting to match the request to a better network if
3941 * possible. If a better match is found, the platform will switch this request to the now-best
3942 * network and inform the app of the newly best network by invoking
3943 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3944 * will not try to maintain any other network than the best one currently matching the request:
3945 * a network not matching any network request may be disconnected at any time.
3946 *
3947 * <p>For example, an application could use this method to obtain a connected cellular network
3948 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3949 * radio to consume additional power. Or, an application could inform the system that it wants
3950 * a network supporting sending MMSes and have the system let it know about the currently best
3951 * MMS-supporting network through the provided {@link NetworkCallback}.
3952 *
3953 * <p>The status of the request can be followed by listening to the various callbacks described
3954 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3955 * used to direct traffic to the network (although accessing some networks may be subject to
3956 * holding specific permissions). Callers will learn about the specific characteristics of the
3957 * network through
3958 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3959 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3960 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3961 * matching the request at any given time; therefore when a better network matching the request
3962 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3963 * with the new network after which no further updates are given about the previously-best
3964 * network, unless it becomes the best again at some later time. All callbacks are invoked
3965 * in order on the same thread, which by default is a thread created by the framework running
3966 * in the app.
3967 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3968 * callbacks are invoked.
3969 *
3970 * <p>This{@link NetworkRequest} will live until released via
3971 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3972 * which point the system may let go of the network at any time.
3973 *
3974 * <p>A version of this method which takes a timeout is
3975 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3976 * wait for a limited amount of time for the network to become unavailable.
3977 *
Paul Jensenee52d232015-06-16 15:11:58 -04003978 * <p>It is presently unsupported to request a network with mutable
3979 * {@link NetworkCapabilities} such as
3980 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3981 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3982 * as these {@code NetworkCapabilities} represent states that a particular
3983 * network may never attain, and whether a network will attain these states
3984 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003985 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003986 *
3987 * <p>This method requires the caller to hold either the
3988 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3989 * or the ability to modify system settings as determined by
3990 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003991 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003992 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3993 * number of outstanding requests to 100 per app (identified by their UID), shared with
3994 * all variants of this method, of {@link #registerNetworkCallback} as well as
3995 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3996 * Requesting a network with this method will count toward this limit. If this limit is
3997 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3998 * make sure to unregister the callbacks with
3999 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4000 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004001 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09004002 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4003 * the callback must not be shared - it uniquely specifies this request.
4004 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09004005 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4006 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004007 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004008 */
Chalard Jean158702d2019-01-07 19:26:34 +09004009 public void requestNetwork(@NonNull NetworkRequest request,
4010 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004011 requestNetwork(request, networkCallback, getDefaultHandler());
4012 }
4013
4014 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004015 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichifd44e912017-02-02 17:02:36 +09004016 *
Chalard Jean01378b62019-08-30 16:27:28 +09004017 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4018 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09004019 *
Chalard Jean01378b62019-08-30 16:27:28 +09004020 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004021 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4022 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09004023 *
4024 * @param request {@link NetworkRequest} describing this request.
4025 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4026 * the callback must not be shared - it uniquely specifies this request.
4027 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09004028 */
Chalard Jean158702d2019-01-07 19:26:34 +09004029 public void requestNetwork(@NonNull NetworkRequest request,
4030 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004031 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08004032 NetworkCapabilities nc = request.networkCapabilities;
4033 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004034 }
4035
4036 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004037 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohenf67bde92017-03-01 12:47:28 -08004038 * by a timeout.
4039 *
4040 * This function behaves identically to the non-timed-out version
4041 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4042 * is not found within the given time (in milliseconds) the
4043 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4044 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4045 * not have to be released if timed-out (it is automatically released). Unregistering a
4046 * request that timed out is not an error.
4047 *
4048 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4049 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4050 * for that purpose. Calling this method will attempt to bring up the requested network.
4051 *
Chalard Jean01378b62019-08-30 16:27:28 +09004052 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004053 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4054 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08004055 *
4056 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004057 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4058 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08004059 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4060 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4061 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08004062 */
Chalard Jean158702d2019-01-07 19:26:34 +09004063 public void requestNetwork(@NonNull NetworkRequest request,
4064 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09004065 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08004066 NetworkCapabilities nc = request.networkCapabilities;
4067 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4068 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09004069 }
4070
Hugo Benichifd44e912017-02-02 17:02:36 +09004071 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004072 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichifd44e912017-02-02 17:02:36 +09004073 * by a timeout.
4074 *
Chalard Jean01378b62019-08-30 16:27:28 +09004075 * This method behaves identically to
4076 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4077 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08004078 *
Chalard Jean01378b62019-08-30 16:27:28 +09004079 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004080 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4081 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09004082 *
4083 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08004084 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4085 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09004086 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004087 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4088 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004089 */
Chalard Jean158702d2019-01-07 19:26:34 +09004090 public void requestNetwork(@NonNull NetworkRequest request,
4091 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09004092 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09004093 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08004094 NetworkCapabilities nc = request.networkCapabilities;
4095 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004096 }
4097
4098 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004099 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004100 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004101 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08004102 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04004103 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4104 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004105 */
Erik Kline8a826212014-11-19 12:12:24 +09004106 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004107
4108 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004109 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004110 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004111 * {@link android.content.Intent#getParcelableExtra(String)}.
4112 */
Erik Kline8a826212014-11-19 12:12:24 +09004113 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004114
4115
4116 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004117 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004118 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004119 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004120 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004121 * the request may outlive the calling application and get called back when a suitable
4122 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004123 * <p>
4124 * The operation is an Intent broadcast that goes to a broadcast receiver that
4125 * you registered with {@link Context#registerReceiver} or through the
4126 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4127 * <p>
4128 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09004129 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4130 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004131 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004132 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004133 * Intent to reserve the network or it will be released shortly after the Intent
4134 * is processed.
4135 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04004136 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004137 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004138 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004139 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004140 * The request may be released normally by calling
4141 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04004142 * <p>It is presently unsupported to request a network with either
4143 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4144 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4145 * as these {@code NetworkCapabilities} represent states that a particular
4146 * network may never attain, and whether a network will attain these states
4147 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09004148 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004149 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004150 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4151 * number of outstanding requests to 100 per app (identified by their UID), shared with
4152 * all variants of this method, of {@link #registerNetworkCallback} as well as
4153 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4154 * Requesting a network with this method will count toward this limit. If this limit is
4155 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4156 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4157 * or {@link #releaseNetworkRequest(PendingIntent)}.
4158 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004159 * <p>This method requires the caller to hold either the
4160 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4161 * or the ability to modify system settings as determined by
4162 * {@link android.provider.Settings.System#canWrite}.</p>
4163 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004164 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004165 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004166 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004167 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004168 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4169 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004170 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004171 */
Chalard Jean158702d2019-01-07 19:26:34 +09004172 public void requestNetwork(@NonNull NetworkRequest request,
4173 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004174 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004175 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004176 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004177 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004178 request.networkCapabilities, operation, mContext.getOpPackageName(),
4179 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004180 } catch (RemoteException e) {
4181 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004182 } catch (ServiceSpecificException e) {
4183 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004184 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004185 }
4186
4187 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004188 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4189 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004190 * This method has the same behavior as
4191 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004192 * releasing network resources and disconnecting.
4193 *
4194 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4195 * PendingIntent passed to
4196 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4197 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4198 */
Chalard Jean158702d2019-01-07 19:26:34 +09004199 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004200 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004201 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004202 try {
4203 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004204 } catch (RemoteException e) {
4205 throw e.rethrowFromSystemServer();
4206 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004207 }
4208
Hugo Benichibc1104b2017-05-09 15:19:01 +09004209 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004210 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004211 }
4212
4213 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004214 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004215 }
4216
4217 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004218 if (timeoutMs <= 0) {
4219 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4220 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004221 }
4222
4223 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004224 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004225 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004226 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4227 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004228 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004229 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4230 * number of outstanding requests to 100 per app (identified by their UID), shared with
4231 * all variants of this method, of {@link #requestNetwork} as well as
4232 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4233 * Requesting a network with this method will count toward this limit. If this limit is
4234 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4235 * make sure to unregister the callbacks with
4236 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4237 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004238 * @param request {@link NetworkRequest} describing this request.
4239 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4240 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004241 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004242 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004243 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004244 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004245 public void registerNetworkCallback(@NonNull NetworkRequest request,
4246 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004247 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4248 }
4249
4250 /**
4251 * Registers to receive notifications about all networks which satisfy the given
4252 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004253 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4254 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004255 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004256 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4257 * number of outstanding requests to 100 per app (identified by their UID), shared with
4258 * all variants of this method, of {@link #requestNetwork} as well as
4259 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4260 * Requesting a network with this method will count toward this limit. If this limit is
4261 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4262 * make sure to unregister the callbacks with
4263 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4264 *
4265 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004266 * @param request {@link NetworkRequest} describing this request.
4267 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4268 * networks change state.
4269 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004270 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004271 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004272 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004273 public void registerNetworkCallback(@NonNull NetworkRequest request,
4274 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004275 CallbackHandler cbHandler = new CallbackHandler(handler);
4276 NetworkCapabilities nc = request.networkCapabilities;
4277 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004278 }
4279
4280 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004281 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4282 * {@link NetworkRequest}.
4283 *
4284 * This function behaves identically to the version that takes a NetworkCallback, but instead
4285 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4286 * the request may outlive the calling application and get called back when a suitable
4287 * network is found.
4288 * <p>
4289 * The operation is an Intent broadcast that goes to a broadcast receiver that
4290 * you registered with {@link Context#registerReceiver} or through the
4291 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4292 * <p>
4293 * The operation Intent is delivered with two extras, a {@link Network} typed
4294 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4295 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4296 * the original requests parameters.
4297 * <p>
4298 * If there is already a request for this Intent registered (with the equality of
4299 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4300 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4301 * <p>
4302 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004303 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004304 *
4305 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4306 * number of outstanding requests to 100 per app (identified by their UID), shared with
4307 * all variants of this method, of {@link #requestNetwork} as well as
4308 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4309 * Requesting a network with this method will count toward this limit. If this limit is
4310 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4311 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4312 * or {@link #releaseNetworkRequest(PendingIntent)}.
4313 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004314 * @param request {@link NetworkRequest} describing this request.
4315 * @param operation Action to perform when the network is available (corresponds
4316 * to the {@link NetworkCallback#onAvailable} call. Typically
4317 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004318 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004319 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004320 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004321 public void registerNetworkCallback(@NonNull NetworkRequest request,
4322 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004323 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004324 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004325 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004326 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004327 request.networkCapabilities, operation, mContext.getOpPackageName(),
4328 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004329 } catch (RemoteException e) {
4330 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004331 } catch (ServiceSpecificException e) {
4332 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004333 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004334 }
4335
4336 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004337 * Registers to receive notifications about changes in the application's default network. This
4338 * may be a physical network or a virtual network, such as a VPN that applies to the
4339 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004340 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004341 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004342 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4343 * number of outstanding requests to 100 per app (identified by their UID), shared with
4344 * all variants of this method, of {@link #requestNetwork} as well as
4345 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4346 * Requesting a network with this method will count toward this limit. If this limit is
4347 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4348 * make sure to unregister the callbacks with
4349 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4350 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004351 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004352 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004353 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004354 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004355 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004356 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004357 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004358 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4359 }
4360
4361 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004362 * Registers to receive notifications about changes in the application's default network. This
4363 * may be a physical network or a virtual network, such as a VPN that applies to the
4364 * application. The callbacks will continue to be called until either the application exits or
4365 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4366 *
4367 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4368 * number of outstanding requests to 100 per app (identified by their UID), shared with
4369 * all variants of this method, of {@link #requestNetwork} as well as
4370 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4371 * Requesting a network with this method will count toward this limit. If this limit is
4372 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4373 * make sure to unregister the callbacks with
4374 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4375 *
4376 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4377 * application's default network changes.
4378 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4379 * @throws RuntimeException if the app already has too many callbacks registered.
4380 */
4381 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4382 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4383 @NonNull Handler handler) {
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004384 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4385 }
4386
4387 /**
4388 * Registers to receive notifications about changes in the default network for the specified
4389 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4390 * UID. The callbacks will continue to be called until either the application exits or
4391 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4392 *
4393 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4394 * number of outstanding requests to 100 per app (identified by their UID), shared with
4395 * all variants of this method, of {@link #requestNetwork} as well as
4396 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4397 * Requesting a network with this method will count toward this limit. If this limit is
4398 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4399 * make sure to unregister the callbacks with
4400 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4401 *
4402 * @param uid the UID for which to track default network changes.
4403 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4404 * UID's default network changes.
4405 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4406 * @throws RuntimeException if the app already has too many callbacks registered.
4407 * @hide
4408 */
Lorenzo Colitti92ed8b92021-03-22 18:23:21 +09004409 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004410 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4411 @RequiresPermission(anyOf = {
4412 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4413 android.Manifest.permission.NETWORK_SETTINGS})
4414 public void registerDefaultNetworkCallbackAsUid(int uid,
4415 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004416 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004417 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004418 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4419 }
4420
4421 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004422 * Registers to receive notifications about changes in the system default network. The callbacks
4423 * will continue to be called until either the application exits or
4424 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004425 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004426 * This method should not be used to determine networking state seen by applications, because in
4427 * many cases, most or even all application traffic may not use the default network directly,
4428 * and traffic from different applications may go on different networks by default. As an
4429 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4430 * and not onto the system default network. Applications or system components desiring to do
4431 * determine network state as seen by applications should use other methods such as
4432 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4433 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004434 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4435 * number of outstanding requests to 100 per app (identified by their UID), shared with
4436 * all variants of this method, of {@link #requestNetwork} as well as
4437 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4438 * Requesting a network with this method will count toward this limit. If this limit is
4439 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4440 * make sure to unregister the callbacks with
4441 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4442 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004443 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4444 * system default network changes.
4445 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004446 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004447 *
4448 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004449 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004450 @SystemApi(client = MODULE_LIBRARIES)
4451 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4452 @RequiresPermission(anyOf = {
4453 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4454 android.Manifest.permission.NETWORK_SETTINGS})
4455 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004456 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004457 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004458 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004459 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004460 }
4461
4462 /**
junyulai8eb13a22021-03-15 11:48:48 +08004463 * Registers to receive notifications about the best matching network which satisfy the given
4464 * {@link NetworkRequest}. The callbacks will continue to be called until
4465 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4466 * called.
4467 *
4468 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4469 * number of outstanding requests to 100 per app (identified by their UID), shared with
4470 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4471 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4472 * Requesting a network with this method will count toward this limit. If this limit is
4473 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4474 * make sure to unregister the callbacks with
4475 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4476 *
4477 *
4478 * @param request {@link NetworkRequest} describing this request.
4479 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4480 * networks change state.
4481 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4482 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai7514e312021-03-05 15:51:17 +08004483 */
junyulai7514e312021-03-05 15:51:17 +08004484 @SuppressLint("ExecutorRegistration")
4485 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4486 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4487 final NetworkCapabilities nc = request.networkCapabilities;
4488 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai1b1c8742021-03-12 20:05:08 +08004489 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai7514e312021-03-05 15:51:17 +08004490 }
4491
4492 /**
fenglub00f4882015-04-21 17:12:05 -07004493 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4494 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4495 * network connection for updated bandwidth information. The caller will be notified via
4496 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004497 * method assumes that the caller has previously called
4498 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4499 * changes.
fenglu3f357402015-03-20 11:29:56 -07004500 *
fengluea2d9282015-04-27 14:28:04 -07004501 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004502 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004503 */
Chalard Jean158702d2019-01-07 19:26:34 +09004504 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004505 try {
fenglub00f4882015-04-21 17:12:05 -07004506 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004507 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004508 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004509 }
4510 }
4511
4512 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004513 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004514 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4515 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4516 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004517 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4518 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004519 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004520 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4521 * triggering it as soon as this call returns.
4522 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004523 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004524 */
Chalard Jean158702d2019-01-07 19:26:34 +09004525 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004526 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004527 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004528 final List<NetworkRequest> reqs = new ArrayList<>();
4529 // Find all requests associated to this callback and stop callback triggers immediately.
4530 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4531 synchronized (sCallbacks) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004532 if (networkCallback.networkRequest == null) {
4533 throw new IllegalArgumentException("NetworkCallback was not registered");
4534 }
Etan Cohen6cb65992019-04-16 15:07:55 -07004535 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4536 Log.d(TAG, "NetworkCallback was already unregistered");
4537 return;
4538 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004539 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4540 if (e.getValue() == networkCallback) {
4541 reqs.add(e.getKey());
4542 }
4543 }
4544 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4545 for (NetworkRequest r : reqs) {
4546 try {
4547 mService.releaseNetworkRequest(r);
4548 } catch (RemoteException e) {
4549 throw e.rethrowFromSystemServer();
4550 }
4551 // Only remove mapping if rpc was successful.
4552 sCallbacks.remove(r);
4553 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004554 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004555 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004556 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004557
4558 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004559 * Unregisters a callback previously registered via
4560 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4561 *
4562 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4563 * PendingIntent passed to
4564 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4565 * Cannot be null.
4566 */
Chalard Jean158702d2019-01-07 19:26:34 +09004567 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004568 releaseNetworkRequest(operation);
4569 }
4570
4571 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004572 * Informs the system whether it should switch to {@code network} regardless of whether it is
4573 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4574 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4575 * the system default network regardless of any other network that's currently connected. If
4576 * {@code always} is true, then the choice is remembered, so that the next time the user
4577 * connects to this network, the system will switch to it.
4578 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004579 * @param network The network to accept.
4580 * @param accept Whether to accept the network even if unvalidated.
4581 * @param always Whether to remember this choice in the future.
4582 *
4583 * @hide
4584 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004585 @SystemApi(client = MODULE_LIBRARIES)
4586 @RequiresPermission(anyOf = {
4587 android.Manifest.permission.NETWORK_SETTINGS,
4588 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4589 android.Manifest.permission.NETWORK_STACK,
4590 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4591 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004592 try {
4593 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004594 } catch (RemoteException e) {
4595 throw e.rethrowFromSystemServer();
4596 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004597 }
4598
4599 /**
lucaslin2240ef62019-03-12 13:08:03 +08004600 * Informs the system whether it should consider the network as validated even if it only has
4601 * partial connectivity. If {@code accept} is true, then the network will be considered as
4602 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4603 * is remembered, so that the next time the user connects to this network, the system will
4604 * switch to it.
4605 *
4606 * @param network The network to accept.
4607 * @param accept Whether to consider the network as validated even if it has partial
4608 * connectivity.
4609 * @param always Whether to remember this choice in the future.
4610 *
4611 * @hide
4612 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004613 @SystemApi(client = MODULE_LIBRARIES)
4614 @RequiresPermission(anyOf = {
4615 android.Manifest.permission.NETWORK_SETTINGS,
4616 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4617 android.Manifest.permission.NETWORK_STACK,
4618 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4619 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4620 boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004621 try {
4622 mService.setAcceptPartialConnectivity(network, accept, always);
4623 } catch (RemoteException e) {
4624 throw e.rethrowFromSystemServer();
4625 }
4626 }
4627
4628 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004629 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4630 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4631 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4632 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4633 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004634 * @param network The network to accept.
4635 *
4636 * @hide
4637 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004638 @SystemApi(client = MODULE_LIBRARIES)
4639 @RequiresPermission(anyOf = {
4640 android.Manifest.permission.NETWORK_SETTINGS,
4641 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4642 android.Manifest.permission.NETWORK_STACK,
4643 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4644 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004645 try {
4646 mService.setAvoidUnvalidated(network);
4647 } catch (RemoteException e) {
4648 throw e.rethrowFromSystemServer();
4649 }
4650 }
4651
4652 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004653 * Requests that the system open the captive portal app on the specified network.
4654 *
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004655 * <p>This is to be used on networks where a captive portal was detected, as per
4656 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4657 *
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004658 * @param network The network to log into.
4659 *
4660 * @hide
4661 */
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004662 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4663 @RequiresPermission(anyOf = {
4664 android.Manifest.permission.NETWORK_SETTINGS,
4665 android.Manifest.permission.NETWORK_STACK,
4666 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4667 })
4668 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004669 try {
4670 mService.startCaptivePortalApp(network);
4671 } catch (RemoteException e) {
4672 throw e.rethrowFromSystemServer();
4673 }
4674 }
4675
4676 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004677 * Requests that the system open the captive portal app with the specified extras.
4678 *
4679 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4680 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004681 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004682 * @param appExtras Extras to include in the app start intent.
4683 * @hide
4684 */
4685 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004686 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004687 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004688 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004689 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004690 } catch (RemoteException e) {
4691 throw e.rethrowFromSystemServer();
4692 }
4693 }
4694
4695 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004696 * Determine whether the device is configured to avoid bad wifi.
4697 * @hide
4698 */
4699 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004700 @RequiresPermission(anyOf = {
4701 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4702 android.Manifest.permission.NETWORK_STACK})
4703 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004704 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004705 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004706 } catch (RemoteException e) {
4707 throw e.rethrowFromSystemServer();
4708 }
4709 }
4710
4711 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004712 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4713 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004714 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4715 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004716 *
4717 * An example of such an operation might be a time-sensitive foreground activity, such as a
4718 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4719 */
4720 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4721
4722 /**
4723 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4724 * a backup channel for traffic that is primarily going over another network.
4725 *
4726 * An example might be maintaining backup connections to peers or servers for the purpose of
4727 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4728 * on backup paths should be negligible compared to the traffic on the main path.
4729 */
4730 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4731
4732 /**
4733 * It is acceptable to use metered data to improve network latency and performance.
4734 */
4735 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4736
4737 /**
4738 * Return value to use for unmetered networks. On such networks we currently set all the flags
4739 * to true.
4740 * @hide
4741 */
4742 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4743 MULTIPATH_PREFERENCE_HANDOVER |
4744 MULTIPATH_PREFERENCE_RELIABILITY |
4745 MULTIPATH_PREFERENCE_PERFORMANCE;
4746
4747 /** @hide */
4748 @Retention(RetentionPolicy.SOURCE)
4749 @IntDef(flag = true, value = {
4750 MULTIPATH_PREFERENCE_HANDOVER,
4751 MULTIPATH_PREFERENCE_RELIABILITY,
4752 MULTIPATH_PREFERENCE_PERFORMANCE,
4753 })
4754 public @interface MultipathPreference {
4755 }
4756
4757 /**
4758 * Provides a hint to the calling application on whether it is desirable to use the
4759 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4760 * for multipath data transfer on this network when it is not the system default network.
4761 * Applications desiring to use multipath network protocols should call this method before
4762 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004763 *
4764 * @param network The network on which the application desires to use multipath data.
4765 * If {@code null}, this method will return the a preference that will generally
4766 * apply to metered networks.
4767 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4768 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004769 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004770 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004771 try {
4772 return mService.getMultipathPreference(network);
4773 } catch (RemoteException e) {
4774 throw e.rethrowFromSystemServer();
4775 }
4776 }
4777
4778 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004779 * Resets all connectivity manager settings back to factory defaults.
4780 * @hide
4781 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004782 @SystemApi(client = MODULE_LIBRARIES)
4783 @RequiresPermission(anyOf = {
4784 android.Manifest.permission.NETWORK_SETTINGS,
4785 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scott0f835ac2015-03-30 13:17:11 -07004786 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004787 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004788 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004789 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004790 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004791 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004792 }
4793 }
4794
4795 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004796 * Binds the current process to {@code network}. All Sockets created in the future
4797 * (and not explicitly bound via a bound SocketFactory from
4798 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4799 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4800 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4801 * work and all host name resolutions will fail. This is by design so an application doesn't
4802 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4803 * To clear binding pass {@code null} for {@code network}. Using individually bound
4804 * Sockets created by Network.getSocketFactory().createSocket() and
4805 * performing network-specific host name resolutions via
4806 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004807 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004808 *
4809 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4810 * the current binding.
4811 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4812 */
Chalard Jean158702d2019-01-07 19:26:34 +09004813 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004814 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004815 // instantiated.
4816 return setProcessDefaultNetwork(network);
4817 }
4818
4819 /**
4820 * Binds the current process to {@code network}. All Sockets created in the future
4821 * (and not explicitly bound via a bound SocketFactory from
4822 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4823 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4824 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4825 * work and all host name resolutions will fail. This is by design so an application doesn't
4826 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4827 * To clear binding pass {@code null} for {@code network}. Using individually bound
4828 * Sockets created by Network.getSocketFactory().createSocket() and
4829 * performing network-specific host name resolutions via
4830 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4831 * {@code setProcessDefaultNetwork}.
4832 *
4833 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4834 * the current binding.
4835 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4836 * @deprecated This function can throw {@link IllegalStateException}. Use
4837 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4838 * is a direct replacement.
4839 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004840 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004841 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004842 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004843 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4844
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004845 if (netId != NETID_UNSET) {
4846 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004847 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004848
4849 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4850 return false;
4851 }
4852
4853 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004854 // Set HTTP proxy system properties to match network.
4855 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004856 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004857 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004858 } catch (SecurityException e) {
4859 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4860 Log.e(TAG, "Can't set proxy properties", e);
4861 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004862 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANe1b04f62021-03-18 23:27:19 +09004863 InetAddressCompat.clearDnsCache();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004864 // Must flush socket pool as idle sockets will be bound to previous network and may
4865 // cause subsequent fetches to be performed on old network.
4866 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004867 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004868
4869 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004870 }
4871
4872 /**
4873 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004874 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004875 *
4876 * @return {@code Network} to which this process is bound, or {@code null}.
4877 */
Chalard Jean158702d2019-01-07 19:26:34 +09004878 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004879 public Network getBoundNetworkForProcess() {
4880 // Forcing callers to call thru non-static function ensures ConnectivityManager
4881 // instantiated.
4882 return getProcessDefaultNetwork();
4883 }
4884
4885 /**
4886 * Returns the {@link Network} currently bound to this process via
4887 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4888 *
4889 * @return {@code Network} to which this process is bound, or {@code null}.
4890 * @deprecated Using this function can lead to other functions throwing
4891 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4892 * {@code getBoundNetworkForProcess} is a direct replacement.
4893 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004894 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004895 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004896 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004897 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004898 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004899 return new Network(netId);
4900 }
4901
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004902 private void unsupportedStartingFrom(int version) {
4903 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004904 // The getApplicationInfo() call we make below is not supported in system context. Let
4905 // the call through here, and rely on the fact that ConnectivityService will refuse to
4906 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004907 return;
4908 }
4909
4910 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4911 throw new UnsupportedOperationException(
4912 "This method is not supported in target SDK version " + version + " and above");
4913 }
4914 }
4915
4916 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4917 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004918 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004919 // remove these exemptions. Note that this check is not secure, and apps can still access these
4920 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4921 // so is unsupported and may break in the future. http://b/22728205
4922 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004923 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004924 }
4925
Paul Jensen8cdda642014-05-29 10:12:39 -04004926 /**
4927 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004928 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004929 *
4930 * @param network The {@link Network} to bind host resolutions from the current process to, or
4931 * {@code null} to clear the current binding.
4932 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4933 * @hide
4934 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4935 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004936 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004937 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004938 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004939 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004940 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004941 }
Felipe Leme30511352016-01-22 09:44:57 -08004942
4943 /**
4944 * Device is not restricting metered network activity while application is running on
4945 * background.
4946 */
4947 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4948
4949 /**
4950 * Device is restricting metered network activity while application is running on background,
4951 * but application is allowed to bypass it.
4952 * <p>
4953 * In this state, application should take action to mitigate metered network access.
4954 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4955 */
4956 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4957
4958 /**
4959 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004960 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004961 * In this state, application should not try to use the network while running on background,
4962 * because it would be denied.
4963 */
4964 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4965
Felipe Lemed34c9af2016-01-27 14:46:39 -08004966 /**
4967 * A change in the background metered network activity restriction has occurred.
4968 * <p>
4969 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4970 * applies to them.
4971 * <p>
4972 * This is only sent to registered receivers, not manifest receivers.
4973 */
4974 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4975 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4976 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4977
Felipe Leme7e4c1852016-01-25 11:48:04 -08004978 /** @hide */
4979 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004980 @IntDef(flag = false, value = {
4981 RESTRICT_BACKGROUND_STATUS_DISABLED,
4982 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4983 RESTRICT_BACKGROUND_STATUS_ENABLED,
4984 })
Felipe Leme30511352016-01-22 09:44:57 -08004985 public @interface RestrictBackgroundStatus {
4986 }
4987
Felipe Leme30511352016-01-22 09:44:57 -08004988 /**
4989 * Determines if the calling application is subject to metered network restrictions while
4990 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004991 *
4992 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4993 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4994 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004995 */
4996 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4997 try {
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004998 return mService.getRestrictBackgroundStatusByCaller();
Felipe Leme30511352016-01-22 09:44:57 -08004999 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07005000 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08005001 }
5002 }
Ricky Wai7097cc92018-01-23 04:09:45 +00005003
5004 /**
5005 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00005006 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5007 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00005008 *
5009 * @return Hash of network watchlist config file. Null if config does not exist.
5010 */
Chalard Jean158702d2019-01-07 19:26:34 +09005011 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00005012 public byte[] getNetworkWatchlistConfigHash() {
5013 try {
5014 return mService.getNetworkWatchlistConfigHash();
5015 } catch (RemoteException e) {
5016 Log.e(TAG, "Unable to get watchlist config hash");
5017 throw e.rethrowFromSystemServer();
5018 }
5019 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005020
5021 /**
5022 * Returns the {@code uid} of the owner of a network connection.
5023 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08005024 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5025 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005026 * @param local The local {@link InetSocketAddress} of a connection.
5027 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005028 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08005029 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5030 * android.os.Process#INVALID_UID} if the connection is not found.
5031 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5032 * user.
5033 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005034 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08005035 public int getConnectionOwnerUid(
5036 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005037 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5038 try {
5039 return mService.getConnectionOwnerUid(connectionInfo);
5040 } catch (RemoteException e) {
5041 throw e.rethrowFromSystemServer();
5042 }
5043 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09005044
5045 private void printStackTrace() {
5046 if (DEBUG) {
5047 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5048 final StringBuffer sb = new StringBuffer();
5049 for (int i = 3; i < callStack.length; i++) {
5050 final String stackTrace = callStack[i].toString();
5051 if (stackTrace == null || stackTrace.contains("android.os")) {
5052 break;
5053 }
5054 sb.append(" [").append(stackTrace).append("]");
5055 }
5056 Log.d(TAG, "StackLog:" + sb.toString());
5057 }
5058 }
Cody Kestingf53a0752020-04-15 12:33:28 -07005059
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09005060 /** @hide */
5061 public TestNetworkManager startOrGetTestNetworkManager() {
5062 final IBinder tnBinder;
5063 try {
5064 tnBinder = mService.startOrGetTestNetworkService();
5065 } catch (RemoteException e) {
5066 throw e.rethrowFromSystemServer();
5067 }
5068
5069 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5070 }
5071
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09005072 /** @hide */
5073 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5074 return new ConnectivityDiagnosticsManager(mContext, mService);
5075 }
5076
Cody Kestingf53a0752020-04-15 12:33:28 -07005077 /**
5078 * Simulates a Data Stall for the specified Network.
5079 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09005080 * <p>This method should only be used for tests.
5081 *
Cody Kestingf53a0752020-04-15 12:33:28 -07005082 * <p>The caller must be the owner of the specified Network.
5083 *
5084 * @param detectionMethod The detection method used to identify the Data Stall.
5085 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
5086 * @param network The Network for which a Data Stall is being simluated.
5087 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5088 * @throws SecurityException if the caller is not the owner of the given network.
5089 * @hide
5090 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09005091 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07005092 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5093 android.Manifest.permission.NETWORK_STACK})
5094 public void simulateDataStall(int detectionMethod, long timestampMillis,
5095 @NonNull Network network, @NonNull PersistableBundle extras) {
5096 try {
5097 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5098 } catch (RemoteException e) {
5099 e.rethrowFromSystemServer();
5100 }
5101 }
James Mattis356a8792020-10-28 21:48:54 -07005102
Daniel Brightf9e945b2020-06-15 16:10:01 -07005103 @NonNull
5104 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5105
5106 /**
5107 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5108 * receive available QoS events related to the {@link Network} and local ip + port
5109 * specified within socketInfo.
5110 * <p/>
5111 * The same {@link QosCallback} must be unregistered before being registered a second time,
5112 * otherwise {@link QosCallbackRegistrationException} is thrown.
5113 * <p/>
5114 * This API does not, in itself, require any permission if called with a network that is not
5115 * restricted. However, the underlying implementation currently only supports the IMS network,
5116 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5117 * useful, because they'd never be called back on networks that they would have access to.
5118 *
5119 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5120 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5121 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5122 * @throws RuntimeException if the app already has too many callbacks registered.
5123 *
5124 * Exceptions after the time of registration is passed through
5125 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5126 *
5127 * @param socketInfo the socket information used to match QoS events
Daniel Brightf9e945b2020-06-15 16:10:01 -07005128 * @param executor The executor on which the callback will be invoked. The provided
5129 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright7ee5f522021-03-10 11:51:50 -08005130 * callbacks cannot be guaranteed.onQosCallbackRegistered
5131 * @param callback receives qos events that satisfy socketInfo
Daniel Brightf9e945b2020-06-15 16:10:01 -07005132 *
5133 * @hide
5134 */
5135 @SystemApi
5136 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright7ee5f522021-03-10 11:51:50 -08005137 @CallbackExecutor @NonNull final Executor executor,
5138 @NonNull final QosCallback callback) {
Daniel Brightf9e945b2020-06-15 16:10:01 -07005139 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07005140 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright7ee5f522021-03-10 11:51:50 -08005141 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07005142
5143 try {
5144 synchronized (mQosCallbackConnections) {
5145 if (getQosCallbackConnection(callback) == null) {
5146 final QosCallbackConnection connection =
5147 new QosCallbackConnection(this, callback, executor);
5148 mQosCallbackConnections.add(connection);
5149 mService.registerQosSocketCallback(socketInfo, connection);
5150 } else {
5151 Log.e(TAG, "registerQosCallback: Callback already registered");
5152 throw new QosCallbackRegistrationException();
5153 }
5154 }
5155 } catch (final RemoteException e) {
5156 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5157
5158 // The same unregister method method is called for consistency even though nothing
5159 // will be sent to the ConnectivityService since the callback was never successfully
5160 // registered.
5161 unregisterQosCallback(callback);
5162 e.rethrowFromSystemServer();
5163 } catch (final ServiceSpecificException e) {
5164 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5165 unregisterQosCallback(callback);
5166 throw convertServiceException(e);
5167 }
5168 }
5169
5170 /**
5171 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5172 * events once unregistered and can be registered a second time.
5173 * <p/>
5174 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5175 *
5176 * @param callback the callback being unregistered
5177 *
5178 * @hide
5179 */
5180 @SystemApi
5181 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5182 Objects.requireNonNull(callback, "The callback must be non-null");
5183 try {
5184 synchronized (mQosCallbackConnections) {
5185 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5186 if (connection != null) {
5187 connection.stopReceivingMessages();
5188 mService.unregisterQosCallback(connection);
5189 mQosCallbackConnections.remove(connection);
5190 } else {
5191 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5192 }
5193 }
5194 } catch (final RemoteException e) {
5195 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5196 e.rethrowFromSystemServer();
5197 }
5198 }
5199
5200 /**
5201 * Gets the connection related to the callback.
5202 *
5203 * @param callback the callback to look up
5204 * @return the related connection
5205 */
5206 @Nullable
5207 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5208 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5209 // Checking by reference here is intentional
5210 if (connection.getCallback() == callback) {
5211 return connection;
5212 }
5213 }
5214 return null;
5215 }
Junyu Laia62493f2021-01-19 11:10:56 +00005216
5217 /**
Roshan Pius951c0032020-12-22 15:10:42 -08005218 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Laia62493f2021-01-19 11:10:56 +00005219 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5220 * be used to request that the system provide a network without causing the network to be
5221 * in the foreground.
5222 *
5223 * <p>This method will attempt to find the best network that matches the passed
5224 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5225 * criteria. The platform will evaluate which network is the best at its own discretion.
5226 * Throughput, latency, cost per byte, policy, user preference and other considerations
5227 * may be factored in the decision of what is considered the best network.
5228 *
5229 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5230 * matching this request, while always attempting to match the request to a better network if
5231 * possible. If a better match is found, the platform will switch this request to the now-best
5232 * network and inform the app of the newly best network by invoking
5233 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5234 * will not try to maintain any other network than the best one currently matching the request:
5235 * a network not matching any network request may be disconnected at any time.
5236 *
5237 * <p>For example, an application could use this method to obtain a connected cellular network
5238 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5239 * radio to consume additional power. Or, an application could inform the system that it wants
5240 * a network supporting sending MMSes and have the system let it know about the currently best
5241 * MMS-supporting network through the provided {@link NetworkCallback}.
5242 *
5243 * <p>The status of the request can be followed by listening to the various callbacks described
5244 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5245 * used to direct traffic to the network (although accessing some networks may be subject to
5246 * holding specific permissions). Callers will learn about the specific characteristics of the
5247 * network through
5248 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5249 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5250 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5251 * matching the request at any given time; therefore when a better network matching the request
5252 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5253 * with the new network after which no further updates are given about the previously-best
5254 * network, unless it becomes the best again at some later time. All callbacks are invoked
5255 * in order on the same thread, which by default is a thread created by the framework running
5256 * in the app.
5257 *
5258 * <p>This{@link NetworkRequest} will live until released via
5259 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5260 * which point the system may let go of the network at any time.
5261 *
5262 * <p>It is presently unsupported to request a network with mutable
5263 * {@link NetworkCapabilities} such as
5264 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5265 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5266 * as these {@code NetworkCapabilities} represent states that a particular
5267 * network may never attain, and whether a network will attain these states
5268 * is unknown prior to bringing up the network so the framework does not
5269 * know how to go about satisfying a request with these capabilities.
5270 *
5271 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5272 * number of outstanding requests to 100 per app (identified by their UID), shared with
5273 * all variants of this method, of {@link #registerNetworkCallback} as well as
5274 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5275 * Requesting a network with this method will count toward this limit. If this limit is
5276 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5277 * make sure to unregister the callbacks with
5278 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5279 *
5280 * @param request {@link NetworkRequest} describing this request.
5281 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5282 * If null, the callback is invoked on the default internal Handler.
5283 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5284 * the callback must not be shared - it uniquely specifies this request.
5285 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5286 * @throws SecurityException if missing the appropriate permissions.
5287 * @throws RuntimeException if the app already has too many callbacks registered.
5288 *
5289 * @hide
5290 */
5291 @SystemApi(client = MODULE_LIBRARIES)
5292 @SuppressLint("ExecutorRegistration")
5293 @RequiresPermission(anyOf = {
5294 android.Manifest.permission.NETWORK_SETTINGS,
5295 android.Manifest.permission.NETWORK_STACK,
5296 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5297 })
5298 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai962bdb82021-03-09 20:49:48 +08005299 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Laia62493f2021-01-19 11:10:56 +00005300 final NetworkCapabilities nc = request.networkCapabilities;
5301 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulai962bdb82021-03-09 20:49:48 +08005302 TYPE_NONE, new CallbackHandler(handler));
Junyu Laia62493f2021-01-19 11:10:56 +00005303 }
James Mattis45d81842021-01-10 14:24:24 -08005304
5305 /**
James Mattis45d81842021-01-10 14:24:24 -08005306 * Used by automotive devices to set the network preferences used to direct traffic at an
5307 * application level as per the given OemNetworkPreferences. An example use-case would be an
5308 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5309 * vehicle via a particular network.
5310 *
5311 * Calling this will overwrite the existing preference.
5312 *
5313 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5314 * @param executor the executor on which listener will be invoked.
5315 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5316 * communicate completion of setOemNetworkPreference(). This will only be
5317 * called once upon successful completion of setOemNetworkPreference().
5318 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5319 * @throws SecurityException if missing the appropriate permissions.
5320 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005321 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005322 */
James Mattisda32cfe2021-01-26 16:23:52 -08005323 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005324 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005325 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005326 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean6010c002021-03-03 16:37:13 +09005327 @Nullable final Runnable listener) {
James Mattis45d81842021-01-10 14:24:24 -08005328 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5329 if (null != listener) {
5330 Objects.requireNonNull(executor, "Executor must be non-null");
5331 }
Chalard Jean6010c002021-03-03 16:37:13 +09005332 final IOnCompleteListener listenerInternal = listener == null ? null :
5333 new IOnCompleteListener.Stub() {
James Mattis45d81842021-01-10 14:24:24 -08005334 @Override
5335 public void onComplete() {
Chalard Jean6010c002021-03-03 16:37:13 +09005336 executor.execute(listener::run);
James Mattis45d81842021-01-10 14:24:24 -08005337 }
5338 };
5339
5340 try {
5341 mService.setOemNetworkPreference(preference, listenerInternal);
5342 } catch (RemoteException e) {
5343 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5344 throw e.rethrowFromSystemServer();
5345 }
5346 }
lucaslin30e70a82021-03-12 00:46:33 +08005347
Chalard Jeanfa45a682021-02-25 17:23:40 +09005348 /**
5349 * Request that a user profile is put by default on a network matching a given preference.
5350 *
5351 * See the documentation for the individual preferences for a description of the supported
5352 * behaviors.
5353 *
5354 * @param profile the profile concerned.
5355 * @param preference the preference for this profile.
5356 * @param executor an executor to execute the listener on. Optional if listener is null.
5357 * @param listener an optional listener to listen for completion of the operation.
5358 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5359 * @throws SecurityException if missing the appropriate permissions.
5360 * @hide
5361 */
Chalard Jean6010c002021-03-03 16:37:13 +09005362 // This function is for establishing per-profile default networking and can only be called by
5363 // the device policy manager, running as the system server. It would make no sense to call it
5364 // on a context for a user because it does not establish a setting on behalf of a user, rather
5365 // it establishes a setting for a user on behalf of the DPM.
5366 @SuppressLint({"UserHandle"})
5367 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09005368 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5369 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5370 @ProfileNetworkPreference final int preference,
5371 @Nullable @CallbackExecutor final Executor executor,
5372 @Nullable final Runnable listener) {
5373 if (null != listener) {
5374 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5375 }
5376 final IOnCompleteListener proxy;
5377 if (null == listener) {
5378 proxy = null;
5379 } else {
5380 proxy = new IOnCompleteListener.Stub() {
5381 @Override
5382 public void onComplete() {
5383 executor.execute(listener::run);
5384 }
5385 };
5386 }
5387 try {
5388 mService.setProfileNetworkPreference(profile, preference, proxy);
5389 } catch (RemoteException e) {
5390 throw e.rethrowFromSystemServer();
5391 }
5392 }
5393
lucaslin30e70a82021-03-12 00:46:33 +08005394 // The first network ID of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005395 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin30e70a82021-03-12 00:46:33 +08005396 // The network ID range of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005397 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin30e70a82021-03-12 00:46:33 +08005398
5399 /**
5400 * Get the network ID range reserved for IPSec tunnel interfaces.
5401 *
5402 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5403 * @hide
5404 */
5405 @SystemApi(client = MODULE_LIBRARIES)
5406 @NonNull
5407 public static Range<Integer> getIpSecNetIdRange() {
5408 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5409 }
lucaslin705c3332021-03-12 17:56:09 +08005410
5411 /**
5412 * Get private DNS mode from settings.
5413 *
lucaslin7abe7e02021-03-17 14:53:35 +08005414 * @param context The Context to query the private DNS mode from settings.
lucaslin705c3332021-03-12 17:56:09 +08005415 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5416 *
5417 * @hide
5418 */
5419 @SystemApi(client = MODULE_LIBRARIES)
5420 @NonNull
5421 @PrivateDnsMode
lucaslin20f04882021-03-16 17:11:14 +08005422 public static String getPrivateDnsMode(@NonNull Context context) {
5423 final ContentResolver cr = context.getContentResolver();
lucaslin705c3332021-03-12 17:56:09 +08005424 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5425 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5426 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5427 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5428 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5429 return mode;
5430 }
paulhu89a762a2021-03-25 12:36:56 +08005431
5432 /**
5433 * Set private DNS mode to settings.
5434 *
5435 * @param context The {@link Context} to set the private DNS mode.
5436 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5437 *
5438 * @hide
5439 */
5440 @SystemApi(client = MODULE_LIBRARIES)
5441 public static void setPrivateDnsMode(@NonNull Context context,
5442 @NonNull @PrivateDnsMode String mode) {
5443 if (!(mode == PRIVATE_DNS_MODE_OFF
5444 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5445 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5446 throw new IllegalArgumentException("Invalid private dns mode");
5447 }
5448 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5449 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005450}