blob: 9fbf04952f1333b3c08cb9839ffd844111754c01 [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 */
lucasline8b3f9c2021-03-04 17:09:51 +0800428 @SystemApi(client = MODULE_LIBRARIES)
429 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900430
431 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900432 * Action used to display a dialog that asks the user whether to avoid a network that is no
433 * longer validated. This intent is used to start the dialog in settings via startActivity.
434 *
435 * @hide
436 */
lucasline8b3f9c2021-03-04 17:09:51 +0800437 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900438 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucasline8b3f9c2021-03-04 17:09:51 +0800439 "android.net.action.PROMPT_LOST_VALIDATION";
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900440
441 /**
lucaslin2240ef62019-03-12 13:08:03 +0800442 * Action used to display a dialog that asks the user whether to stay connected to a network
443 * that has not validated. This intent is used to start the dialog in settings via
444 * startActivity.
445 *
446 * @hide
447 */
lucasline8b3f9c2021-03-04 17:09:51 +0800448 @SystemApi(client = MODULE_LIBRARIES)
lucaslin2240ef62019-03-12 13:08:03 +0800449 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucasline8b3f9c2021-03-04 17:09:51 +0800450 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
lucaslin2240ef62019-03-12 13:08:03 +0800451
452 /**
paulhue3fe4d02021-04-07 16:18:13 +0800453 * Clear DNS Cache Action: This is broadcast when networks have changed and old
454 * DNS entries should be cleared.
455 * @hide
456 */
457 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
458 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
459 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
460
461 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800462 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900463 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800464 * @hide
465 */
markchiena0f8fd92019-12-25 19:40:32 +0800466 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800467
468 /**
469 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900470 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800471 * @hide
472 */
473 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900474 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800475
476 /**
477 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900478 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800479 * @hide
480 */
481 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900482 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800483
484 /**
485 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900486 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800487 * @hide
488 */
489 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900490 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800491
492 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800493 * Wifi P2p tethering type.
494 * Wifi P2p tethering is set through events automatically, and don't
495 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
496 * @hide
497 */
markchiena0f8fd92019-12-25 19:40:32 +0800498 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800499
500 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800501 * Extra used for communicating with the TetherService. Includes the type of tethering to
502 * enable if any.
503 * @hide
504 */
markchien6ae63e52020-01-21 13:11:06 +0800505 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800506
507 /**
508 * Extra used for communicating with the TetherService. Includes the type of tethering for
509 * which to cancel provisioning.
510 * @hide
511 */
markchien6ae63e52020-01-21 13:11:06 +0800512 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800513
514 /**
515 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
516 * provisioning.
517 * @hide
518 */
markchien6ae63e52020-01-21 13:11:06 +0800519 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800520
521 /**
522 * Tells the TetherService to run a provision check now.
523 * @hide
524 */
markchien6ae63e52020-01-21 13:11:06 +0800525 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800526
527 /**
528 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
529 * which will receive provisioning results. Can be left empty.
530 * @hide
531 */
markchien6ae63e52020-01-21 13:11:06 +0800532 public static final String EXTRA_PROVISION_CALLBACK =
533 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800534
535 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800536 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700537 * @hide
538 */
paulhu74357e72020-01-13 16:46:45 +0800539 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700540 public static final int TYPE_NONE = -1;
541
542 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900543 * A Mobile data connection. Devices may support more than one.
544 *
545 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
546 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
547 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700548 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900549 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700550 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900551
Robert Greenwalt2034b912009-08-12 16:08:25 -0700552 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900553 * A WIFI data connection. Devices may support more than one.
554 *
555 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
556 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
557 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700558 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900559 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700560 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900561
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800563 * An MMS-specific Mobile data connection. This network type may use the
564 * same network interface as {@link #TYPE_MOBILE} or it may use a different
565 * one. This is used by applications needing to talk to the carrier's
566 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900567 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900568 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900569 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900570 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700572 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700573 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900574
Robert Greenwalt2034b912009-08-12 16:08:25 -0700575 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800576 * A SUPL-specific Mobile data connection. This network type may use the
577 * same network interface as {@link #TYPE_MOBILE} or it may use a different
578 * one. This is used by applications needing to talk to the carrier's
579 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900580 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900581 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900582 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900583 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700585 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700586 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900587
Robert Greenwalt2034b912009-08-12 16:08:25 -0700588 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800589 * A DUN-specific Mobile data connection. This network type may use the
590 * same network interface as {@link #TYPE_MOBILE} or it may use a different
591 * one. This is sometimes by the system when setting up an upstream connection
592 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900593 *
594 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
595 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
596 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700597 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900598 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700599 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900600
Robert Greenwalt2034b912009-08-12 16:08:25 -0700601 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800602 * A High Priority Mobile data connection. This network type uses the
603 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900604 * is different.
605 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900606 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
607 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
608 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700609 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700610 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700611 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900612
jshbfa81722010-03-11 15:04:43 -0800613 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900614 * A WiMAX data connection.
615 *
616 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
617 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
618 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800619 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900620 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800621 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800622
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800623 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900624 * A Bluetooth data connection.
625 *
626 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
627 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
628 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800629 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900630 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800631 public static final int TYPE_BLUETOOTH = 7;
632
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700633 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800634 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900635 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700636 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900637 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800638 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800639
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700640 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900641 * An Ethernet data connection.
642 *
643 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
644 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
645 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700646 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900647 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800648 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700649
Wink Savilleb7c92c72011-03-12 14:52:01 -0800650 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800651 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900652 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800653 * {@hide}
654 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900655 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900656 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800657 public static final int TYPE_MOBILE_FOTA = 10;
658
659 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800660 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900661 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800662 * {@hide}
663 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900664 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100665 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800666 public static final int TYPE_MOBILE_IMS = 11;
667
668 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800669 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900670 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800671 * {@hide}
672 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900673 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900674 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800675 public static final int TYPE_MOBILE_CBS = 12;
676
repo syncf5de5572011-07-29 23:55:49 -0700677 /**
678 * A Wi-Fi p2p connection. Only requesting processes will have access to
679 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900680 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700681 * {@hide}
682 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900683 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800684 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700685 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800686
Wink Saville512c2202013-07-29 15:00:57 -0700687 /**
688 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900689 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700690 * {@hide}
691 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900692 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100693 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700694 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700695
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900696 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700697 * Emergency PDN connection for emergency services. This
698 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900699 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700700 * {@hide}
701 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900702 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900703 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700704 public static final int TYPE_MOBILE_EMERGENCY = 15;
705
Hui Lu865b70d2014-01-15 11:05:36 -0500706 /**
707 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900708 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500709 * {@hide}
710 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900711 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900712 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500713 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700714
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700715 /**
716 * A virtual network using one or more native bearers.
717 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900718 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700719 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900720 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700721 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500722
Benedict Wongbdfaa482018-11-14 17:40:55 -0800723 /**
724 * A network that is exclusively meant to be used for testing
725 *
726 * @deprecated Use {@link NetworkCapabilities} instead.
727 * @hide
728 */
729 @Deprecated
730 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700731
Chalard Jeanaea539a2020-03-25 01:24:04 +0900732 /**
733 * @deprecated Use {@link NetworkCapabilities} instead.
734 * @hide
735 */
736 @Deprecated
737 @Retention(RetentionPolicy.SOURCE)
738 @IntDef(prefix = { "TYPE_" }, value = {
739 TYPE_NONE,
740 TYPE_MOBILE,
741 TYPE_WIFI,
742 TYPE_MOBILE_MMS,
743 TYPE_MOBILE_SUPL,
744 TYPE_MOBILE_DUN,
745 TYPE_MOBILE_HIPRI,
746 TYPE_WIMAX,
747 TYPE_BLUETOOTH,
748 TYPE_DUMMY,
749 TYPE_ETHERNET,
750 TYPE_MOBILE_FOTA,
751 TYPE_MOBILE_IMS,
752 TYPE_MOBILE_CBS,
753 TYPE_WIFI_P2P,
754 TYPE_MOBILE_IA,
755 TYPE_MOBILE_EMERGENCY,
756 TYPE_PROXY,
757 TYPE_VPN,
758 TYPE_TEST
759 })
760 public @interface LegacyNetworkType {}
761
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900762 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
763 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
764 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
765 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
766 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
767
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700768 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800769 public static final int MAX_RADIO_TYPE = TYPE_TEST;
770
771 /** {@hide} */
772 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800773
Hugo Benichiad353f42017-06-20 14:07:59 +0900774 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
775
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800776 /**
777 * If you want to set the default network preference,you can directly
778 * change the networkAttributes array in framework's config.xml.
779 *
780 * @deprecated Since we support so many more networks now, the single
781 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800782 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800783 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800784 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800785 * from an App.
786 */
787 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800788 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
789
Jeff Sharkey8c870452012-09-26 22:03:49 -0700790 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700791 * @hide
792 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900793 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700794
Paul Jensen5dea4352014-07-11 12:28:19 -0400795 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900796 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
797 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900798 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900799 * @hide
800 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900801 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900802 new NetworkRequest.Builder().clearCapabilities().build();
803
804 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400805 * A NetID indicating no Network is selected.
806 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
807 * @hide
808 */
809 public static final int NETID_UNSET = 0;
810
Erik Klineb0be3e62017-10-30 15:29:44 +0900811 /**
812 * Private DNS Mode values.
813 *
814 * The "private_dns_mode" global setting stores a String value which is
815 * expected to be one of the following.
816 */
817
818 /**
819 * @hide
820 */
lucaslin705c3332021-03-12 17:56:09 +0800821 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900822 public static final String PRIVATE_DNS_MODE_OFF = "off";
823 /**
824 * @hide
825 */
lucaslin705c3332021-03-12 17:56:09 +0800826 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900827 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
828 /**
829 * @hide
830 */
lucaslin705c3332021-03-12 17:56:09 +0800831 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900832 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin705c3332021-03-12 17:56:09 +0800833
834 /** @hide */
835 @Retention(RetentionPolicy.SOURCE)
836 @StringDef(value = {
837 PRIVATE_DNS_MODE_OFF,
838 PRIVATE_DNS_MODE_OPPORTUNISTIC,
839 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
840 })
841 public @interface PrivateDnsMode {}
Erik Klineb0be3e62017-10-30 15:29:44 +0900842
Sudheer Shanka98215562021-03-23 08:12:28 +0000843 /**
844 * Flag to indicate that an app is not subject to any restrictions that could result in its
845 * network access blocked.
846 *
847 * @hide
848 */
849 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
850 public static final int BLOCKED_REASON_NONE = 0;
851
852 /**
853 * Flag to indicate that an app is subject to Battery saver restrictions that would
854 * result in its network access being blocked.
855 *
856 * @hide
857 */
858 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
859 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
860
861 /**
862 * Flag to indicate that an app is subject to Doze restrictions that would
863 * result in its network access being blocked.
864 *
865 * @hide
866 */
867 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
868 public static final int BLOCKED_REASON_DOZE = 1 << 1;
869
870 /**
871 * Flag to indicate that an app is subject to App Standby restrictions that would
872 * result in its network access being blocked.
873 *
874 * @hide
875 */
876 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
877 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
878
879 /**
880 * Flag to indicate that an app is subject to Restricted mode restrictions that would
881 * result in its network access being blocked.
882 *
883 * @hide
884 */
885 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
886 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
887
888 /**
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900889 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
890 * is not currently connected.
891 *
892 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
893 *
894 * @hide
895 */
896 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
897 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
898
899 /**
Sudheer Shanka98215562021-03-23 08:12:28 +0000900 * Flag to indicate that an app is subject to Data saver restrictions that would
901 * result in its metered network access being blocked.
902 *
903 * @hide
904 */
905 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
906 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
907
908 /**
909 * Flag to indicate that an app is subject to user restrictions that would
910 * result in its metered network access being blocked.
911 *
912 * @hide
913 */
914 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
915 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
916
917 /**
918 * Flag to indicate that an app is subject to Device admin restrictions that would
919 * result in its metered network access being blocked.
920 *
921 * @hide
922 */
923 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
924 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
925
926 /**
927 * @hide
928 */
929 @Retention(RetentionPolicy.SOURCE)
930 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
931 BLOCKED_REASON_NONE,
932 BLOCKED_REASON_BATTERY_SAVER,
933 BLOCKED_REASON_DOZE,
934 BLOCKED_REASON_APP_STANDBY,
935 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colitti42fe2232021-03-25 23:17:36 +0900936 BLOCKED_REASON_LOCKDOWN_VPN,
Sudheer Shanka98215562021-03-23 08:12:28 +0000937 BLOCKED_METERED_REASON_DATA_SAVER,
938 BLOCKED_METERED_REASON_USER_RESTRICTED,
939 BLOCKED_METERED_REASON_ADMIN_DISABLED,
940 })
941 public @interface BlockedReason {}
942
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900943 /**
944 * Set of blocked reasons that are only applicable on metered networks.
945 *
946 * @hide
947 */
948 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
949 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
950
Chalard Jeana3b77512019-04-09 15:46:21 +0900951 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700952 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900953
Paul Jensenc0618a62014-12-10 15:12:18 -0500954 /**
955 * A kludge to facilitate static access where a Context pointer isn't available, like in the
956 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
957 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
958 * methods that take a Context argument.
959 */
960 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800961
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900962 private final Context mContext;
963
Amos Bianchia9b415a2020-03-04 11:07:38 -0800964 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800965
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800966 /**
967 * Tests if a given integer represents a valid network type.
968 * @param networkType the type to be tested
969 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400970 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
971 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800972 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700973 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700974 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900975 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800976 }
977
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800978 /**
979 * Returns a non-localized string representing a given network type.
980 * ONLY used for debugging output.
981 * @param type the type needing naming
982 * @return a String for the given type, or a string version of the type ("87")
983 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900984 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800985 * {@hide}
986 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900987 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000988 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700989 public static String getNetworkTypeName(int type) {
990 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900991 case TYPE_NONE:
992 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700993 case TYPE_MOBILE:
994 return "MOBILE";
995 case TYPE_WIFI:
996 return "WIFI";
997 case TYPE_MOBILE_MMS:
998 return "MOBILE_MMS";
999 case TYPE_MOBILE_SUPL:
1000 return "MOBILE_SUPL";
1001 case TYPE_MOBILE_DUN:
1002 return "MOBILE_DUN";
1003 case TYPE_MOBILE_HIPRI:
1004 return "MOBILE_HIPRI";
1005 case TYPE_WIMAX:
1006 return "WIMAX";
1007 case TYPE_BLUETOOTH:
1008 return "BLUETOOTH";
1009 case TYPE_DUMMY:
1010 return "DUMMY";
1011 case TYPE_ETHERNET:
1012 return "ETHERNET";
1013 case TYPE_MOBILE_FOTA:
1014 return "MOBILE_FOTA";
1015 case TYPE_MOBILE_IMS:
1016 return "MOBILE_IMS";
1017 case TYPE_MOBILE_CBS:
1018 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -07001019 case TYPE_WIFI_P2P:
1020 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -07001021 case TYPE_MOBILE_IA:
1022 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -07001023 case TYPE_MOBILE_EMERGENCY:
1024 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -05001025 case TYPE_PROXY:
1026 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +09001027 case TYPE_VPN:
1028 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -07001029 default:
1030 return Integer.toString(type);
1031 }
1032 }
1033
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001034 /**
Aaron Huang96011892020-06-27 07:18:23 +08001035 * @hide
Aaron Huang96011892020-06-27 07:18:23 +08001036 */
lucaslin7fc930b2021-03-17 14:16:01 +08001037 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huang96011892020-06-27 07:18:23 +08001038 public void systemReady() {
1039 try {
1040 mService.systemReady();
1041 } catch (RemoteException e) {
1042 throw e.rethrowFromSystemServer();
1043 }
1044 }
1045
1046 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001047 * Checks if a given type uses the cellular data connection.
1048 * This should be replaced in the future by a network property.
1049 * @param networkType the type to check
1050 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001051 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001052 * {@hide}
1053 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001054 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +09001055 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001056 public static boolean isNetworkTypeMobile(int networkType) {
1057 switch (networkType) {
1058 case TYPE_MOBILE:
1059 case TYPE_MOBILE_MMS:
1060 case TYPE_MOBILE_SUPL:
1061 case TYPE_MOBILE_DUN:
1062 case TYPE_MOBILE_HIPRI:
1063 case TYPE_MOBILE_FOTA:
1064 case TYPE_MOBILE_IMS:
1065 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -07001066 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -07001067 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -07001068 return true;
1069 default:
1070 return false;
1071 }
1072 }
1073
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001074 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001075 * Checks if the given network type is backed by a Wi-Fi radio.
1076 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001077 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001078 * @hide
1079 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001080 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001081 public static boolean isNetworkTypeWifi(int networkType) {
1082 switch (networkType) {
1083 case TYPE_WIFI:
1084 case TYPE_WIFI_P2P:
1085 return true;
1086 default:
1087 return false;
1088 }
1089 }
1090
1091 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +09001092 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1093 * Specify that the traffic for this user should by follow the default rules.
1094 * @hide
1095 */
Chalard Jeanb43f3962021-03-17 14:33:24 +09001096 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09001097 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1098
1099 /**
1100 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1101 * Specify that the traffic for this user should by default go on a network with
1102 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1103 * if no such network is available.
1104 * @hide
1105 */
Chalard Jeanb43f3962021-03-17 14:33:24 +09001106 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09001107 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1108
1109 /** @hide */
1110 @Retention(RetentionPolicy.SOURCE)
1111 @IntDef(value = {
1112 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1113 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1114 })
1115 public @interface ProfileNetworkPreference {
1116 }
1117
1118 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001119 * Specifies the preferred network type. When the device has more
1120 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001121 *
1122 * @param preference the network type to prefer over all others. It is
1123 * unspecified what happens to the old preferred network in the
1124 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001125 * @deprecated Functionality has been removed as it no longer makes sense,
1126 * with many more than two networks - we'd need an array to express
1127 * preference. Instead we use dynamic network properties of
1128 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001129 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001130 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001131 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001132 }
1133
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001134 /**
1135 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001136 *
1137 * @return an integer representing the preferred network type
1138 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001139 * @deprecated Functionality has been removed as it no longer makes sense,
1140 * with many more than two networks - we'd need an array to express
1141 * preference. Instead we use dynamic network properties of
1142 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001143 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001144 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001145 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001146 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001147 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001148 }
1149
Scott Mainf58b7d82011-10-06 19:02:28 -07001150 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001151 * Returns details about the currently active default data network. When
1152 * connected, this network is the default route for outgoing connections.
1153 * You should always check {@link NetworkInfo#isConnected()} before initiating
1154 * network traffic. This may return {@code null} when there is no default
1155 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001156 * Note that if the default network is a VPN, this method will return the
1157 * NetworkInfo for one of its underlying networks instead, or null if the
1158 * VPN agent did not specify any. Apps interested in learning about VPNs
1159 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001160 *
1161 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001162 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001163 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001164 */
junyulai9826e7f2018-12-13 12:47:51 +08001165 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001166 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001167 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001168 public NetworkInfo getActiveNetworkInfo() {
1169 try {
1170 return mService.getActiveNetworkInfo();
1171 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001172 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001173 }
1174 }
1175
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001176 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001177 * Returns a {@link Network} object corresponding to the currently active
1178 * default data network. In the event that the current active default data
1179 * network disconnects, the returned {@code Network} object will no longer
1180 * be usable. This will return {@code null} when there is no default
1181 * network.
1182 *
1183 * @return a {@link Network} object for the current default network or
1184 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001185 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001186 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001187 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001188 public Network getActiveNetwork() {
1189 try {
1190 return mService.getActiveNetwork();
1191 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001192 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001193 }
1194 }
1195
1196 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001197 * Returns a {@link Network} object corresponding to the currently active
1198 * default data network for a specific UID. In the event that the default data
1199 * network disconnects, the returned {@code Network} object will no longer
1200 * be usable. This will return {@code null} when there is no default
1201 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001202 *
1203 * @return a {@link Network} object for the current default network for the
1204 * given UID or {@code null} if no default network is currently active
lifr42a60c22021-03-11 20:11:09 +08001205 * TODO: b/183465229 Cleanup getActiveNetworkForUid once b/165835257 is fixed
Robin Lee5b52bef2016-03-24 12:07:00 +00001206 */
paulhu8e96a752019-08-12 16:25:11 +08001207 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001208 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001209 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001210 return getActiveNetworkForUid(uid, false);
1211 }
1212
1213 /** {@hide} */
1214 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001215 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001216 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001217 } catch (RemoteException e) {
1218 throw e.rethrowFromSystemServer();
1219 }
1220 }
1221
1222 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001223 * Adds or removes a requirement for given UID ranges to use the VPN.
1224 *
1225 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1226 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1227 * otherwise have permission to bypass the VPN (e.g., because they have the
1228 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1229 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1230 * set to {@code false}, a previously-added restriction is removed.
1231 * <p>
1232 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1233 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1234 * remove a previously-added range, the exact range must be removed as is.
1235 * <p>
1236 * The changes are applied asynchronously and may not have been applied by the time the method
1237 * returns. Apps will be notified about any changes that apply to them via
1238 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1239 * effect.
1240 * <p>
1241 * This method should be called only by the VPN code.
1242 *
1243 * @param ranges the UID ranges to restrict
1244 * @param requireVpn whether the specified UID ranges must use a VPN
1245 *
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001246 * @hide
1247 */
1248 @RequiresPermission(anyOf = {
1249 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucasline257bce2021-03-22 11:51:27 +08001250 android.Manifest.permission.NETWORK_STACK,
1251 android.Manifest.permission.NETWORK_SETTINGS})
1252 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001253 public void setRequireVpnForUids(boolean requireVpn,
1254 @NonNull Collection<Range<Integer>> ranges) {
1255 Objects.requireNonNull(ranges);
1256 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1257 // This method is not necessarily expected to be used outside the system server, so
1258 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1259 // stack process, or by tests.
1260 UidRange[] rangesArray = new UidRange[ranges.size()];
1261 int index = 0;
1262 for (Range<Integer> range : ranges) {
1263 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1264 }
1265 try {
1266 mService.setRequireVpnForUids(requireVpn, rangesArray);
1267 } catch (RemoteException e) {
1268 throw e.rethrowFromSystemServer();
1269 }
1270 }
1271
1272 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001273 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1274 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1275 * but is still supported for backwards compatibility.
1276 * <p>
1277 * This type of VPN is assumed always to use the system default network, and must always declare
1278 * exactly one underlying network, which is the network that was the default when the VPN
1279 * connected.
1280 * <p>
1281 * Calling this method with {@code true} enables legacy behaviour, specifically:
1282 * <ul>
1283 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1284 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1285 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1286 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1287 * underlying the VPN.</li>
1288 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1289 * similarly replaced by the VPN network state.</li>
1290 * <li>Information on current network interfaces passed to NetworkStatsService will not
1291 * include any VPN interfaces.</li>
1292 * </ul>
1293 *
1294 * @param enabled whether legacy lockdown VPN is enabled or disabled
1295 *
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001296 * @hide
1297 */
1298 @RequiresPermission(anyOf = {
1299 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucasline257bce2021-03-22 11:51:27 +08001300 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001301 android.Manifest.permission.NETWORK_SETTINGS})
lucasline257bce2021-03-22 11:51:27 +08001302 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001303 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1304 try {
1305 mService.setLegacyLockdownVpnEnabled(enabled);
1306 } catch (RemoteException e) {
1307 throw e.rethrowFromSystemServer();
1308 }
1309 }
1310
1311 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001312 * Returns details about the currently active default data network
1313 * for a given uid. This is for internal use only to avoid spying
1314 * other apps.
1315 *
1316 * @return a {@link NetworkInfo} object for the current default network
1317 * for the given uid or {@code null} if no default network is
1318 * available for the specified uid.
1319 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001320 * {@hide}
1321 */
paulhu8e96a752019-08-12 16:25:11 +08001322 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001323 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001324 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001325 return getActiveNetworkInfoForUid(uid, false);
1326 }
1327
1328 /** {@hide} */
1329 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001330 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001331 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001332 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001333 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001334 }
1335 }
1336
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001337 /**
1338 * Returns connection status information about a particular
1339 * network type.
1340 *
1341 * @param networkType integer specifying which networkType in
1342 * which you're interested.
1343 * @return a {@link NetworkInfo} object for the requested
1344 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001345 * supported by the device. If {@code networkType} is
1346 * TYPE_VPN and a VPN is active for the calling app,
1347 * then this method will try to return one of the
1348 * underlying networks for the VPN or null if the
1349 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001350 *
Paul Jensendda8e592015-03-18 12:23:02 -04001351 * @deprecated This method does not support multiple connected networks
1352 * of the same type. Use {@link #getAllNetworks} and
1353 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001354 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001355 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001356 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001357 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001358 public NetworkInfo getNetworkInfo(int networkType) {
1359 try {
1360 return mService.getNetworkInfo(networkType);
1361 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001362 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001363 }
1364 }
1365
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001366 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001367 * Returns connection status information about a particular
1368 * Network.
1369 *
1370 * @param network {@link Network} specifying which network
1371 * in which you're interested.
1372 * @return a {@link NetworkInfo} object for the requested
1373 * network or {@code null} if the {@code Network}
1374 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001375 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001376 */
junyulai9826e7f2018-12-13 12:47:51 +08001377 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001378 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001379 @Nullable
1380 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001381 return getNetworkInfoForUid(network, Process.myUid(), false);
1382 }
1383
1384 /** {@hide} */
1385 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001386 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001387 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001388 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001389 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001390 }
1391 }
1392
1393 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001394 * Returns connection status information about all network
1395 * types supported by the device.
1396 *
1397 * @return an array of {@link NetworkInfo} objects. Check each
1398 * {@link NetworkInfo#getType} for which type each applies.
1399 *
Paul Jensendda8e592015-03-18 12:23:02 -04001400 * @deprecated This method does not support multiple connected networks
1401 * of the same type. Use {@link #getAllNetworks} and
1402 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001403 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001404 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001405 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001406 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001407 public NetworkInfo[] getAllNetworkInfo() {
1408 try {
1409 return mService.getAllNetworkInfo();
1410 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001411 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001412 }
1413 }
1414
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001415 /**
junyulaiebd15162021-03-03 12:09:05 +08001416 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1417 * connected.
1418 * @hide
1419 */
1420 @SystemApi(client = MODULE_LIBRARIES)
1421 @RequiresPermission(anyOf = {
1422 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1423 android.Manifest.permission.NETWORK_STACK,
1424 android.Manifest.permission.NETWORK_SETTINGS})
1425 @NonNull
1426 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1427 try {
1428 return mService.getAllNetworkStateSnapshot();
1429 } catch (RemoteException e) {
1430 throw e.rethrowFromSystemServer();
1431 }
1432 }
1433
1434 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001435 * Returns the {@link Network} object currently serving a given type, or
1436 * null if the given type is not connected.
1437 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001438 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001439 * @deprecated This method does not support multiple connected networks
1440 * of the same type. Use {@link #getAllNetworks} and
1441 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001442 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001443 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001444 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001445 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001446 public Network getNetworkForType(int networkType) {
1447 try {
1448 return mService.getNetworkForType(networkType);
1449 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001450 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001451 }
1452 }
1453
1454 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001455 * Returns an array of all {@link Network} currently tracked by the
1456 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001457 *
1458 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001459 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001460 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001461 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001462 public Network[] getAllNetworks() {
1463 try {
1464 return mService.getAllNetworks();
1465 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001466 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001467 }
1468 }
1469
1470 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001471 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001472 * the Networks that applications run by the given user will use by default.
1473 * @hide
1474 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001475 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001476 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1477 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001478 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001479 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001480 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001481 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001482 }
1483 }
1484
1485 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001486 * Returns the IP information for the current default network.
1487 *
1488 * @return a {@link LinkProperties} object describing the IP info
1489 * for the current default network, or {@code null} if there
1490 * is no current default network.
1491 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001492 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001493 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1494 * value of {@link #getActiveNetwork()} instead. In particular,
1495 * this method will return non-null LinkProperties even if the
1496 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001497 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001498 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001499 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001500 public LinkProperties getActiveLinkProperties() {
1501 try {
1502 return mService.getActiveLinkProperties();
1503 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001504 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001505 }
1506 }
1507
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001508 /**
1509 * Returns the IP information for a given network type.
1510 *
1511 * @param networkType the network type of interest.
1512 * @return a {@link LinkProperties} object describing the IP info
1513 * for the given networkType, or {@code null} if there is
1514 * no current default network.
1515 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001516 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001517 * @deprecated This method does not support multiple connected networks
1518 * of the same type. Use {@link #getAllNetworks},
1519 * {@link #getNetworkInfo(android.net.Network)}, and
1520 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001521 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001522 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001523 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001524 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001525 public LinkProperties getLinkProperties(int networkType) {
1526 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001527 return mService.getLinkPropertiesForType(networkType);
1528 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001529 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001530 }
1531 }
1532
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001533 /**
1534 * Get the {@link LinkProperties} for the given {@link Network}. This
1535 * will return {@code null} if the network is unknown.
1536 *
1537 * @param network The {@link Network} object identifying the network in question.
1538 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001539 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001540 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001541 @Nullable
1542 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001543 try {
1544 return mService.getLinkProperties(network);
1545 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001546 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001547 }
1548 }
1549
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001550 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001551 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001552 * will return {@code null} if the network is unknown.
1553 *
Roshan Pius951c0032020-12-22 15:10:42 -08001554 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1555 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1556 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1557 * this location sensitive information (subject to app's location permissions) will be
1558 * noted by system. To include any location sensitive data in {@link TransportInfo},
1559 * use a {@link NetworkCallback} with
1560 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1561 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001562 * @param network The {@link Network} object identifying the network in question.
Roshan Pius951c0032020-12-22 15:10:42 -08001563 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001564 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001565 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001566 @Nullable
1567 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001568 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001569 return mService.getNetworkCapabilities(
1570 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001571 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001572 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001573 }
1574 }
1575
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001576 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001577 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001578 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1579 * portal is present.
1580 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1581 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1582 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001583 * The system network validation may be using different strategies to detect captive portals,
1584 * so this method does not necessarily return a URL used by the system. It only returns a URL
1585 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001586 *
Udam Sainicd645462016-01-04 12:16:14 -08001587 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001588 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1589 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001590 */
paulhu8e96a752019-08-12 16:25:11 +08001591 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001592 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001593 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001594 public String getCaptivePortalServerUrl() {
1595 try {
1596 return mService.getCaptivePortalServerUrl();
1597 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001598 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001599 }
1600 }
1601
1602 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001603 * Tells the underlying networking system that the caller wants to
1604 * begin using the named feature. The interpretation of {@code feature}
1605 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001606 *
1607 * <p>This method requires the caller to hold either the
1608 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1609 * or the ability to modify system settings as determined by
1610 * {@link android.provider.Settings.System#canWrite}.</p>
1611 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001612 * @param networkType specifies which network the request pertains to
1613 * @param feature the name of the feature to be used
1614 * @return an integer value representing the outcome of the request.
1615 * The interpretation of this value is specific to each networking
1616 * implementation+feature combination, except that the value {@code -1}
1617 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001618 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001619 * @deprecated Deprecated in favor of the cleaner
1620 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001621 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001622 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001623 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001624 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001625 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001626 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001627 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001628 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1629 if (netCap == null) {
1630 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1631 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001632 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001633 }
1634
1635 NetworkRequest request = null;
1636 synchronized (sLegacyRequests) {
1637 LegacyRequest l = sLegacyRequests.get(netCap);
1638 if (l != null) {
1639 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1640 renewRequestLocked(l);
1641 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001642 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001643 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001644 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001645 }
1646 }
1647
1648 request = requestNetworkForFeatureLocked(netCap);
1649 }
1650 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001651 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001652 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001653 } else {
1654 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001655 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001656 }
1657 }
1658
1659 /**
1660 * Tells the underlying networking system that the caller is finished
1661 * using the named feature. The interpretation of {@code feature}
1662 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001663 *
1664 * <p>This method requires the caller to hold either the
1665 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1666 * or the ability to modify system settings as determined by
1667 * {@link android.provider.Settings.System#canWrite}.</p>
1668 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001669 * @param networkType specifies which network the request pertains to
1670 * @param feature the name of the feature that is no longer needed
1671 * @return an integer value representing the outcome of the request.
1672 * The interpretation of this value is specific to each networking
1673 * implementation+feature combination, except that the value {@code -1}
1674 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001675 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001676 * @deprecated Deprecated in favor of the cleaner
1677 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001678 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001679 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001680 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001681 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001682 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001683 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001684 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001685 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1686 if (netCap == null) {
1687 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1688 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001689 return -1;
1690 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001691
Paul Jensen49f74a32014-12-17 10:39:34 -05001692 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001693 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001694 }
1695 return 1;
1696 }
1697
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001698 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001699 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1700 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001701 switch (feature) {
1702 case "enableCBS":
1703 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1704 case "enableDUN":
1705 case "enableDUNAlways":
1706 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1707 case "enableFOTA":
1708 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1709 case "enableHIPRI":
1710 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1711 case "enableIMS":
1712 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1713 case "enableMMS":
1714 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1715 case "enableSUPL":
1716 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1717 default:
1718 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001719 }
Erik Klinece55eb12017-01-26 18:08:28 +09001720 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1721 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001722 }
1723 return null;
1724 }
1725
Robert Greenwalt802c1102014-06-02 15:32:02 -07001726 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001727 if (netCap == null) return TYPE_NONE;
1728 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1729 return TYPE_MOBILE_CBS;
1730 }
1731 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1732 return TYPE_MOBILE_IMS;
1733 }
1734 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1735 return TYPE_MOBILE_FOTA;
1736 }
1737 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1738 return TYPE_MOBILE_DUN;
1739 }
1740 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1741 return TYPE_MOBILE_SUPL;
1742 }
1743 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1744 return TYPE_MOBILE_MMS;
1745 }
1746 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1747 return TYPE_MOBILE_HIPRI;
1748 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001749 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1750 return TYPE_WIFI_P2P;
1751 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001752 return TYPE_NONE;
1753 }
1754
1755 private static class LegacyRequest {
1756 NetworkCapabilities networkCapabilities;
1757 NetworkRequest networkRequest;
1758 int expireSequenceNumber;
1759 Network currentNetwork;
1760 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001761
1762 private void clearDnsBinding() {
1763 if (currentNetwork != null) {
1764 currentNetwork = null;
1765 setProcessDefaultNetworkForHostResolution(null);
1766 }
1767 }
1768
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001769 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001770 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001771 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001772 currentNetwork = network;
1773 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001774 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001775 }
1776 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001777 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001778 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001779 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1780 }
1781 };
1782 }
1783
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001784 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001785 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1786 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001787
1788 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1789 synchronized (sLegacyRequests) {
1790 LegacyRequest l = sLegacyRequests.get(netCap);
1791 if (l != null) return l.networkRequest;
1792 }
1793 return null;
1794 }
1795
1796 private void renewRequestLocked(LegacyRequest l) {
1797 l.expireSequenceNumber++;
1798 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1799 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1800 }
1801
1802 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1803 int ourSeqNum = -1;
1804 synchronized (sLegacyRequests) {
1805 LegacyRequest l = sLegacyRequests.get(netCap);
1806 if (l == null) return;
1807 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001808 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001809 }
1810 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1811 }
1812
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001813 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001814 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1815 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001816 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001817 try {
1818 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001819 } catch (RemoteException e) {
1820 throw e.rethrowFromSystemServer();
1821 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001822 LegacyRequest l = new LegacyRequest();
1823 l.networkCapabilities = netCap;
1824 l.delay = delay;
1825 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001826 l.networkRequest = sendRequestForNetwork(
1827 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001828 if (l.networkRequest == null) return null;
1829 sLegacyRequests.put(netCap, l);
1830 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1831 return l.networkRequest;
1832 }
1833
1834 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1835 if (delay >= 0) {
1836 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001837 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001838 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1839 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001840 }
1841 }
1842
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001843 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001844 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1845 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001846 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001847 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001848 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001849 if (l == null) return false;
1850 unregisterNetworkCallback(l.networkCallback);
1851 l.clearDnsBinding();
1852 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001853 }
1854
Erik Klinece55eb12017-01-26 18:08:28 +09001855 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1856 static {
1857 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1858 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1859 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1860 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1861 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1862 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1863 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1864 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1865 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1866 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1867 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1868 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1869 }
1870
1871 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1872 static {
1873 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1874 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1875 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1876 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1877 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1878 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1879 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1880 }
1881
1882 /**
1883 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1884 * instance suitable for registering a request or callback. Throws an
1885 * IllegalArgumentException if no mapping from the legacy type to
1886 * NetworkCapabilities is known.
1887 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001888 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1889 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001890 * @hide
1891 */
1892 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1893 final NetworkCapabilities nc = new NetworkCapabilities();
1894
1895 // Map from type to transports.
1896 final int NOT_FOUND = -1;
1897 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00001898 if (transport == NOT_FOUND) {
1899 throw new IllegalArgumentException("unknown legacy type: " + type);
1900 }
Erik Klinece55eb12017-01-26 18:08:28 +09001901 nc.addTransportType(transport);
1902
1903 // Map from type to capabilities.
1904 nc.addCapability(sLegacyTypeToCapability.get(
1905 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1906 nc.maybeMarkCapabilitiesRestricted();
1907 return nc;
1908 }
1909
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001910 /** @hide */
1911 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001912 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001913 public PacketKeepaliveCallback() {
1914 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001915 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001916 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001917 public void onStarted() {}
1918 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001919 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001920 public void onStopped() {}
1921 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001922 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001923 public void onError(int error) {}
1924 }
1925
1926 /**
1927 * Allows applications to request that the system periodically send specific packets on their
1928 * behalf, using hardware offload to save battery power.
1929 *
1930 * To request that the system send keepalives, call one of the methods that return a
1931 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1932 * passing in a non-null callback. If the callback is successfully started, the callback's
1933 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1934 * specifying one of the {@code ERROR_*} constants in this class.
1935 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001936 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1937 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1938 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001939 *
junyulai4c95b082018-12-27 17:25:29 +08001940 * @deprecated Use {@link SocketKeepalive} instead.
1941 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001942 * @hide
1943 */
1944 public class PacketKeepalive {
1945
1946 private static final String TAG = "PacketKeepalive";
1947
1948 /** @hide */
1949 public static final int SUCCESS = 0;
1950
1951 /** @hide */
1952 public static final int NO_KEEPALIVE = -1;
1953
1954 /** @hide */
1955 public static final int BINDER_DIED = -10;
1956
1957 /** The specified {@code Network} is not connected. */
1958 public static final int ERROR_INVALID_NETWORK = -20;
1959 /** The specified IP addresses are invalid. For example, the specified source IP address is
1960 * not configured on the specified {@code Network}. */
1961 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1962 /** The requested port is invalid. */
1963 public static final int ERROR_INVALID_PORT = -22;
1964 /** The packet length is invalid (e.g., too long). */
1965 public static final int ERROR_INVALID_LENGTH = -23;
1966 /** The packet transmission interval is invalid (e.g., too short). */
1967 public static final int ERROR_INVALID_INTERVAL = -24;
1968
1969 /** The hardware does not support this request. */
1970 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001971 /** The hardware returned an error. */
1972 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001973
Nathan Harold0990bc82018-02-14 13:09:45 -08001974 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001975 public static final int NATT_PORT = 4500;
1976
Nathan Harold0990bc82018-02-14 13:09:45 -08001977 /** The minimum interval in seconds between keepalive packet transmissions */
1978 public static final int MIN_INTERVAL = 10;
1979
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001980 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001981 private final ISocketKeepaliveCallback mCallback;
1982 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001983
1984 private volatile Integer mSlot;
1985
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001986 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001987 public void stop() {
1988 try {
junyulai070f9ff2019-01-16 20:23:34 +08001989 mExecutor.execute(() -> {
1990 try {
1991 if (mSlot != null) {
1992 mService.stopKeepalive(mNetwork, mSlot);
1993 }
1994 } catch (RemoteException e) {
1995 Log.e(TAG, "Error stopping packet keepalive: ", e);
1996 throw e.rethrowFromSystemServer();
1997 }
1998 });
1999 } catch (RejectedExecutionException e) {
2000 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002001 }
2002 }
2003
2004 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002005 Objects.requireNonNull(network, "network cannot be null");
2006 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002007 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08002008 mExecutor = Executors.newSingleThreadExecutor();
2009 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002010 @Override
junyulai070f9ff2019-01-16 20:23:34 +08002011 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08002012 final long token = Binder.clearCallingIdentity();
2013 try {
2014 mExecutor.execute(() -> {
2015 mSlot = slot;
2016 callback.onStarted();
2017 });
2018 } finally {
2019 Binder.restoreCallingIdentity(token);
2020 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002021 }
junyulai070f9ff2019-01-16 20:23:34 +08002022
2023 @Override
2024 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08002025 final long token = Binder.clearCallingIdentity();
2026 try {
2027 mExecutor.execute(() -> {
2028 mSlot = null;
2029 callback.onStopped();
2030 });
2031 } finally {
2032 Binder.restoreCallingIdentity(token);
2033 }
junyulai070f9ff2019-01-16 20:23:34 +08002034 mExecutor.shutdown();
2035 }
2036
2037 @Override
2038 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08002039 final long token = Binder.clearCallingIdentity();
2040 try {
2041 mExecutor.execute(() -> {
2042 mSlot = null;
2043 callback.onError(error);
2044 });
2045 } finally {
2046 Binder.restoreCallingIdentity(token);
2047 }
junyulai070f9ff2019-01-16 20:23:34 +08002048 mExecutor.shutdown();
2049 }
2050
2051 @Override
2052 public void onDataReceived() {
2053 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2054 // this callback when data is received.
2055 }
2056 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002057 }
2058 }
2059
2060 /**
2061 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2062 *
junyulai4c95b082018-12-27 17:25:29 +08002063 * @deprecated Use {@link #createSocketKeepalive} instead.
2064 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002065 * @hide
2066 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002067 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002068 public PacketKeepalive startNattKeepalive(
2069 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2070 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2071 final PacketKeepalive k = new PacketKeepalive(network, callback);
2072 try {
junyulai070f9ff2019-01-16 20:23:34 +08002073 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002074 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2075 } catch (RemoteException e) {
2076 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08002077 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002078 }
2079 return k;
2080 }
2081
Chiachang Wang619319a2021-01-15 11:06:21 +08002082 // Construct an invalid fd.
2083 private ParcelFileDescriptor createInvalidFd() {
2084 final int invalidFd = -1;
2085 return ParcelFileDescriptor.adoptFd(invalidFd);
2086 }
2087
The Android Open Source Project28527d22009-03-03 19:31:44 -08002088 /**
junyulai4c95b082018-12-27 17:25:29 +08002089 * Request that keepalives be started on a IPsec NAT-T socket.
2090 *
2091 * @param network The {@link Network} the socket is on.
2092 * @param socket The socket that needs to be kept alive.
2093 * @param source The source address of the {@link UdpEncapsulationSocket}.
2094 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2095 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2096 * must run callback sequentially, otherwise the order of callbacks cannot be
2097 * guaranteed.
2098 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2099 * changes. Must be extended by applications that use this API.
2100 *
junyulai0835a1e2019-01-08 20:04:33 +08002101 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2102 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08002103 **/
junyulai7e06ad42019-03-04 22:45:36 +08002104 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08002105 @NonNull UdpEncapsulationSocket socket,
2106 @NonNull InetAddress source,
2107 @NonNull InetAddress destination,
2108 @NonNull @CallbackExecutor Executor executor,
2109 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002110 ParcelFileDescriptor dup;
2111 try {
junyulai828dad12019-03-27 11:00:37 +08002112 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2113 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08002114 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2115 } catch (IOException ignored) {
2116 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2117 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002118 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002119 }
2120 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2121 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002122 }
2123
2124 /**
2125 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2126 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2127 *
2128 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002129 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2130 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2131 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002132 * @param source The source address of the {@link UdpEncapsulationSocket}.
2133 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2134 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2135 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2136 * must run callback sequentially, otherwise the order of callbacks cannot be
2137 * guaranteed.
2138 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2139 * changes. Must be extended by applications that use this API.
2140 *
junyulai0835a1e2019-01-08 20:04:33 +08002141 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2142 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002143 * @hide
2144 */
2145 @SystemApi
2146 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002147 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2148 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002149 @NonNull InetAddress source,
2150 @NonNull InetAddress destination,
2151 @NonNull @CallbackExecutor Executor executor,
2152 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002153 ParcelFileDescriptor dup;
2154 try {
junyulai828dad12019-03-27 11:00:37 +08002155 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002156 dup = pfd.dup();
2157 } catch (IOException ignored) {
2158 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2159 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002160 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002161 }
2162 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANce355502021-03-11 10:56:49 +00002163 -1 /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002164 }
2165
2166 /**
junyulai0835a1e2019-01-08 20:04:33 +08002167 * Request that keepalives be started on a TCP socket.
2168 * The socket must be established.
2169 *
2170 * @param network The {@link Network} the socket is on.
2171 * @param socket The socket that needs to be kept alive.
2172 * @param executor The executor on which callback will be invoked. This implementation assumes
2173 * the provided {@link Executor} runs the callbacks in sequence with no
2174 * concurrency. Failing this, no guarantee of correctness can be made. It is
2175 * the responsibility of the caller to ensure the executor provides this
2176 * guarantee. A simple way of creating such an executor is with the standard
2177 * tool {@code Executors.newSingleThreadExecutor}.
2178 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2179 * changes. Must be extended by applications that use this API.
2180 *
2181 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2182 * given socket.
2183 * @hide
2184 */
2185 @SystemApi
2186 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002187 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002188 @NonNull Socket socket,
2189 @NonNull Executor executor,
2190 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002191 ParcelFileDescriptor dup;
2192 try {
2193 dup = ParcelFileDescriptor.fromSocket(socket);
2194 } catch (UncheckedIOException ignored) {
2195 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2196 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002197 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002198 }
2199 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002200 }
2201
2202 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002203 * Ensure that a network route exists to deliver traffic to the specified
2204 * host via the specified network interface. An attempt to add a route that
2205 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002206 *
2207 * <p>This method requires the caller to hold either the
2208 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2209 * or the ability to modify system settings as determined by
2210 * {@link android.provider.Settings.System#canWrite}.</p>
2211 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002212 * @param networkType the type of the network over which traffic to the specified
2213 * host is to be routed
2214 * @param hostAddress the IP address of the host to which the route is desired
2215 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002216 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002217 * @deprecated Deprecated in favor of the
2218 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2219 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002220 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002221 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002222 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002223 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002224 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002225 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002226 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002227 }
2228
2229 /**
2230 * Ensure that a network route exists to deliver traffic to the specified
2231 * host via the specified network interface. An attempt to add a route that
2232 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002233 *
2234 * <p>This method requires the caller to hold either the
2235 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2236 * or the ability to modify system settings as determined by
2237 * {@link android.provider.Settings.System#canWrite}.</p>
2238 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002239 * @param networkType the type of the network over which traffic to the specified
2240 * host is to be routed
2241 * @param hostAddress the IP address of the host to which the route is desired
2242 * @return {@code true} on success, {@code false} on failure
2243 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002244 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002245 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002246 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002247 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002248 @UnsupportedAppUsage
lucasline257bce2021-03-22 11:51:27 +08002249 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002250 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002251 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002252 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002253 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2254 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002255 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002256 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002257 }
2258 }
2259
2260 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002261 * @return the context's attribution tag
2262 */
2263 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2264 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002265 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002266 }
2267
2268 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002269 * Returns the value of the setting for background data usage. If false,
2270 * applications should not use the network if the application is not in the
2271 * foreground. Developers should respect this setting, and check the value
2272 * of this before performing any background data operations.
2273 * <p>
2274 * All applications that have background services that use the network
2275 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002276 * <p>
Scott Main50589142011-10-06 18:32:43 -07002277 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002278 * background data depends on several combined factors, and this method will
2279 * always return {@code true}. Instead, when background data is unavailable,
2280 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002281 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002282 * @return Whether background data usage is allowed.
2283 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002284 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002285 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002286 // assume that background data is allowed; final authority is
2287 // NetworkInfo which may be blocked.
2288 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002289 }
2290
2291 /**
2292 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002293 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002294 * @param allowBackgroundData Whether an application should use data while
2295 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002296 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002297 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2298 * @see #getBackgroundDataSetting()
2299 * @hide
2300 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002301 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002302 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002303 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002304 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002305 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002306
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002307 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002308 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002309 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002310 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002311 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002312 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002313 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002314 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2315 if (tm != null) {
2316 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2317 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2318 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2319 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2320 + " retVal=" + retVal);
2321 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002322 }
Wink Saville689f7042014-12-05 11:10:30 -08002323 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002324 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002325 }
2326
The Android Open Source Project28527d22009-03-03 19:31:44 -08002327 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002328 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002329 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002330 */
2331 public interface OnNetworkActiveListener {
2332 /**
2333 * Called on the main thread of the process to report that the current data network
2334 * has become active, and it is now a good time to perform any pending network
2335 * operations. Note that this listener only tells you when the network becomes
2336 * active; if at any other time you want to know whether it is active (and thus okay
2337 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002338 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002339 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002340 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002341 }
2342
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002343 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002344 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002345
2346 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002347 * Start listening to reports when the system's default data network is active, meaning it is
2348 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2349 * to determine the current state of the system's default network after registering the
2350 * listener.
2351 * <p>
2352 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002353 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002354 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002355 *
2356 * @param l The listener to be told when the network is active.
2357 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002358 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002359 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2360 @Override
2361 public void onNetworkActive() throws RemoteException {
2362 l.onNetworkActive();
2363 }
2364 };
2365
2366 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002367 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002368 mNetworkActivityListeners.put(l, rl);
2369 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002370 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002371 }
2372 }
2373
2374 /**
2375 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002376 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002377 *
2378 * @param l Previously registered listener.
2379 */
Chalard Jean158702d2019-01-07 19:26:34 +09002380 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002381 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002382 if (rl == null) {
2383 throw new IllegalArgumentException("Listener was not registered.");
2384 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002385 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002386 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002387 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002388 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002389 }
2390 }
2391
2392 /**
2393 * Return whether the data network is currently active. An active network means that
2394 * it is currently in a high power state for performing data transmission. On some
2395 * types of networks, it may be expensive to move and stay in such a state, so it is
2396 * more power efficient to batch network traffic together when the radio is already in
2397 * this state. This method tells you whether right now is currently a good time to
2398 * initiate network traffic, as the network is already active.
2399 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002400 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002401 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002402 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002403 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002404 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002405 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002406 }
2407
2408 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002409 * {@hide}
2410 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002411 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002412 mContext = Objects.requireNonNull(context, "missing context");
2413 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002414 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002415 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002416 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002417
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002418 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002419 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002420 public static ConnectivityManager from(Context context) {
2421 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2422 }
2423
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002424 /** @hide */
2425 public NetworkRequest getDefaultRequest() {
2426 try {
2427 // This is not racy as the default request is final in ConnectivityService.
2428 return mService.getDefaultRequest();
2429 } catch (RemoteException e) {
2430 throw e.rethrowFromSystemServer();
2431 }
2432 }
2433
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002434 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002435 * Check if the package is a allowed to write settings. This also accounts that such an access
2436 * happened.
2437 *
2438 * @return {@code true} iff the package is allowed to write settings.
2439 */
2440 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2441 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2442 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2443 boolean throwException) {
2444 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2445 throwException);
2446 }
2447
2448 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002449 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2450 * situations where a Context pointer is unavailable.
2451 * @hide
2452 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002453 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002454 static ConnectivityManager getInstanceOrNull() {
2455 return sInstance;
2456 }
2457
2458 /**
2459 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2460 * situations where a Context pointer is unavailable.
2461 * @hide
2462 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002463 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002464 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002465 private static ConnectivityManager getInstance() {
2466 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002467 throw new IllegalStateException("No ConnectivityManager yet constructed");
2468 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002469 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002470 }
2471
2472 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002473 * Get the set of tetherable, available interfaces. This list is limited by
2474 * device configuration and current interface existence.
2475 *
2476 * @return an array of 0 or more Strings of tetherable interface names.
2477 *
markchien6ae63e52020-01-21 13:11:06 +08002478 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002479 * {@hide}
2480 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002481 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002482 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002483 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002484 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002485 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002486 }
2487
2488 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002489 * Get the set of tethered interfaces.
2490 *
2491 * @return an array of 0 or more String of currently tethered interface names.
2492 *
markchien6ae63e52020-01-21 13:11:06 +08002493 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002494 * {@hide}
2495 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002496 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002497 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002498 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002499 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002500 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002501 }
2502
2503 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002504 * Get the set of interface names which attempted to tether but
2505 * failed. Re-attempting to tether may cause them to reset to the Tethered
2506 * state. Alternatively, causing the interface to be destroyed and recreated
2507 * may cause them to reset to the available state.
2508 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2509 * information on the cause of the errors.
2510 *
2511 * @return an array of 0 or more String indicating the interface names
2512 * which failed to tether.
2513 *
markchien6ae63e52020-01-21 13:11:06 +08002514 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002515 * {@hide}
2516 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002517 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002518 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002519 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002520 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002521 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002522 }
2523
2524 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002525 * Get the set of tethered dhcp ranges.
2526 *
markchien2e6ba522020-02-14 11:55:48 +08002527 * @deprecated This method is not supported.
2528 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002529 * {@hide}
2530 */
paulhu8e96a752019-08-12 16:25:11 +08002531 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002532 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002533 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002534 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002535 }
2536
2537 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002538 * Attempt to tether the named interface. This will setup a dhcp server
2539 * on the interface, forward and NAT IP packets and forward DNS requests
2540 * to the best active upstream network interface. Note that if no upstream
2541 * IP network interface is available, dhcp will still run and traffic will be
2542 * allowed between the tethered devices and this device, though upstream net
2543 * access will of course fail until an upstream network interface becomes
2544 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002545 *
2546 * <p>This method requires the caller to hold either the
2547 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2548 * or the ability to modify system settings as determined by
2549 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002550 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002551 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2552 * and WifiStateMachine which need direct access. All other clients should use
2553 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2554 * logic.</p>
2555 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002556 * @param iface the interface name to tether.
2557 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002558 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002559 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002560 * {@hide}
2561 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002562 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002563 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002564 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002565 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002566 }
2567
2568 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002569 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002570 *
2571 * <p>This method requires the caller to hold either the
2572 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2573 * or the ability to modify system settings as determined by
2574 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002575 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002576 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2577 * and WifiStateMachine which need direct access. All other clients should use
2578 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2579 * logic.</p>
2580 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002581 * @param iface the interface name to untether.
2582 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2583 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002584 * {@hide}
2585 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002586 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002587 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002588 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002589 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002590 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002591
2592 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002593 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002594 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002595 * due to device configuration.
2596 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002597 * <p>If this app does not have permission to use this API, it will always
2598 * return false rather than throw an exception.</p>
2599 *
2600 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2601 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2602 *
2603 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2604 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2605 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002606 * @return a boolean - {@code true} indicating Tethering is supported.
2607 *
markchien6ae63e52020-01-21 13:11:06 +08002608 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002609 * {@hide}
2610 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002611 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002612 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2613 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002614 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002615 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002616 }
2617
2618 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002619 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002620 *
2621 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002622 * @hide
2623 */
2624 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002625 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002626 public static abstract class OnStartTetheringCallback {
2627 /**
2628 * Called when tethering has been successfully started.
2629 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002630 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002631
2632 /**
2633 * Called when starting tethering failed.
2634 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002635 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002636 }
2637
2638 /**
2639 * Convenient overload for
2640 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2641 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002642 *
2643 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002644 * @hide
2645 */
2646 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002647 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002648 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002649 public void startTethering(int type, boolean showProvisioningUi,
2650 final OnStartTetheringCallback callback) {
2651 startTethering(type, showProvisioningUi, callback, null);
2652 }
2653
2654 /**
2655 * Runs tether provisioning for the given type if needed and then starts tethering if
2656 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2657 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2658 * schedules tether provisioning re-checks if appropriate.
2659 *
2660 * @param type The type of tethering to start. Must be one of
2661 * {@link ConnectivityManager.TETHERING_WIFI},
2662 * {@link ConnectivityManager.TETHERING_USB}, or
2663 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2664 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2665 * is one. This should be true the first time this function is called and also any time
2666 * the user can see this UI. It gives users information from their carrier about the
2667 * check failing and how they can sign up for tethering if possible.
2668 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2669 * of the result of trying to tether.
2670 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002671 *
2672 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002673 * @hide
2674 */
2675 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002676 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002677 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002678 public void startTethering(int type, boolean showProvisioningUi,
2679 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002680 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002681
markchien91c78e52020-01-20 19:31:56 +08002682 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002683 @Override
markchien91c78e52020-01-20 19:31:56 +08002684 public void execute(Runnable command) {
2685 if (handler == null) {
2686 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002687 } else {
markchien91c78e52020-01-20 19:31:56 +08002688 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002689 }
2690 }
2691 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002692
markchien91c78e52020-01-20 19:31:56 +08002693 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2694 @Override
2695 public void onTetheringStarted() {
2696 callback.onTetheringStarted();
2697 }
2698
2699 @Override
markchienf47d8342020-03-19 13:37:43 +08002700 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002701 callback.onTetheringFailed();
2702 }
2703 };
2704
2705 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002706 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002707
Amos Bianchia9b415a2020-03-04 11:07:38 -08002708 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002709 }
2710
2711 /**
2712 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2713 * applicable.
2714 *
2715 * @param type The type of tethering to stop. Must be one of
2716 * {@link ConnectivityManager.TETHERING_WIFI},
2717 * {@link ConnectivityManager.TETHERING_USB}, or
2718 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002719 *
2720 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002721 * @hide
2722 */
2723 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002724 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002725 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002726 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002727 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002728 }
2729
2730 /**
markchien4ef53e82019-02-27 14:56:11 +08002731 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2732 * upstream status.
2733 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002734 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002735 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002736 */
2737 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002738 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002739 public abstract static class OnTetheringEventCallback {
2740
2741 /**
2742 * Called when tethering upstream changed. This can be called multiple times and can be
2743 * called any time.
2744 *
2745 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2746 * have any upstream.
2747 */
2748 public void onUpstreamChanged(@Nullable Network network) {}
2749 }
2750
markchien6ae63e52020-01-21 13:11:06 +08002751 @GuardedBy("mTetheringEventCallbacks")
2752 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2753 mTetheringEventCallbacks = new ArrayMap<>();
2754
markchien4ef53e82019-02-27 14:56:11 +08002755 /**
2756 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002757 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002758 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2759 * with a null argument. The same callback object cannot be registered twice.
2760 *
2761 * @param executor the executor on which callback will be invoked.
2762 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002763 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002764 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002765 * @hide
2766 */
2767 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002768 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002769 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2770 public void registerTetheringEventCallback(
2771 @NonNull @CallbackExecutor Executor executor,
2772 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002773 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchien4ef53e82019-02-27 14:56:11 +08002774
markchien6ae63e52020-01-21 13:11:06 +08002775 final TetheringEventCallback tetherCallback =
2776 new TetheringEventCallback() {
2777 @Override
2778 public void onUpstreamChanged(@Nullable Network network) {
2779 callback.onUpstreamChanged(network);
2780 }
2781 };
2782
2783 synchronized (mTetheringEventCallbacks) {
2784 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002785 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002786 }
markchien4ef53e82019-02-27 14:56:11 +08002787 }
2788
2789 /**
2790 * Remove tethering event callback previously registered with
2791 * {@link #registerTetheringEventCallback}.
2792 *
2793 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002794 *
2795 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002796 * @hide
2797 */
2798 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002799 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002800 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2801 public void unregisterTetheringEventCallback(
2802 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002803 Objects.requireNonNull(callback, "The callback must be non-null");
2804 synchronized (mTetheringEventCallbacks) {
2805 final TetheringEventCallback tetherCallback =
2806 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002807 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002808 }
markchien4ef53e82019-02-27 14:56:11 +08002809 }
2810
2811
2812 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002813 * Get the list of regular expressions that define any tetherable
2814 * USB network interfaces. If USB tethering is not supported by the
2815 * device, this list should be empty.
2816 *
2817 * @return an array of 0 or more regular expression Strings defining
2818 * what interfaces are considered tetherable usb interfaces.
2819 *
markchien6ae63e52020-01-21 13:11:06 +08002820 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002821 * {@hide}
2822 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002823 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002824 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002825 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002826 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002827 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002828 }
2829
2830 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002831 * Get the list of regular expressions that define any tetherable
2832 * Wifi network interfaces. If Wifi tethering is not supported by the
2833 * device, this list should be empty.
2834 *
2835 * @return an array of 0 or more regular expression Strings defining
2836 * what interfaces are considered tetherable wifi interfaces.
2837 *
markchien6ae63e52020-01-21 13:11:06 +08002838 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002839 * {@hide}
2840 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002841 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002842 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002843 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002844 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002845 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002846 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002847
Danica Chang96567052010-08-11 14:54:43 -07002848 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002849 * Get the list of regular expressions that define any tetherable
2850 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2851 * device, this list should be empty.
2852 *
2853 * @return an array of 0 or more regular expression Strings defining
2854 * what interfaces are considered tetherable bluetooth interfaces.
2855 *
markchien6ae63e52020-01-21 13:11:06 +08002856 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2857 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002858 * {@hide}
2859 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002860 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002861 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002862 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002863 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002864 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002865 }
2866
Mike Lockwooded4a1742011-07-19 13:04:47 -07002867 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002868 * Attempt to both alter the mode of USB and Tethering of USB. A
2869 * utility method to deal with some of the complexity of USB - will
2870 * attempt to switch to Rndis and subsequently tether the resulting
2871 * interface on {@code true} or turn off tethering and switch off
2872 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002873 *
2874 * <p>This method requires the caller to hold either the
2875 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2876 * or the ability to modify system settings as determined by
2877 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002878 *
2879 * @param enable a boolean - {@code true} to enable tethering
2880 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002881 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002882 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002883 * {@hide}
2884 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002885 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002886 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002887 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002888 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002889 }
2890
markchien6ae63e52020-01-21 13:11:06 +08002891 /**
2892 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2893 * {@hide}
2894 */
markchien0f45bb92019-01-16 17:44:13 +08002895 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002896 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002897 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002898 /**
2899 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2900 * {@hide}
2901 */
2902 @Deprecated
2903 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2904 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2905 /**
2906 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2907 * {@hide}
2908 */
2909 @Deprecated
2910 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2911 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2912 /**
2913 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2914 * {@hide}
2915 */
2916 @Deprecated
2917 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2918 /**
2919 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2920 * {@hide}
2921 */
2922 @Deprecated
2923 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2924 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2925 /**
markchienf47d8342020-03-19 13:37:43 +08002926 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002927 * {@hide}
2928 */
2929 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002930 public static final int TETHER_ERROR_MASTER_ERROR =
2931 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002932 /**
2933 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2934 * {@hide}
2935 */
2936 @Deprecated
2937 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2938 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2939 /**
2940 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2941 * {@hide}
2942 */
2943 @Deprecated
2944 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2945 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2946 /**
markchienf47d8342020-03-19 13:37:43 +08002947 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002948 * {@hide}
2949 */
2950 @Deprecated
2951 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002952 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002953 /**
markchienf47d8342020-03-19 13:37:43 +08002954 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002955 * {@hide}
2956 */
2957 @Deprecated
2958 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002959 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002960 /**
2961 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2962 * {@hide}
2963 */
2964 @Deprecated
2965 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2966 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2967 /**
markchienf47d8342020-03-19 13:37:43 +08002968 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002969 * {@hide}
2970 */
markchien0f45bb92019-01-16 17:44:13 +08002971 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002972 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002973 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002974 /**
2975 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2976 * {@hide}
2977 */
2978 @Deprecated
2979 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2980 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2981 /**
2982 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2983 * {@hide}
2984 */
markchien0f45bb92019-01-16 17:44:13 +08002985 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002986 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002987 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002988
2989 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002990 * Get a more detailed error code after a Tethering or Untethering
2991 * request asynchronously failed.
2992 *
2993 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002994 * @return error The error code of the last error tethering or untethering the named
2995 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002996 *
markchien6ae63e52020-01-21 13:11:06 +08002997 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002998 * {@hide}
2999 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003000 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00003001 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08003002 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003003 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08003004 int error = mTetheringManager.getLastTetherError(iface);
3005 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3006 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3007 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3008 // instead.
3009 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3010 }
3011 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003012 }
3013
markchienbf5ab012019-03-06 16:25:00 +08003014 /** @hide */
3015 @Retention(RetentionPolicy.SOURCE)
3016 @IntDef(value = {
3017 TETHER_ERROR_NO_ERROR,
3018 TETHER_ERROR_PROVISION_FAILED,
3019 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3020 })
3021 public @interface EntitlementResultCode {
3022 }
3023
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003024 /**
markchienbf5ab012019-03-06 16:25:00 +08003025 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08003026 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08003027 *
3028 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08003029 * @hide
3030 */
3031 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08003032 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08003033 public interface OnTetheringEntitlementResultListener {
3034 /**
3035 * Called to notify entitlement result.
3036 *
3037 * @param resultCode an int value of entitlement result. It may be one of
3038 * {@link #TETHER_ERROR_NO_ERROR},
3039 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3040 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3041 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07003042 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08003043 }
3044
3045 /**
markchien0f45bb92019-01-16 17:44:13 +08003046 * Get the last value of the entitlement check on this downstream. If the cached value is
3047 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3048 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3049 * guaranteed that the UI-based entitlement check will complete in any specific time period
3050 * and may in fact never complete. Any successful entitlement check the platform performs for
3051 * any reason will update the cached value.
3052 *
3053 * @param type the downstream type of tethering. Must be one of
3054 * {@link #TETHERING_WIFI},
3055 * {@link #TETHERING_USB}, or
3056 * {@link #TETHERING_BLUETOOTH}.
3057 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08003058 * @param executor the executor on which callback will be invoked.
3059 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3060 * notify the caller of the result of entitlement check. The listener may be called zero
3061 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08003062 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08003063 * {@hide}
3064 */
3065 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08003066 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08003067 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08003068 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3069 @NonNull @CallbackExecutor Executor executor,
3070 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003071 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchienbf5ab012019-03-06 16:25:00 +08003072 ResultReceiver wrappedListener = new ResultReceiver(null) {
3073 @Override
3074 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08003075 final long token = Binder.clearCallingIdentity();
3076 try {
3077 executor.execute(() -> {
3078 listener.onTetheringEntitlementResult(resultCode);
3079 });
3080 } finally {
3081 Binder.restoreCallingIdentity(token);
3082 }
markchienbf5ab012019-03-06 16:25:00 +08003083 }
3084 };
3085
Amos Bianchia9b415a2020-03-04 11:07:38 -08003086 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08003087 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08003088 }
3089
3090 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003091 * Report network connectivity status. This is currently used only
3092 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003093 * <p>This method requires the caller to hold the permission
3094 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003095 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003096 * @param networkType The type of network you want to report on
3097 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003098 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003099 * {@hide}
3100 */
3101 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003102 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003103 try {
3104 mService.reportInetCondition(networkType, percentage);
3105 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003106 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003107 }
3108 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003109
3110 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003111 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003112 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003113 * the framework to re-evaluate network connectivity and/or switch to another
3114 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003115 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003116 * @param network The {@link Network} the application was attempting to use
3117 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003118 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3119 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003120 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003121 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003122 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003123 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003124 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003125 // One of these will be ignored because it matches system's current state.
3126 // The other will trigger the necessary reevaluation.
3127 mService.reportNetworkConnectivity(network, true);
3128 mService.reportNetworkConnectivity(network, false);
3129 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003130 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003131 }
3132 }
3133
3134 /**
3135 * Report to the framework whether a network has working connectivity.
3136 * This provides a hint to the system that a particular network is providing
3137 * working connectivity or not. In response the framework may re-evaluate
3138 * the network's connectivity and might take further action thereafter.
3139 *
3140 * @param network The {@link Network} the application was attempting to use
3141 * or {@code null} to indicate the current default network.
3142 * @param hasConnectivity {@code true} if the application was able to successfully access the
3143 * Internet using {@code network} or {@code false} if not.
3144 */
Chalard Jean158702d2019-01-07 19:26:34 +09003145 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003146 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003147 try {
3148 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003149 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003150 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003151 }
3152 }
3153
3154 /**
Chalard Jean48d60ea2021-03-17 17:03:34 +09003155 * Set a network-independent global HTTP proxy.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003156 *
Chalard Jean48d60ea2021-03-17 17:03:34 +09003157 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3158 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3159 * accessing any network, regardless of what the settings for that network are.
3160 *
3161 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3162 * proxy is likely to break networking on multiple networks. This method is only meant
3163 * for device policy clients looking to do general internal filtering or similar use cases.
3164 *
3165 * {@see #getGlobalProxy}
3166 * {@see LinkProperties#getHttpProxy}
3167 *
3168 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3169 * method with a {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003170 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003171 */
Chalard Jean48d60ea2021-03-17 17:03:34 +09003172 // Used by Device Policy Manager to set the global proxy.
Chiachang Wang4d513572021-03-18 09:44:34 +08003173 @SystemApi(client = MODULE_LIBRARIES)
paulhu8e96a752019-08-12 16:25:11 +08003174 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean48d60ea2021-03-17 17:03:34 +09003175 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003176 try {
3177 mService.setGlobalProxy(p);
3178 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003179 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003180 }
3181 }
3182
3183 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003184 * Retrieve any network-independent global HTTP proxy.
3185 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003186 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003187 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003188 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003189 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003190 @SystemApi(client = MODULE_LIBRARIES)
3191 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04003192 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003193 try {
3194 return mService.getGlobalProxy();
3195 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003196 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003197 }
3198 }
3199
3200 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003201 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3202 * network-specific HTTP proxy. If {@code network} is null, the
3203 * network-specific proxy returned is the proxy of the default active
3204 * network.
3205 *
3206 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3207 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3208 * or when {@code network} is {@code null},
3209 * the {@code ProxyInfo} for the default active network. Returns
3210 * {@code null} when no proxy applies or the caller doesn't have
3211 * permission to use {@code network}.
3212 * @hide
3213 */
3214 public ProxyInfo getProxyForNetwork(Network network) {
3215 try {
3216 return mService.getProxyForNetwork(network);
3217 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003218 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003219 }
3220 }
3221
3222 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003223 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3224 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003225 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003226 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003227 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003228 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003229 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003230 */
Chalard Jean158702d2019-01-07 19:26:34 +09003231 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003232 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003233 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003234 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003235
3236 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003237 * Returns true if the hardware supports the given network type
3238 * else it returns false. This doesn't indicate we have coverage
3239 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003240 * hardware supports it. For example a GSM phone without a SIM
3241 * should still return {@code true} for mobile data, but a wifi only
3242 * tablet would return {@code false}.
3243 *
3244 * @param networkType The network type we'd like to check
3245 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003246 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003247 * @hide
3248 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003249 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003250 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003251 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003252 public boolean isNetworkSupported(int networkType) {
3253 try {
3254 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003255 } catch (RemoteException e) {
3256 throw e.rethrowFromSystemServer();
3257 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003258 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003259
3260 /**
3261 * Returns if the currently active data network is metered. A network is
3262 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003263 * that connection due to monetary costs, data limitations or
3264 * battery/performance issues. You should check this before doing large
3265 * data transfers, and warn the user or delay the operation until another
3266 * network is available.
3267 *
3268 * @return {@code true} if large transfers should be avoided, otherwise
3269 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003270 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003271 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003272 public boolean isActiveNetworkMetered() {
3273 try {
3274 return mService.isActiveNetworkMetered();
3275 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003276 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003277 }
3278 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003279
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003280 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003281 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003282 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003283 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003284 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003285 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003286 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003287 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003288 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003289 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003290 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003291 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003292 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003293 }
3294 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003295
3296 /**
3297 * Set the value for enabling/disabling airplane mode
3298 *
3299 * @param enable whether to enable airplane mode or not
3300 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003301 * @hide
3302 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003303 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003304 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003305 android.Manifest.permission.NETWORK_SETTINGS,
3306 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3307 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003308 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003309 public void setAirplaneMode(boolean enable) {
3310 try {
3311 mService.setAirplaneMode(enable);
3312 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003313 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003314 }
3315 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003316
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003317 /**
3318 * Registers the specified {@link NetworkProvider}.
3319 * Each listener must only be registered once. The listener can be unregistered with
3320 * {@link #unregisterNetworkProvider}.
3321 *
3322 * @param provider the provider to register
3323 * @return the ID of the provider. This ID must be used by the provider when registering
3324 * {@link android.net.NetworkAgent}s.
3325 * @hide
3326 */
3327 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003328 @RequiresPermission(anyOf = {
3329 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3330 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003331 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3332 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003333 throw new IllegalStateException("NetworkProviders can only be registered once");
3334 }
3335
3336 try {
3337 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3338 provider.getName());
3339 provider.setProviderId(providerId);
3340 } catch (RemoteException e) {
3341 throw e.rethrowFromSystemServer();
3342 }
3343 return provider.getProviderId();
3344 }
3345
3346 /**
3347 * Unregisters the specified NetworkProvider.
3348 *
3349 * @param provider the provider to unregister
3350 * @hide
3351 */
3352 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003353 @RequiresPermission(anyOf = {
3354 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3355 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003356 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3357 try {
3358 mService.unregisterNetworkProvider(provider.getMessenger());
3359 } catch (RemoteException e) {
3360 throw e.rethrowFromSystemServer();
3361 }
3362 provider.setProviderId(NetworkProvider.ID_NONE);
3363 }
3364
3365
3366 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003367 @RequiresPermission(anyOf = {
3368 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3369 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003370 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3371 try {
3372 mService.declareNetworkRequestUnfulfillable(request);
3373 } catch (RemoteException e) {
3374 throw e.rethrowFromSystemServer();
3375 }
3376 }
3377
Paul Jensen1f567382015-02-13 14:18:39 -05003378 /**
3379 * @hide
3380 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003381 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003382 */
paulhub6ba8e82020-03-04 09:43:41 +08003383 @RequiresPermission(anyOf = {
3384 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3385 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003386 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jean28018572020-12-21 18:36:52 +09003387 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3388 int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003389 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003390 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003391 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003392 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003393 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003394 }
3395
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003396 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003397 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3398 * changes. Should be extended by applications wanting notifications.
3399 *
3400 * A {@code NetworkCallback} is registered by calling
3401 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3402 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003403 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003404 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3405 * A {@code NetworkCallback} should be registered at most once at any time.
3406 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003407 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003408 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003409 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003410 * No flags associated with this callback.
3411 * @hide
3412 */
3413 public static final int FLAG_NONE = 0;
3414 /**
3415 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3416 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3417 * <p>
3418 * These include:
3419 * <li> Some transport info instances (retrieved via
3420 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3421 * contain location sensitive information.
3422 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3423 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3424 * </p>
3425 * <p>
3426 * Note:
3427 * <li> Retrieving this location sensitive information (subject to app's location
3428 * permissions) will be noted by system. </li>
3429 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3430 * not include location sensitive info.
3431 * </p>
3432 */
Roshan Piuse1220262021-03-11 21:16:44 -08003433 // Note: Some existing fields which are location sensitive may still be included without
3434 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Pius951c0032020-12-22 15:10:42 -08003435 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3436
3437 /** @hide */
3438 @Retention(RetentionPolicy.SOURCE)
3439 @IntDef(flag = true, prefix = "FLAG_", value = {
3440 FLAG_NONE,
3441 FLAG_INCLUDE_LOCATION_INFO
3442 })
3443 public @interface Flag { }
3444
3445 /**
3446 * All the valid flags for error checking.
3447 */
3448 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3449
3450 public NetworkCallback() {
3451 this(FLAG_NONE);
3452 }
3453
3454 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003455 if ((flags & VALID_FLAGS) != flags) {
3456 throw new IllegalArgumentException("Invalid flags");
3457 }
Roshan Pius951c0032020-12-22 15:10:42 -08003458 mFlags = flags;
3459 }
3460
3461 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003462 * Called when the framework connects to a new network to evaluate whether it satisfies this
3463 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3464 * callback. There is no guarantee that this new network will satisfy any requests, or that
3465 * the network will stay connected for longer than the time necessary to evaluate it.
3466 * <p>
3467 * Most applications <b>should not</b> act on this callback, and should instead use
3468 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3469 * the framework in properly evaluating the network &mdash; for example, an application that
3470 * can automatically log in to a captive portal without user intervention.
3471 *
3472 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003473 *
3474 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003475 */
paulhu1a407652019-03-22 16:35:06 +08003476 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003477
3478 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003479 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003480 * This callback may be called more than once if the {@link Network} that is
3481 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003482 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003483 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003484 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3485 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003486 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003487 * @hide
3488 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003489 public final void onAvailable(@NonNull Network network,
paulhu1a407652019-03-22 16:35:06 +08003490 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003491 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003492 // Internally only this method is called when a new network is available, and
3493 // it calls the callback in the same way and order that older versions used
3494 // to call so as not to change the behavior.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003495 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3496 onBlockedStatusChanged(network, blocked);
3497 }
3498
3499 /**
3500 * Legacy variant of onAvailable that takes a boolean blocked reason.
3501 *
3502 * This method has never been public API, but it's not final, so there may be apps that
3503 * implemented it and rely on it being called. Do our best not to break them.
3504 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3505 * this method is called. There does not seem to be a way to avoid this.
3506 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3507 *
3508 * @hide
3509 */
3510 public void onAvailable(@NonNull Network network,
3511 @NonNull NetworkCapabilities networkCapabilities,
3512 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003513 onAvailable(network);
3514 if (!networkCapabilities.hasCapability(
3515 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3516 onNetworkSuspended(network);
3517 }
3518 onCapabilitiesChanged(network, networkCapabilities);
3519 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003520 // No call to onBlockedStatusChanged here. That is done by the caller.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003521 }
3522
3523 /**
3524 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003525 *
3526 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3527 * be available at the same time, and onAvailable will be called for each of these as they
3528 * appear.
3529 *
3530 * <p>For callbacks registered with {@link #requestNetwork} and
3531 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3532 * is the new best network for this request and is now tracked by this callback ; this
3533 * callback will no longer receive method calls about other networks that may have been
3534 * passed to this method previously. The previously-best network may have disconnected, or
3535 * it may still be around and the newly-best network may simply be better.
3536 *
3537 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3538 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3539 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3540 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3541 *
3542 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3543 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3544 * this callback as this is prone to race conditions (there is no guarantee the objects
3545 * returned by these methods will be current). Instead, wait for a call to
3546 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3547 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3548 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003549 *
3550 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003551 */
paulhu1a407652019-03-22 16:35:06 +08003552 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003553
3554 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003555 * Called when the network is about to be lost, typically because there are no outstanding
3556 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3557 * with the new replacement network for graceful handover. This method is not guaranteed
3558 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3559 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003560 *
Chalard Jean01378b62019-08-30 16:27:28 +09003561 * <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.
3565 *
3566 * @param network The {@link Network} that is about to be lost.
3567 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3568 * connected for graceful handover; note that the network may still
3569 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003570 */
paulhu1a407652019-03-22 16:35:06 +08003571 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003572
3573 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003574 * Called when a network disconnects or otherwise no longer satisfies this request or
3575 * callback.
3576 *
3577 * <p>If the callback was registered with requestNetwork() or
3578 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3579 * returned by onAvailable() when that network is lost and no other network satisfies
3580 * the criteria of the request.
3581 *
3582 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3583 * each network which no longer satisfies the criteria of the callback.
3584 *
3585 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3586 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3587 * this callback as this is prone to race conditions ; calling these methods while in a
3588 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003589 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003590 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003591 */
paulhu1a407652019-03-22 16:35:06 +08003592 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003593
3594 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003595 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003596 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3597 * requested network request cannot be fulfilled (whether or not a timeout was
3598 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003599 * {@link NetworkRequest} will have already been removed and released, as if
3600 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003601 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003602 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003603
3604 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003605 * Called when the network corresponding to this request changes capabilities but still
3606 * satisfies the requested criteria.
3607 *
3608 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3609 * to be called immediately after {@link #onAvailable}.
3610 *
3611 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3612 * ConnectivityManager methods in this callback as this is prone to race conditions :
3613 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003614 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003615 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius951c0032020-12-22 15:10:42 -08003616 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003617 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003618 */
paulhu1a407652019-03-22 16:35:06 +08003619 public void onCapabilitiesChanged(@NonNull Network network,
3620 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003621
3622 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003623 * Called when the network corresponding to this request changes {@link LinkProperties}.
3624 *
3625 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3626 * to be called immediately after {@link #onAvailable}.
3627 *
3628 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3629 * ConnectivityManager methods in this callback as this is prone to race conditions :
3630 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003631 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003632 * @param network The {@link Network} whose link properties have changed.
3633 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003634 */
paulhu1a407652019-03-22 16:35:06 +08003635 public void onLinkPropertiesChanged(@NonNull Network network,
3636 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003637
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003638 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003639 * Called when the network the framework connected to for this request suspends data
3640 * transmission temporarily.
3641 *
3642 * <p>This generally means that while the TCP connections are still live temporarily
3643 * network data fails to transfer. To give a specific example, this is used on cellular
3644 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3645 * means read operations on sockets on this network will block once the buffers are
3646 * drained, and write operations will block once the buffers are full.
3647 *
3648 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3649 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3650 * this callback as this is prone to race conditions (there is no guarantee the objects
3651 * returned by these methods will be current).
3652 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003653 * @hide
3654 */
paulhu1a407652019-03-22 16:35:06 +08003655 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003656
3657 /**
3658 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003659 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3660 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003661
3662 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3663 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3664 * this callback as this is prone to race conditions : calling these methods while in a
3665 * callback may return an outdated or even a null object.
3666 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003667 * @hide
3668 */
paulhu1a407652019-03-22 16:35:06 +08003669 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003670
junyulaif2c67e42018-08-07 19:50:45 +08003671 /**
3672 * Called when access to the specified network is blocked or unblocked.
3673 *
Chalard Jean01378b62019-08-30 16:27:28 +09003674 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3675 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3676 * this callback as this is prone to race conditions : calling these methods while in a
3677 * callback may return an outdated or even a null object.
3678 *
junyulaif2c67e42018-08-07 19:50:45 +08003679 * @param network The {@link Network} whose blocked status has changed.
3680 * @param blocked The blocked status of this {@link Network}.
3681 */
junyulai7e06ad42019-03-04 22:45:36 +08003682 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003683
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003684 /**
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09003685 * Called when access to the specified network is blocked or unblocked, or the reason for
3686 * access being blocked changes.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003687 *
3688 * If a NetworkCallback object implements this method,
3689 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3690 *
3691 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3692 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3693 * this callback as this is prone to race conditions : calling these methods while in a
3694 * callback may return an outdated or even a null object.
3695 *
3696 * @param network The {@link Network} whose blocked status has changed.
3697 * @param blocked The blocked status of this {@link Network}.
3698 * @hide
3699 */
3700 @SystemApi(client = MODULE_LIBRARIES)
3701 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3702 onBlockedStatusChanged(network, blocked != 0);
3703 }
3704
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003705 private NetworkRequest networkRequest;
Roshan Pius951c0032020-12-22 15:10:42 -08003706 private final int mFlags;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003707 }
3708
Hugo Benichia590ab82017-05-11 13:16:17 +09003709 /**
3710 * Constant error codes used by ConnectivityService to communicate about failures and errors
3711 * across a Binder boundary.
3712 * @hide
3713 */
3714 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003715 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003716 }
3717
3718 /** @hide */
3719 public static class TooManyRequestsException extends RuntimeException {}
3720
3721 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3722 switch (e.errorCode) {
3723 case Errors.TOO_MANY_REQUESTS:
3724 return new TooManyRequestsException();
3725 default:
3726 Log.w(TAG, "Unknown service error code " + e.errorCode);
3727 return new RuntimeException(e);
3728 }
3729 }
3730
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003731 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003732 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003733 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003734 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003735 /** @hide arg1 = TTL */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003736 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003737 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003738 public static final int CALLBACK_LOST = 4;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003739 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003740 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003741 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003742 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003743 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003744 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003745 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003746 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003747 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003748 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003749 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003750 public static final int CALLBACK_RESUMED = 10;
junyulaif2c67e42018-08-07 19:50:45 +08003751 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003752 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003753
Erik Kline155a59a2015-11-25 12:49:38 +09003754 /** @hide */
3755 public static String getCallbackName(int whichCallback) {
3756 switch (whichCallback) {
3757 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3758 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3759 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3760 case CALLBACK_LOST: return "CALLBACK_LOST";
3761 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3762 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3763 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003764 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3765 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3766 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003767 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003768 default:
3769 return Integer.toString(whichCallback);
3770 }
3771 }
3772
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003773 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003774 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003775 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003776
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003777 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003778 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003779 }
3780
Hugo Benichifd44e912017-02-02 17:02:36 +09003781 CallbackHandler(Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003782 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003783 }
3784
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003785 @Override
3786 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003787 if (message.what == EXPIRE_LEGACY_REQUEST) {
3788 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3789 return;
3790 }
3791
3792 final NetworkRequest request = getObject(message, NetworkRequest.class);
3793 final Network network = getObject(message, Network.class);
3794 final NetworkCallback callback;
3795 synchronized (sCallbacks) {
3796 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003797 if (callback == null) {
3798 Log.w(TAG,
3799 "callback not found for " + getCallbackName(message.what) + " message");
3800 return;
3801 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003802 if (message.what == CALLBACK_UNAVAIL) {
3803 sCallbacks.remove(request);
3804 callback.networkRequest = ALREADY_UNREGISTERED;
3805 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003806 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003807 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003808 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003809 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003810
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003811 switch (message.what) {
3812 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003813 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003814 break;
3815 }
3816 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003817 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3818 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003819 callback.onAvailable(network, cap, lp, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003820 break;
3821 }
3822 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003823 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003824 break;
3825 }
3826 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003827 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003828 break;
3829 }
3830 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003831 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003832 break;
3833 }
3834 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003835 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3836 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003837 break;
3838 }
3839 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003840 LinkProperties lp = getObject(message, LinkProperties.class);
3841 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003842 break;
3843 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003844 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003845 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003846 break;
3847 }
3848 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003849 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003850 break;
3851 }
junyulaif2c67e42018-08-07 19:50:45 +08003852 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003853 callback.onBlockedStatusChanged(network, message.arg1);
junyulaif2c67e42018-08-07 19:50:45 +08003854 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003855 }
3856 }
3857
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003858 private <T> T getObject(Message msg, Class<T> c) {
3859 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003860 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003861 }
3862
Hugo Benichifd44e912017-02-02 17:02:36 +09003863 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003864 synchronized (sCallbacks) {
3865 if (sCallbackHandler == null) {
3866 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003867 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003868 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003869 }
3870 }
3871
Hugo Benichibc4ac972017-02-03 14:18:44 +09003872 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3873 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003874
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003875 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3876 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3877 CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003878 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003879 checkCallbackNotNull(callback);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003880 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3881 throw new IllegalArgumentException("null NetworkCapabilities");
3882 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003883 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003884 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003885 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003886 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003887 if (callback.networkRequest != null
3888 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003889 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3890 // and requests (http://b/20701525).
3891 Log.e(TAG, "NetworkCallback was already registered");
3892 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003893 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003894 Binder binder = new Binder();
Roshan Pius951c0032020-12-22 15:10:42 -08003895 final int callbackFlags = callback.mFlags;
junyulaiad010792021-01-11 16:53:38 +08003896 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003897 request = mService.listenForNetwork(
Roshan Pius951c0032020-12-22 15:10:42 -08003898 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003899 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003900 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003901 request = mService.requestNetwork(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003902 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3903 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003904 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003905 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003906 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003907 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003908 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003909 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003910 } catch (RemoteException e) {
3911 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003912 } catch (ServiceSpecificException e) {
3913 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003914 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003915 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003916 }
3917
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003918 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3919 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3920 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3921 legacyType, handler);
3922 }
3923
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003924 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003925 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003926 *
markchienfac84a22020-03-18 21:16:15 +08003927 * This API is only for use in internal system code that requests networks with legacy type and
3928 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003929 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003930 *
markchiend6eeffd2020-01-14 00:55:21 +08003931 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003932 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3933 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3934 * be a positive value (i.e. >0).
3935 * @param legacyType to specify the network type(#TYPE_*).
3936 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003937 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3938 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003939 *
3940 * @hide
3941 */
markchiend6eeffd2020-01-14 00:55:21 +08003942 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003943 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003944 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003945 int timeoutMs, int legacyType, @NonNull Handler handler,
3946 @NonNull NetworkCallback networkCallback) {
3947 if (legacyType == TYPE_NONE) {
3948 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3949 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003950 CallbackHandler cbHandler = new CallbackHandler(handler);
3951 NetworkCapabilities nc = request.networkCapabilities;
3952 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003953 }
3954
3955 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003956 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003957 *
Chalard Jean01378b62019-08-30 16:27:28 +09003958 * <p>This method will attempt to find the best network that matches the passed
3959 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3960 * criteria. The platform will evaluate which network is the best at its own discretion.
3961 * Throughput, latency, cost per byte, policy, user preference and other considerations
3962 * may be factored in the decision of what is considered the best network.
3963 *
3964 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3965 * matching this request, while always attempting to match the request to a better network if
3966 * possible. If a better match is found, the platform will switch this request to the now-best
3967 * network and inform the app of the newly best network by invoking
3968 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3969 * will not try to maintain any other network than the best one currently matching the request:
3970 * a network not matching any network request may be disconnected at any time.
3971 *
3972 * <p>For example, an application could use this method to obtain a connected cellular network
3973 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3974 * radio to consume additional power. Or, an application could inform the system that it wants
3975 * a network supporting sending MMSes and have the system let it know about the currently best
3976 * MMS-supporting network through the provided {@link NetworkCallback}.
3977 *
3978 * <p>The status of the request can be followed by listening to the various callbacks described
3979 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3980 * used to direct traffic to the network (although accessing some networks may be subject to
3981 * holding specific permissions). Callers will learn about the specific characteristics of the
3982 * network through
3983 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3984 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3985 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3986 * matching the request at any given time; therefore when a better network matching the request
3987 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3988 * with the new network after which no further updates are given about the previously-best
3989 * network, unless it becomes the best again at some later time. All callbacks are invoked
3990 * in order on the same thread, which by default is a thread created by the framework running
3991 * in the app.
3992 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3993 * callbacks are invoked.
3994 *
3995 * <p>This{@link NetworkRequest} will live until released via
3996 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3997 * which point the system may let go of the network at any time.
3998 *
3999 * <p>A version of this method which takes a timeout is
4000 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4001 * wait for a limited amount of time for the network to become unavailable.
4002 *
Paul Jensenee52d232015-06-16 15:11:58 -04004003 * <p>It is presently unsupported to request a network with mutable
4004 * {@link NetworkCapabilities} such as
4005 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4006 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4007 * as these {@code NetworkCapabilities} represent states that a particular
4008 * network may never attain, and whether a network will attain these states
4009 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09004010 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004011 *
4012 * <p>This method requires the caller to hold either the
4013 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4014 * or the ability to modify system settings as determined by
4015 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004016 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004017 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4018 * number of outstanding requests to 100 per app (identified by their UID), shared with
4019 * all variants of this method, of {@link #registerNetworkCallback} as well as
4020 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4021 * Requesting a network with this method will count toward this limit. If this limit is
4022 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4023 * make sure to unregister the callbacks with
4024 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4025 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004026 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09004027 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4028 * the callback must not be shared - it uniquely specifies this request.
4029 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09004030 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4031 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004032 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004033 */
Chalard Jean158702d2019-01-07 19:26:34 +09004034 public void requestNetwork(@NonNull NetworkRequest request,
4035 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004036 requestNetwork(request, networkCallback, getDefaultHandler());
4037 }
4038
4039 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004040 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichifd44e912017-02-02 17:02:36 +09004041 *
Chalard Jean01378b62019-08-30 16:27:28 +09004042 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4043 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09004044 *
Chalard Jean01378b62019-08-30 16:27:28 +09004045 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004046 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4047 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09004048 *
4049 * @param request {@link NetworkRequest} describing this request.
4050 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4051 * the callback must not be shared - it uniquely specifies this request.
4052 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09004053 */
Chalard Jean158702d2019-01-07 19:26:34 +09004054 public void requestNetwork(@NonNull NetworkRequest request,
4055 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004056 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08004057 NetworkCapabilities nc = request.networkCapabilities;
4058 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004059 }
4060
4061 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004062 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohenf67bde92017-03-01 12:47:28 -08004063 * by a timeout.
4064 *
4065 * This function behaves identically to the non-timed-out version
4066 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4067 * is not found within the given time (in milliseconds) the
4068 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4069 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4070 * not have to be released if timed-out (it is automatically released). Unregistering a
4071 * request that timed out is not an error.
4072 *
4073 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4074 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4075 * for that purpose. Calling this method will attempt to bring up the requested network.
4076 *
Chalard Jean01378b62019-08-30 16:27:28 +09004077 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004078 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4079 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08004080 *
4081 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004082 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4083 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08004084 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4085 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4086 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08004087 */
Chalard Jean158702d2019-01-07 19:26:34 +09004088 public void requestNetwork(@NonNull NetworkRequest request,
4089 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09004090 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08004091 NetworkCapabilities nc = request.networkCapabilities;
4092 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4093 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09004094 }
4095
Hugo Benichifd44e912017-02-02 17:02:36 +09004096 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004097 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichifd44e912017-02-02 17:02:36 +09004098 * by a timeout.
4099 *
Chalard Jean01378b62019-08-30 16:27:28 +09004100 * This method behaves identically to
4101 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4102 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08004103 *
Chalard Jean01378b62019-08-30 16:27:28 +09004104 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004105 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4106 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09004107 *
4108 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08004109 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4110 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09004111 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004112 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4113 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004114 */
Chalard Jean158702d2019-01-07 19:26:34 +09004115 public void requestNetwork(@NonNull NetworkRequest request,
4116 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09004117 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09004118 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08004119 NetworkCapabilities nc = request.networkCapabilities;
4120 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004121 }
4122
4123 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004124 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004125 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004126 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08004127 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04004128 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4129 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004130 */
Erik Kline8a826212014-11-19 12:12:24 +09004131 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004132
4133 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004134 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004135 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004136 * {@link android.content.Intent#getParcelableExtra(String)}.
4137 */
Erik Kline8a826212014-11-19 12:12:24 +09004138 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004139
4140
4141 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004142 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004143 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004144 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004145 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004146 * the request may outlive the calling application and get called back when a suitable
4147 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004148 * <p>
4149 * The operation is an Intent broadcast that goes to a broadcast receiver that
4150 * you registered with {@link Context#registerReceiver} or through the
4151 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4152 * <p>
4153 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09004154 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4155 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004156 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004157 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004158 * Intent to reserve the network or it will be released shortly after the Intent
4159 * is processed.
4160 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04004161 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004162 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004163 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004164 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004165 * The request may be released normally by calling
4166 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04004167 * <p>It is presently unsupported to request a network with either
4168 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4169 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4170 * as these {@code NetworkCapabilities} represent states that a particular
4171 * network may never attain, and whether a network will attain these states
4172 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09004173 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004174 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004175 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4176 * number of outstanding requests to 100 per app (identified by their UID), shared with
4177 * all variants of this method, of {@link #registerNetworkCallback} as well as
4178 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4179 * Requesting a network with this method will count toward this limit. If this limit is
4180 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4181 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4182 * or {@link #releaseNetworkRequest(PendingIntent)}.
4183 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004184 * <p>This method requires the caller to hold either the
4185 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4186 * or the ability to modify system settings as determined by
4187 * {@link android.provider.Settings.System#canWrite}.</p>
4188 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004189 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004190 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004191 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004192 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004193 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4194 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004195 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004196 */
Chalard Jean158702d2019-01-07 19:26:34 +09004197 public void requestNetwork(@NonNull NetworkRequest request,
4198 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004199 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004200 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004201 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004202 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004203 request.networkCapabilities, operation, mContext.getOpPackageName(),
4204 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004205 } catch (RemoteException e) {
4206 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004207 } catch (ServiceSpecificException e) {
4208 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004209 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004210 }
4211
4212 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004213 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4214 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004215 * This method has the same behavior as
4216 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004217 * releasing network resources and disconnecting.
4218 *
4219 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4220 * PendingIntent passed to
4221 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4222 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4223 */
Chalard Jean158702d2019-01-07 19:26:34 +09004224 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004225 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004226 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004227 try {
4228 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004229 } catch (RemoteException e) {
4230 throw e.rethrowFromSystemServer();
4231 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004232 }
4233
Hugo Benichibc1104b2017-05-09 15:19:01 +09004234 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004235 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004236 }
4237
4238 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004239 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004240 }
4241
4242 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004243 if (timeoutMs <= 0) {
4244 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4245 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004246 }
4247
4248 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004249 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004250 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004251 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4252 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004253 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004254 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4255 * number of outstanding requests to 100 per app (identified by their UID), shared with
4256 * all variants of this method, of {@link #requestNetwork} as well as
4257 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4258 * Requesting a network with this method will count toward this limit. If this limit is
4259 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4260 * make sure to unregister the callbacks with
4261 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4262 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004263 * @param request {@link NetworkRequest} describing this request.
4264 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4265 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004266 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004267 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004268 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004269 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004270 public void registerNetworkCallback(@NonNull NetworkRequest request,
4271 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004272 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4273 }
4274
4275 /**
4276 * Registers to receive notifications about all networks which satisfy the given
4277 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004278 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4279 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004280 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004281 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4282 * number of outstanding requests to 100 per app (identified by their UID), shared with
4283 * all variants of this method, of {@link #requestNetwork} as well as
4284 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4285 * Requesting a network with this method will count toward this limit. If this limit is
4286 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4287 * make sure to unregister the callbacks with
4288 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4289 *
4290 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004291 * @param request {@link NetworkRequest} describing this request.
4292 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4293 * networks change state.
4294 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004295 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004296 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004297 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004298 public void registerNetworkCallback(@NonNull NetworkRequest request,
4299 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004300 CallbackHandler cbHandler = new CallbackHandler(handler);
4301 NetworkCapabilities nc = request.networkCapabilities;
4302 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004303 }
4304
4305 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004306 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4307 * {@link NetworkRequest}.
4308 *
4309 * This function behaves identically to the version that takes a NetworkCallback, but instead
4310 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4311 * the request may outlive the calling application and get called back when a suitable
4312 * network is found.
4313 * <p>
4314 * The operation is an Intent broadcast that goes to a broadcast receiver that
4315 * you registered with {@link Context#registerReceiver} or through the
4316 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4317 * <p>
4318 * The operation Intent is delivered with two extras, a {@link Network} typed
4319 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4320 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4321 * the original requests parameters.
4322 * <p>
4323 * If there is already a request for this Intent registered (with the equality of
4324 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4325 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4326 * <p>
4327 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004328 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004329 *
4330 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4331 * number of outstanding requests to 100 per app (identified by their UID), shared with
4332 * all variants of this method, of {@link #requestNetwork} as well as
4333 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4334 * Requesting a network with this method will count toward this limit. If this limit is
4335 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4336 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4337 * or {@link #releaseNetworkRequest(PendingIntent)}.
4338 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004339 * @param request {@link NetworkRequest} describing this request.
4340 * @param operation Action to perform when the network is available (corresponds
4341 * to the {@link NetworkCallback#onAvailable} call. Typically
4342 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004343 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004344 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004345 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004346 public void registerNetworkCallback(@NonNull NetworkRequest request,
4347 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004348 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004349 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004350 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004351 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004352 request.networkCapabilities, operation, mContext.getOpPackageName(),
4353 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004354 } catch (RemoteException e) {
4355 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004356 } catch (ServiceSpecificException e) {
4357 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004358 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004359 }
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
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004365 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004366 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004367 * <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 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004376 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004377 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004378 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004379 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004380 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004381 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004382 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004383 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4384 }
4385
4386 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004387 * Registers to receive notifications about changes in the application's default network. This
4388 * may be a physical network or a virtual network, such as a VPN that applies to the
4389 * application. The callbacks will continue to be called until either the application exits or
4390 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4391 *
4392 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4393 * number of outstanding requests to 100 per app (identified by their UID), shared with
4394 * all variants of this method, of {@link #requestNetwork} as well as
4395 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4396 * Requesting a network with this method will count toward this limit. If this limit is
4397 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4398 * make sure to unregister the callbacks with
4399 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4400 *
4401 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4402 * application's default network changes.
4403 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4404 * @throws RuntimeException if the app already has too many callbacks registered.
4405 */
4406 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4407 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4408 @NonNull Handler handler) {
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004409 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4410 }
4411
4412 /**
4413 * Registers to receive notifications about changes in the default network for the specified
4414 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4415 * UID. The callbacks will continue to be called until either the application exits or
4416 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4417 *
4418 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4419 * number of outstanding requests to 100 per app (identified by their UID), shared with
4420 * all variants of this method, of {@link #requestNetwork} as well as
4421 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4422 * Requesting a network with this method will count toward this limit. If this limit is
4423 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4424 * make sure to unregister the callbacks with
4425 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4426 *
4427 * @param uid the UID for which to track default network changes.
4428 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4429 * UID's default network changes.
4430 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4431 * @throws RuntimeException if the app already has too many callbacks registered.
4432 * @hide
4433 */
Lorenzo Colitti92ed8b92021-03-22 18:23:21 +09004434 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004435 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4436 @RequiresPermission(anyOf = {
4437 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4438 android.Manifest.permission.NETWORK_SETTINGS})
4439 public void registerDefaultNetworkCallbackAsUid(int uid,
4440 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004441 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004442 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004443 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4444 }
4445
4446 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004447 * Registers to receive notifications about changes in the system default network. The callbacks
4448 * will continue to be called until either the application exits or
4449 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004450 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004451 * This method should not be used to determine networking state seen by applications, because in
4452 * many cases, most or even all application traffic may not use the default network directly,
4453 * and traffic from different applications may go on different networks by default. As an
4454 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4455 * and not onto the system default network. Applications or system components desiring to do
4456 * determine network state as seen by applications should use other methods such as
4457 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4458 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004459 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4460 * number of outstanding requests to 100 per app (identified by their UID), shared with
4461 * all variants of this method, of {@link #requestNetwork} as well as
4462 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4463 * Requesting a network with this method will count toward this limit. If this limit is
4464 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4465 * make sure to unregister the callbacks with
4466 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4467 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004468 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4469 * system default network changes.
4470 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004471 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004472 *
4473 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004474 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004475 @SystemApi(client = MODULE_LIBRARIES)
4476 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4477 @RequiresPermission(anyOf = {
4478 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4479 android.Manifest.permission.NETWORK_SETTINGS})
4480 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004481 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004482 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004483 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004484 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004485 }
4486
4487 /**
junyulai8eb13a22021-03-15 11:48:48 +08004488 * Registers to receive notifications about the best matching network which satisfy the given
4489 * {@link NetworkRequest}. The callbacks will continue to be called until
4490 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4491 * called.
4492 *
4493 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4494 * number of outstanding requests to 100 per app (identified by their UID), shared with
4495 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4496 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4497 * Requesting a network with this method will count toward this limit. If this limit is
4498 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4499 * make sure to unregister the callbacks with
4500 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4501 *
4502 *
4503 * @param request {@link NetworkRequest} describing this request.
4504 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4505 * networks change state.
4506 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4507 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai7514e312021-03-05 15:51:17 +08004508 */
junyulai7514e312021-03-05 15:51:17 +08004509 @SuppressLint("ExecutorRegistration")
4510 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4511 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4512 final NetworkCapabilities nc = request.networkCapabilities;
4513 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai1b1c8742021-03-12 20:05:08 +08004514 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai7514e312021-03-05 15:51:17 +08004515 }
4516
4517 /**
fenglub00f4882015-04-21 17:12:05 -07004518 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4519 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4520 * network connection for updated bandwidth information. The caller will be notified via
4521 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004522 * method assumes that the caller has previously called
4523 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4524 * changes.
fenglu3f357402015-03-20 11:29:56 -07004525 *
fengluea2d9282015-04-27 14:28:04 -07004526 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004527 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004528 */
Chalard Jean158702d2019-01-07 19:26:34 +09004529 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004530 try {
fenglub00f4882015-04-21 17:12:05 -07004531 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004532 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004533 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004534 }
4535 }
4536
4537 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004538 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004539 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4540 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4541 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004542 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4543 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004544 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004545 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4546 * triggering it as soon as this call returns.
4547 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004548 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004549 */
Chalard Jean158702d2019-01-07 19:26:34 +09004550 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004551 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004552 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004553 final List<NetworkRequest> reqs = new ArrayList<>();
4554 // Find all requests associated to this callback and stop callback triggers immediately.
4555 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4556 synchronized (sCallbacks) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004557 if (networkCallback.networkRequest == null) {
4558 throw new IllegalArgumentException("NetworkCallback was not registered");
4559 }
Etan Cohen6cb65992019-04-16 15:07:55 -07004560 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4561 Log.d(TAG, "NetworkCallback was already unregistered");
4562 return;
4563 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004564 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4565 if (e.getValue() == networkCallback) {
4566 reqs.add(e.getKey());
4567 }
4568 }
4569 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4570 for (NetworkRequest r : reqs) {
4571 try {
4572 mService.releaseNetworkRequest(r);
4573 } catch (RemoteException e) {
4574 throw e.rethrowFromSystemServer();
4575 }
4576 // Only remove mapping if rpc was successful.
4577 sCallbacks.remove(r);
4578 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004579 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004580 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004581 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004582
4583 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004584 * Unregisters a callback previously registered via
4585 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4586 *
4587 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4588 * PendingIntent passed to
4589 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4590 * Cannot be null.
4591 */
Chalard Jean158702d2019-01-07 19:26:34 +09004592 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004593 releaseNetworkRequest(operation);
4594 }
4595
4596 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004597 * Informs the system whether it should switch to {@code network} regardless of whether it is
4598 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4599 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4600 * the system default network regardless of any other network that's currently connected. If
4601 * {@code always} is true, then the choice is remembered, so that the next time the user
4602 * connects to this network, the system will switch to it.
4603 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004604 * @param network The network to accept.
4605 * @param accept Whether to accept the network even if unvalidated.
4606 * @param always Whether to remember this choice in the future.
4607 *
4608 * @hide
4609 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004610 @SystemApi(client = MODULE_LIBRARIES)
4611 @RequiresPermission(anyOf = {
4612 android.Manifest.permission.NETWORK_SETTINGS,
4613 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4614 android.Manifest.permission.NETWORK_STACK,
4615 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4616 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004617 try {
4618 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004619 } catch (RemoteException e) {
4620 throw e.rethrowFromSystemServer();
4621 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004622 }
4623
4624 /**
lucaslin2240ef62019-03-12 13:08:03 +08004625 * Informs the system whether it should consider the network as validated even if it only has
4626 * partial connectivity. If {@code accept} is true, then the network will be considered as
4627 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4628 * is remembered, so that the next time the user connects to this network, the system will
4629 * switch to it.
4630 *
4631 * @param network The network to accept.
4632 * @param accept Whether to consider the network as validated even if it has partial
4633 * connectivity.
4634 * @param always Whether to remember this choice in the future.
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 setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4645 boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004646 try {
4647 mService.setAcceptPartialConnectivity(network, accept, always);
4648 } catch (RemoteException e) {
4649 throw e.rethrowFromSystemServer();
4650 }
4651 }
4652
4653 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004654 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4655 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4656 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4657 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4658 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004659 * @param network The network to accept.
4660 *
4661 * @hide
4662 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004663 @SystemApi(client = MODULE_LIBRARIES)
4664 @RequiresPermission(anyOf = {
4665 android.Manifest.permission.NETWORK_SETTINGS,
4666 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4667 android.Manifest.permission.NETWORK_STACK,
4668 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4669 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004670 try {
4671 mService.setAvoidUnvalidated(network);
4672 } catch (RemoteException e) {
4673 throw e.rethrowFromSystemServer();
4674 }
4675 }
4676
4677 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004678 * Requests that the system open the captive portal app on the specified network.
4679 *
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004680 * <p>This is to be used on networks where a captive portal was detected, as per
4681 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4682 *
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004683 * @param network The network to log into.
4684 *
4685 * @hide
4686 */
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004687 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4688 @RequiresPermission(anyOf = {
4689 android.Manifest.permission.NETWORK_SETTINGS,
4690 android.Manifest.permission.NETWORK_STACK,
4691 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4692 })
4693 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004694 try {
4695 mService.startCaptivePortalApp(network);
4696 } catch (RemoteException e) {
4697 throw e.rethrowFromSystemServer();
4698 }
4699 }
4700
4701 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004702 * Requests that the system open the captive portal app with the specified extras.
4703 *
4704 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4705 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004706 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004707 * @param appExtras Extras to include in the app start intent.
4708 * @hide
4709 */
4710 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004711 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004712 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004713 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004714 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004715 } catch (RemoteException e) {
4716 throw e.rethrowFromSystemServer();
4717 }
4718 }
4719
4720 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004721 * Determine whether the device is configured to avoid bad wifi.
4722 * @hide
4723 */
4724 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004725 @RequiresPermission(anyOf = {
4726 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4727 android.Manifest.permission.NETWORK_STACK})
4728 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004729 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004730 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004731 } catch (RemoteException e) {
4732 throw e.rethrowFromSystemServer();
4733 }
4734 }
4735
4736 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004737 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4738 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004739 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4740 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004741 *
4742 * An example of such an operation might be a time-sensitive foreground activity, such as a
4743 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4744 */
4745 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4746
4747 /**
4748 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4749 * a backup channel for traffic that is primarily going over another network.
4750 *
4751 * An example might be maintaining backup connections to peers or servers for the purpose of
4752 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4753 * on backup paths should be negligible compared to the traffic on the main path.
4754 */
4755 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4756
4757 /**
4758 * It is acceptable to use metered data to improve network latency and performance.
4759 */
4760 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4761
4762 /**
4763 * Return value to use for unmetered networks. On such networks we currently set all the flags
4764 * to true.
4765 * @hide
4766 */
4767 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4768 MULTIPATH_PREFERENCE_HANDOVER |
4769 MULTIPATH_PREFERENCE_RELIABILITY |
4770 MULTIPATH_PREFERENCE_PERFORMANCE;
4771
4772 /** @hide */
4773 @Retention(RetentionPolicy.SOURCE)
4774 @IntDef(flag = true, value = {
4775 MULTIPATH_PREFERENCE_HANDOVER,
4776 MULTIPATH_PREFERENCE_RELIABILITY,
4777 MULTIPATH_PREFERENCE_PERFORMANCE,
4778 })
4779 public @interface MultipathPreference {
4780 }
4781
4782 /**
4783 * Provides a hint to the calling application on whether it is desirable to use the
4784 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4785 * for multipath data transfer on this network when it is not the system default network.
4786 * Applications desiring to use multipath network protocols should call this method before
4787 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004788 *
4789 * @param network The network on which the application desires to use multipath data.
4790 * If {@code null}, this method will return the a preference that will generally
4791 * apply to metered networks.
4792 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4793 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004794 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004795 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004796 try {
4797 return mService.getMultipathPreference(network);
4798 } catch (RemoteException e) {
4799 throw e.rethrowFromSystemServer();
4800 }
4801 }
4802
4803 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004804 * Resets all connectivity manager settings back to factory defaults.
4805 * @hide
4806 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004807 @SystemApi(client = MODULE_LIBRARIES)
4808 @RequiresPermission(anyOf = {
4809 android.Manifest.permission.NETWORK_SETTINGS,
4810 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scott0f835ac2015-03-30 13:17:11 -07004811 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004812 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004813 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004814 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004815 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004816 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004817 }
4818 }
4819
4820 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004821 * Binds the current process to {@code network}. All Sockets created in the future
4822 * (and not explicitly bound via a bound SocketFactory from
4823 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4824 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4825 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4826 * work and all host name resolutions will fail. This is by design so an application doesn't
4827 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4828 * To clear binding pass {@code null} for {@code network}. Using individually bound
4829 * Sockets created by Network.getSocketFactory().createSocket() and
4830 * performing network-specific host name resolutions via
4831 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004832 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004833 *
4834 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4835 * the current binding.
4836 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4837 */
Chalard Jean158702d2019-01-07 19:26:34 +09004838 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004839 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004840 // instantiated.
4841 return setProcessDefaultNetwork(network);
4842 }
4843
4844 /**
4845 * Binds the current process to {@code network}. All Sockets created in the future
4846 * (and not explicitly bound via a bound SocketFactory from
4847 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4848 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4849 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4850 * work and all host name resolutions will fail. This is by design so an application doesn't
4851 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4852 * To clear binding pass {@code null} for {@code network}. Using individually bound
4853 * Sockets created by Network.getSocketFactory().createSocket() and
4854 * performing network-specific host name resolutions via
4855 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4856 * {@code setProcessDefaultNetwork}.
4857 *
4858 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4859 * the current binding.
4860 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4861 * @deprecated This function can throw {@link IllegalStateException}. Use
4862 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4863 * is a direct replacement.
4864 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004865 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004866 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004867 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004868 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4869
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004870 if (netId != NETID_UNSET) {
4871 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004872 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004873
4874 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4875 return false;
4876 }
4877
4878 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004879 // Set HTTP proxy system properties to match network.
4880 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004881 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004882 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004883 } catch (SecurityException e) {
4884 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4885 Log.e(TAG, "Can't set proxy properties", e);
4886 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004887 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANe1b04f62021-03-18 23:27:19 +09004888 InetAddressCompat.clearDnsCache();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004889 // Must flush socket pool as idle sockets will be bound to previous network and may
4890 // cause subsequent fetches to be performed on old network.
4891 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004892 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004893
4894 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004895 }
4896
4897 /**
4898 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004899 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004900 *
4901 * @return {@code Network} to which this process is bound, or {@code null}.
4902 */
Chalard Jean158702d2019-01-07 19:26:34 +09004903 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004904 public Network getBoundNetworkForProcess() {
4905 // Forcing callers to call thru non-static function ensures ConnectivityManager
4906 // instantiated.
4907 return getProcessDefaultNetwork();
4908 }
4909
4910 /**
4911 * Returns the {@link Network} currently bound to this process via
4912 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4913 *
4914 * @return {@code Network} to which this process is bound, or {@code null}.
4915 * @deprecated Using this function can lead to other functions throwing
4916 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4917 * {@code getBoundNetworkForProcess} is a direct replacement.
4918 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004919 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004920 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004921 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004922 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004923 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004924 return new Network(netId);
4925 }
4926
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004927 private void unsupportedStartingFrom(int version) {
4928 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004929 // The getApplicationInfo() call we make below is not supported in system context. Let
4930 // the call through here, and rely on the fact that ConnectivityService will refuse to
4931 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004932 return;
4933 }
4934
4935 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4936 throw new UnsupportedOperationException(
4937 "This method is not supported in target SDK version " + version + " and above");
4938 }
4939 }
4940
4941 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4942 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004943 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004944 // remove these exemptions. Note that this check is not secure, and apps can still access these
4945 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4946 // so is unsupported and may break in the future. http://b/22728205
4947 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004948 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004949 }
4950
Paul Jensen8cdda642014-05-29 10:12:39 -04004951 /**
4952 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004953 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004954 *
4955 * @param network The {@link Network} to bind host resolutions from the current process to, or
4956 * {@code null} to clear the current binding.
4957 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4958 * @hide
4959 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4960 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004961 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004962 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004963 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004964 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004965 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004966 }
Felipe Leme30511352016-01-22 09:44:57 -08004967
4968 /**
4969 * Device is not restricting metered network activity while application is running on
4970 * background.
4971 */
4972 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4973
4974 /**
4975 * Device is restricting metered network activity while application is running on background,
4976 * but application is allowed to bypass it.
4977 * <p>
4978 * In this state, application should take action to mitigate metered network access.
4979 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4980 */
4981 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4982
4983 /**
4984 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004985 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004986 * In this state, application should not try to use the network while running on background,
4987 * because it would be denied.
4988 */
4989 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4990
Felipe Lemed34c9af2016-01-27 14:46:39 -08004991 /**
4992 * A change in the background metered network activity restriction has occurred.
4993 * <p>
4994 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4995 * applies to them.
4996 * <p>
4997 * This is only sent to registered receivers, not manifest receivers.
4998 */
4999 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5000 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5001 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5002
Felipe Leme7e4c1852016-01-25 11:48:04 -08005003 /** @hide */
5004 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08005005 @IntDef(flag = false, value = {
5006 RESTRICT_BACKGROUND_STATUS_DISABLED,
5007 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5008 RESTRICT_BACKGROUND_STATUS_ENABLED,
5009 })
Felipe Leme30511352016-01-22 09:44:57 -08005010 public @interface RestrictBackgroundStatus {
5011 }
5012
Felipe Leme30511352016-01-22 09:44:57 -08005013 /**
5014 * Determines if the calling application is subject to metered network restrictions while
5015 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07005016 *
5017 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5018 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5019 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08005020 */
5021 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5022 try {
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005023 return mService.getRestrictBackgroundStatusByCaller();
Felipe Leme30511352016-01-22 09:44:57 -08005024 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07005025 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08005026 }
5027 }
Ricky Wai7097cc92018-01-23 04:09:45 +00005028
5029 /**
5030 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00005031 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5032 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00005033 *
5034 * @return Hash of network watchlist config file. Null if config does not exist.
5035 */
Chalard Jean158702d2019-01-07 19:26:34 +09005036 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00005037 public byte[] getNetworkWatchlistConfigHash() {
5038 try {
5039 return mService.getNetworkWatchlistConfigHash();
5040 } catch (RemoteException e) {
5041 Log.e(TAG, "Unable to get watchlist config hash");
5042 throw e.rethrowFromSystemServer();
5043 }
5044 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005045
5046 /**
5047 * Returns the {@code uid} of the owner of a network connection.
5048 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08005049 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5050 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005051 * @param local The local {@link InetSocketAddress} of a connection.
5052 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005053 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08005054 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5055 * android.os.Process#INVALID_UID} if the connection is not found.
5056 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5057 * user.
5058 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005059 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08005060 public int getConnectionOwnerUid(
5061 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005062 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5063 try {
5064 return mService.getConnectionOwnerUid(connectionInfo);
5065 } catch (RemoteException e) {
5066 throw e.rethrowFromSystemServer();
5067 }
5068 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09005069
5070 private void printStackTrace() {
5071 if (DEBUG) {
5072 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5073 final StringBuffer sb = new StringBuffer();
5074 for (int i = 3; i < callStack.length; i++) {
5075 final String stackTrace = callStack[i].toString();
5076 if (stackTrace == null || stackTrace.contains("android.os")) {
5077 break;
5078 }
5079 sb.append(" [").append(stackTrace).append("]");
5080 }
5081 Log.d(TAG, "StackLog:" + sb.toString());
5082 }
5083 }
Cody Kestingf53a0752020-04-15 12:33:28 -07005084
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09005085 /** @hide */
5086 public TestNetworkManager startOrGetTestNetworkManager() {
5087 final IBinder tnBinder;
5088 try {
5089 tnBinder = mService.startOrGetTestNetworkService();
5090 } catch (RemoteException e) {
5091 throw e.rethrowFromSystemServer();
5092 }
5093
5094 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5095 }
5096
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09005097 /** @hide */
5098 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5099 return new ConnectivityDiagnosticsManager(mContext, mService);
5100 }
5101
Cody Kestingf53a0752020-04-15 12:33:28 -07005102 /**
5103 * Simulates a Data Stall for the specified Network.
5104 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09005105 * <p>This method should only be used for tests.
5106 *
Cody Kestingf53a0752020-04-15 12:33:28 -07005107 * <p>The caller must be the owner of the specified Network.
5108 *
5109 * @param detectionMethod The detection method used to identify the Data Stall.
5110 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
5111 * @param network The Network for which a Data Stall is being simluated.
5112 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5113 * @throws SecurityException if the caller is not the owner of the given network.
5114 * @hide
5115 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09005116 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07005117 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5118 android.Manifest.permission.NETWORK_STACK})
5119 public void simulateDataStall(int detectionMethod, long timestampMillis,
5120 @NonNull Network network, @NonNull PersistableBundle extras) {
5121 try {
5122 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5123 } catch (RemoteException e) {
5124 e.rethrowFromSystemServer();
5125 }
5126 }
James Mattis356a8792020-10-28 21:48:54 -07005127
Daniel Brightf9e945b2020-06-15 16:10:01 -07005128 @NonNull
5129 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5130
5131 /**
5132 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5133 * receive available QoS events related to the {@link Network} and local ip + port
5134 * specified within socketInfo.
5135 * <p/>
5136 * The same {@link QosCallback} must be unregistered before being registered a second time,
5137 * otherwise {@link QosCallbackRegistrationException} is thrown.
5138 * <p/>
5139 * This API does not, in itself, require any permission if called with a network that is not
5140 * restricted. However, the underlying implementation currently only supports the IMS network,
5141 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5142 * useful, because they'd never be called back on networks that they would have access to.
5143 *
5144 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5145 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5146 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5147 * @throws RuntimeException if the app already has too many callbacks registered.
5148 *
5149 * Exceptions after the time of registration is passed through
5150 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5151 *
5152 * @param socketInfo the socket information used to match QoS events
Daniel Brightf9e945b2020-06-15 16:10:01 -07005153 * @param executor The executor on which the callback will be invoked. The provided
5154 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright7ee5f522021-03-10 11:51:50 -08005155 * callbacks cannot be guaranteed.onQosCallbackRegistered
5156 * @param callback receives qos events that satisfy socketInfo
Daniel Brightf9e945b2020-06-15 16:10:01 -07005157 *
5158 * @hide
5159 */
5160 @SystemApi
5161 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright7ee5f522021-03-10 11:51:50 -08005162 @CallbackExecutor @NonNull final Executor executor,
5163 @NonNull final QosCallback callback) {
Daniel Brightf9e945b2020-06-15 16:10:01 -07005164 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07005165 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright7ee5f522021-03-10 11:51:50 -08005166 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07005167
5168 try {
5169 synchronized (mQosCallbackConnections) {
5170 if (getQosCallbackConnection(callback) == null) {
5171 final QosCallbackConnection connection =
5172 new QosCallbackConnection(this, callback, executor);
5173 mQosCallbackConnections.add(connection);
5174 mService.registerQosSocketCallback(socketInfo, connection);
5175 } else {
5176 Log.e(TAG, "registerQosCallback: Callback already registered");
5177 throw new QosCallbackRegistrationException();
5178 }
5179 }
5180 } catch (final RemoteException e) {
5181 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5182
5183 // The same unregister method method is called for consistency even though nothing
5184 // will be sent to the ConnectivityService since the callback was never successfully
5185 // registered.
5186 unregisterQosCallback(callback);
5187 e.rethrowFromSystemServer();
5188 } catch (final ServiceSpecificException e) {
5189 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5190 unregisterQosCallback(callback);
5191 throw convertServiceException(e);
5192 }
5193 }
5194
5195 /**
5196 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5197 * events once unregistered and can be registered a second time.
5198 * <p/>
5199 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5200 *
5201 * @param callback the callback being unregistered
5202 *
5203 * @hide
5204 */
5205 @SystemApi
5206 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5207 Objects.requireNonNull(callback, "The callback must be non-null");
5208 try {
5209 synchronized (mQosCallbackConnections) {
5210 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5211 if (connection != null) {
5212 connection.stopReceivingMessages();
5213 mService.unregisterQosCallback(connection);
5214 mQosCallbackConnections.remove(connection);
5215 } else {
5216 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5217 }
5218 }
5219 } catch (final RemoteException e) {
5220 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5221 e.rethrowFromSystemServer();
5222 }
5223 }
5224
5225 /**
5226 * Gets the connection related to the callback.
5227 *
5228 * @param callback the callback to look up
5229 * @return the related connection
5230 */
5231 @Nullable
5232 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5233 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5234 // Checking by reference here is intentional
5235 if (connection.getCallback() == callback) {
5236 return connection;
5237 }
5238 }
5239 return null;
5240 }
Junyu Laia62493f2021-01-19 11:10:56 +00005241
5242 /**
Roshan Pius951c0032020-12-22 15:10:42 -08005243 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Laia62493f2021-01-19 11:10:56 +00005244 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5245 * be used to request that the system provide a network without causing the network to be
5246 * in the foreground.
5247 *
5248 * <p>This method will attempt to find the best network that matches the passed
5249 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5250 * criteria. The platform will evaluate which network is the best at its own discretion.
5251 * Throughput, latency, cost per byte, policy, user preference and other considerations
5252 * may be factored in the decision of what is considered the best network.
5253 *
5254 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5255 * matching this request, while always attempting to match the request to a better network if
5256 * possible. If a better match is found, the platform will switch this request to the now-best
5257 * network and inform the app of the newly best network by invoking
5258 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5259 * will not try to maintain any other network than the best one currently matching the request:
5260 * a network not matching any network request may be disconnected at any time.
5261 *
5262 * <p>For example, an application could use this method to obtain a connected cellular network
5263 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5264 * radio to consume additional power. Or, an application could inform the system that it wants
5265 * a network supporting sending MMSes and have the system let it know about the currently best
5266 * MMS-supporting network through the provided {@link NetworkCallback}.
5267 *
5268 * <p>The status of the request can be followed by listening to the various callbacks described
5269 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5270 * used to direct traffic to the network (although accessing some networks may be subject to
5271 * holding specific permissions). Callers will learn about the specific characteristics of the
5272 * network through
5273 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5274 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5275 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5276 * matching the request at any given time; therefore when a better network matching the request
5277 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5278 * with the new network after which no further updates are given about the previously-best
5279 * network, unless it becomes the best again at some later time. All callbacks are invoked
5280 * in order on the same thread, which by default is a thread created by the framework running
5281 * in the app.
5282 *
5283 * <p>This{@link NetworkRequest} will live until released via
5284 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5285 * which point the system may let go of the network at any time.
5286 *
5287 * <p>It is presently unsupported to request a network with mutable
5288 * {@link NetworkCapabilities} such as
5289 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5290 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5291 * as these {@code NetworkCapabilities} represent states that a particular
5292 * network may never attain, and whether a network will attain these states
5293 * is unknown prior to bringing up the network so the framework does not
5294 * know how to go about satisfying a request with these capabilities.
5295 *
5296 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5297 * number of outstanding requests to 100 per app (identified by their UID), shared with
5298 * all variants of this method, of {@link #registerNetworkCallback} as well as
5299 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5300 * Requesting a network with this method will count toward this limit. If this limit is
5301 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5302 * make sure to unregister the callbacks with
5303 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5304 *
5305 * @param request {@link NetworkRequest} describing this request.
5306 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5307 * If null, the callback is invoked on the default internal Handler.
5308 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5309 * the callback must not be shared - it uniquely specifies this request.
5310 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5311 * @throws SecurityException if missing the appropriate permissions.
5312 * @throws RuntimeException if the app already has too many callbacks registered.
5313 *
5314 * @hide
5315 */
5316 @SystemApi(client = MODULE_LIBRARIES)
5317 @SuppressLint("ExecutorRegistration")
5318 @RequiresPermission(anyOf = {
5319 android.Manifest.permission.NETWORK_SETTINGS,
5320 android.Manifest.permission.NETWORK_STACK,
5321 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5322 })
5323 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai962bdb82021-03-09 20:49:48 +08005324 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Laia62493f2021-01-19 11:10:56 +00005325 final NetworkCapabilities nc = request.networkCapabilities;
5326 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulai962bdb82021-03-09 20:49:48 +08005327 TYPE_NONE, new CallbackHandler(handler));
Junyu Laia62493f2021-01-19 11:10:56 +00005328 }
James Mattis45d81842021-01-10 14:24:24 -08005329
5330 /**
James Mattis45d81842021-01-10 14:24:24 -08005331 * Used by automotive devices to set the network preferences used to direct traffic at an
5332 * application level as per the given OemNetworkPreferences. An example use-case would be an
5333 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5334 * vehicle via a particular network.
5335 *
5336 * Calling this will overwrite the existing preference.
5337 *
5338 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5339 * @param executor the executor on which listener will be invoked.
5340 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5341 * communicate completion of setOemNetworkPreference(). This will only be
5342 * called once upon successful completion of setOemNetworkPreference().
5343 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5344 * @throws SecurityException if missing the appropriate permissions.
5345 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005346 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005347 */
James Mattisda32cfe2021-01-26 16:23:52 -08005348 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005349 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005350 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005351 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean6010c002021-03-03 16:37:13 +09005352 @Nullable final Runnable listener) {
James Mattis45d81842021-01-10 14:24:24 -08005353 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5354 if (null != listener) {
5355 Objects.requireNonNull(executor, "Executor must be non-null");
5356 }
Chalard Jean6010c002021-03-03 16:37:13 +09005357 final IOnCompleteListener listenerInternal = listener == null ? null :
5358 new IOnCompleteListener.Stub() {
James Mattis45d81842021-01-10 14:24:24 -08005359 @Override
5360 public void onComplete() {
Chalard Jean6010c002021-03-03 16:37:13 +09005361 executor.execute(listener::run);
James Mattis45d81842021-01-10 14:24:24 -08005362 }
5363 };
5364
5365 try {
5366 mService.setOemNetworkPreference(preference, listenerInternal);
5367 } catch (RemoteException e) {
5368 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5369 throw e.rethrowFromSystemServer();
5370 }
5371 }
lucaslin30e70a82021-03-12 00:46:33 +08005372
Chalard Jeanfa45a682021-02-25 17:23:40 +09005373 /**
5374 * Request that a user profile is put by default on a network matching a given preference.
5375 *
5376 * See the documentation for the individual preferences for a description of the supported
5377 * behaviors.
5378 *
5379 * @param profile the profile concerned.
5380 * @param preference the preference for this profile.
5381 * @param executor an executor to execute the listener on. Optional if listener is null.
5382 * @param listener an optional listener to listen for completion of the operation.
5383 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5384 * @throws SecurityException if missing the appropriate permissions.
5385 * @hide
5386 */
Chalard Jean6010c002021-03-03 16:37:13 +09005387 // This function is for establishing per-profile default networking and can only be called by
5388 // the device policy manager, running as the system server. It would make no sense to call it
5389 // on a context for a user because it does not establish a setting on behalf of a user, rather
5390 // it establishes a setting for a user on behalf of the DPM.
5391 @SuppressLint({"UserHandle"})
5392 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09005393 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5394 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5395 @ProfileNetworkPreference final int preference,
5396 @Nullable @CallbackExecutor final Executor executor,
5397 @Nullable final Runnable listener) {
5398 if (null != listener) {
5399 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5400 }
5401 final IOnCompleteListener proxy;
5402 if (null == listener) {
5403 proxy = null;
5404 } else {
5405 proxy = new IOnCompleteListener.Stub() {
5406 @Override
5407 public void onComplete() {
5408 executor.execute(listener::run);
5409 }
5410 };
5411 }
5412 try {
5413 mService.setProfileNetworkPreference(profile, preference, proxy);
5414 } catch (RemoteException e) {
5415 throw e.rethrowFromSystemServer();
5416 }
5417 }
5418
lucaslin30e70a82021-03-12 00:46:33 +08005419 // The first network ID of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005420 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin30e70a82021-03-12 00:46:33 +08005421 // The network ID range of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005422 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin30e70a82021-03-12 00:46:33 +08005423
5424 /**
5425 * Get the network ID range reserved for IPSec tunnel interfaces.
5426 *
5427 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5428 * @hide
5429 */
5430 @SystemApi(client = MODULE_LIBRARIES)
5431 @NonNull
5432 public static Range<Integer> getIpSecNetIdRange() {
5433 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5434 }
lucaslin705c3332021-03-12 17:56:09 +08005435
5436 /**
5437 * Get private DNS mode from settings.
5438 *
lucaslin7abe7e02021-03-17 14:53:35 +08005439 * @param context The Context to query the private DNS mode from settings.
lucaslin705c3332021-03-12 17:56:09 +08005440 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5441 *
5442 * @hide
5443 */
5444 @SystemApi(client = MODULE_LIBRARIES)
5445 @NonNull
5446 @PrivateDnsMode
lucaslin20f04882021-03-16 17:11:14 +08005447 public static String getPrivateDnsMode(@NonNull Context context) {
5448 final ContentResolver cr = context.getContentResolver();
lucaslin705c3332021-03-12 17:56:09 +08005449 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5450 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5451 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5452 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5453 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5454 return mode;
5455 }
paulhu89a762a2021-03-25 12:36:56 +08005456
5457 /**
5458 * Set private DNS mode to settings.
5459 *
5460 * @param context The {@link Context} to set the private DNS mode.
5461 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5462 *
5463 * @hide
5464 */
5465 @SystemApi(client = MODULE_LIBRARIES)
5466 public static void setPrivateDnsMode(@NonNull Context context,
5467 @NonNull @PrivateDnsMode String mode) {
5468 if (!(mode == PRIVATE_DNS_MODE_OFF
5469 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5470 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5471 throw new IllegalArgumentException("Invalid private dns mode");
5472 }
5473 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5474 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005475}