blob: 34d95c7978c5b555ae0b1e696437b1b5920b3edd [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;
junyulaid05a1922019-01-15 11:32:44 +080019import static android.net.IpSecManager.INVALID_RESOURCE_ID;
Junyu Laia62493f2021-01-19 11:10:56 +000020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaiad010792021-01-11 16:53:38 +080021import static android.net.NetworkRequest.Type.LISTEN;
22import static android.net.NetworkRequest.Type.REQUEST;
23import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +090024import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Brightf9e945b2020-06-15 16:10:01 -070025import static android.net.QosCallback.QosCallbackRegistrationException;
junyulaid05a1922019-01-15 11:32:44 +080026
junyulai4c95b082018-12-27 17:25:29 +080027import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080028import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090029import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000030import android.annotation.Nullable;
Jeff Sharkey656584a2017-04-24 11:18:03 -060031import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080032import android.annotation.SdkConstant;
33import android.annotation.SdkConstant.SdkConstantType;
Junyu Laia62493f2021-01-19 11:10:56 +000034import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080035import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060036import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070037import android.app.PendingIntent;
Artur Satayev9c2add62019-12-10 17:47:52 +000038import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070039import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070040import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080041import android.net.IpSecManager.UdpEncapsulationSocket;
42import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080043import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080044import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080045import android.net.TetheringManager.TetheringRequest;
Robert Greenwalt2034b912009-08-12 16:08:25 -070046import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000047import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070048import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080049import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070050import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080051import android.os.IBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070052import android.os.Looper;
53import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070054import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080055import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070056import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090057import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080058import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080059import android.os.ResultReceiver;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080060import android.os.ServiceManager;
Hugo Benichia590ab82017-05-11 13:16:17 +090061import android.os.ServiceSpecificException;
Jeff Sharkey971cd162011-08-29 16:02:57 -070062import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080063import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080064import android.telephony.TelephonyManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080065import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070066import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090067import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090068import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090070import com.android.connectivity.aidl.INetworkAgent;
markchien6ae63e52020-01-21 13:11:06 +080071import com.android.internal.annotations.GuardedBy;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090072import com.android.internal.util.Preconditions;
73import com.android.internal.util.Protocol;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070074
Paul Jensen3e2917c2014-08-27 12:38:45 -040075import libcore.net.event.NetworkEventDispatcher;
76
junyulai7e06ad42019-03-04 22:45:36 +080077import java.io.IOException;
78import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080079import java.lang.annotation.Retention;
80import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090081import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080082import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070083import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080084import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090085import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090086import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080087import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090088import java.util.List;
89import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080090import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080091import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080092import java.util.concurrent.ExecutorService;
93import java.util.concurrent.Executors;
94import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -080095
The Android Open Source Project28527d22009-03-03 19:31:44 -080096/**
97 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060098 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -080099 * <p>
100 * The primary responsibilities of this class are to:
101 * <ol>
102 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
103 * <li>Send broadcast intents when network connectivity changes</li>
104 * <li>Attempt to "fail over" to another network when connectivity to a network
105 * is lost</li>
106 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
107 * state of the available networks</li>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700108 * <li>Provide an API that allows applications to request and select networks for their data
109 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800110 * </ol>
111 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600112@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700113public class ConnectivityManager {
114 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900115 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700116
The Android Open Source Project28527d22009-03-03 19:31:44 -0800117 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700118 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800119 * been established or lost. The NetworkInfo for the affected network is
120 * sent as an extra; it should be consulted to see what kind of
121 * connectivity event occurred.
122 * <p/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800123 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
124 * broadcast if they declare the broadcast receiver in their manifest. Apps
125 * will still receive broadcasts if they register their
126 * {@link android.content.BroadcastReceiver} with
127 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
128 * and that context is still valid.
129 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800130 * If this is a connection that was the result of failing over from a
131 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
132 * set to true.
133 * <p/>
134 * For a loss of connectivity, if the connectivity manager is attempting
135 * to connect (or has already connected) to another network, the
136 * NetworkInfo for the new network is also passed as an extra. This lets
137 * any receivers of the broadcast know that they should not necessarily
138 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800139 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800140 * the failover attempt succeeded (and so there is still overall data
141 * connectivity), or that the failover attempt failed, meaning that all
142 * connectivity has been lost.
143 * <p/>
144 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
145 * is set to {@code true} if there are no connected networks at all.
Chalard Jean52e23962018-02-10 05:33:50 +0900146 *
147 * @deprecated apps should use the more versatile {@link #requestNetwork},
148 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
149 * functions instead for faster and more detailed updates about the network
150 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800151 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800152 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900153 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800154 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700155
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500157 * The device has connected to a network that has presented a captive
158 * portal, which is blocking Internet connectivity. The user was presented
159 * with a notification that network sign in is required,
160 * and the user invoked the notification's action indicating they
Paul Jensen75e0adb2015-05-22 10:50:39 -0400161 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500162 * facilitate signing in to the network. This action includes a
163 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
164 * the network presenting the captive portal; all communication with the
165 * captive portal must be done using this {@code Network} object.
166 * <p/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400167 * This activity includes a {@link CaptivePortal} extra named
168 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
169 * outcomes of the captive portal sign in to the system:
170 * <ul>
171 * <li> When the app handling this action believes the user has signed in to
172 * the network and the captive portal has been dismissed, the app should
173 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
174 * reevaluate the network. If reevaluation finds the network no longer
175 * subject to a captive portal, the network may become the default active
Chalard Jean9dd11612018-06-04 16:52:49 +0900176 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400177 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500178 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400179 * {@link CaptivePortal#ignoreNetwork}. </li>
180 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500181 */
182 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
183 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
184
185 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800186 * The lookup key for a {@link NetworkInfo} object. Retrieve with
187 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700188 *
Chalard Jean97021a12019-01-11 16:47:53 +0900189 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
190 * can't accurately represent modern network characteristics.
191 * Please obtain information about networks from the {@link NetworkCapabilities}
192 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800193 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700194 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800195 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700196
The Android Open Source Project28527d22009-03-03 19:31:44 -0800197 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700198 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700199 *
200 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900201 * @deprecated The network type is not rich enough to represent the characteristics
202 * of modern networks. Please use {@link NetworkCapabilities} instead,
203 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700204 */
Chalard Jean97021a12019-01-11 16:47:53 +0900205 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700206 public static final String EXTRA_NETWORK_TYPE = "networkType";
207
208 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800209 * The lookup key for a boolean that indicates whether a connect event
210 * is for a network to which the connectivity manager was failing over
211 * following a disconnect on another network.
212 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai9826e7f2018-12-13 12:47:51 +0800213 *
214 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800215 */
junyulai9826e7f2018-12-13 12:47:51 +0800216 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800217 public static final String EXTRA_IS_FAILOVER = "isFailover";
218 /**
219 * The lookup key for a {@link NetworkInfo} object. This is supplied when
220 * there is another network that it may be possible to connect to. Retrieve with
221 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800222 *
223 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800224 */
junyulai9826e7f2018-12-13 12:47:51 +0800225 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800226 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
227 /**
228 * The lookup key for a boolean that indicates whether there is a
229 * complete lack of connectivity, i.e., no network is available.
230 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
231 */
232 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
233 /**
234 * The lookup key for a string that indicates why an attempt to connect
235 * to a network failed. The string has no particular structure. It is
236 * intended to be used in notifications presented to users. Retrieve
237 * it with {@link android.content.Intent#getStringExtra(String)}.
238 */
239 public static final String EXTRA_REASON = "reason";
240 /**
241 * The lookup key for a string that provides optionally supplied
242 * extra information about the network state. The information
243 * may be passed up from the lower networking layers, and its
244 * meaning may be specific to a particular network type. Retrieve
245 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800246 *
247 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800248 */
junyulai9826e7f2018-12-13 12:47:51 +0800249 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800250 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700251 /**
252 * The lookup key for an int that provides information about
253 * our connection to the internet at large. 0 indicates no connection,
254 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700255 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700256 * {@hide}
257 */
258 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800259 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400260 * The lookup key for a {@link CaptivePortal} object included with the
261 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
262 * object can be used to either indicate to the system that the captive
263 * portal has been dismissed or that the user does not want to pursue
264 * signing in to captive portal. Retrieve it with
265 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500266 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400267 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700268
269 /**
270 * Key for passing a URL to the captive portal login activity.
271 */
272 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
273
Paul Jensen60df4aa2015-02-27 22:55:47 -0500274 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900275 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
276 * portal login activity.
277 * {@hide}
278 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900279 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900280 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
281 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
282
283 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900284 * Key for passing a user agent string to the captive portal login activity.
285 * {@hide}
286 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900287 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900288 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
289 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
290
291 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700292 * Broadcast action to indicate the change of data activity status
293 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800294 * The network becomes active when data transmission is started, or
295 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700296 * {@hide}
297 */
298 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900299 public static final String ACTION_DATA_ACTIVITY_CHANGE =
300 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700301 /**
302 * The lookup key for an enum that indicates the network device type on which this data activity
303 * change happens.
304 * {@hide}
305 */
306 public static final String EXTRA_DEVICE_TYPE = "deviceType";
307 /**
308 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
309 * it is actively sending or receiving data and {@code false} means it is idle.
310 * {@hide}
311 */
312 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700313 /**
314 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
315 * {@hide}
316 */
317 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700318
319 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800320 * Broadcast Action: The setting for background data usage has changed
321 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
322 * <p>
323 * If an application uses the network in the background, it should listen
324 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700325 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800326 * <p>
327 *
328 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
329 * of background data depends on several combined factors, and
330 * this broadcast is no longer sent. Instead, when background
331 * data is unavailable, {@link #getActiveNetworkInfo()} will now
332 * appear disconnected. During first boot after a platform
333 * upgrade, this broadcast will be sent once if
334 * {@link #getBackgroundDataSetting()} was {@code false} before
335 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800336 */
337 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800338 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800339 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
340 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
341
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700342 /**
343 * Broadcast Action: The network connection may not be good
344 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
345 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
346 * the network and it's condition.
347 * @hide
348 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800349 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100350 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700351 public static final String INET_CONDITION_ACTION =
352 "android.net.conn.INET_CONDITION_ACTION";
353
Robert Greenwalt2034b912009-08-12 16:08:25 -0700354 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800355 * Broadcast Action: A tetherable connection has come or gone.
356 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900357 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
358 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800359 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
360 * the current state of tethering. Each include a list of
361 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800362 * @hide
363 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800364 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000365 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800366 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800367 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800368
369 /**
370 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800371 * gives a String[] listing all the interfaces configured for
372 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800373 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000374 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800375 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800376
377 /**
378 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900379 * gives a String[] listing all the interfaces currently in local-only
380 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800381 */
markchiena0f8fd92019-12-25 19:40:32 +0800382 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900383
384 /**
385 * @hide
386 * gives a String[] listing all the interfaces currently tethered
387 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
388 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000389 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800390 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800391
392 /**
393 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800394 * gives a String[] listing all the interfaces we tried to tether and
395 * failed. Use {@link #getLastTetherError} to find the error code
396 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800397 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000398 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800399 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800400
401 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800402 * Broadcast Action: The captive portal tracker has finished its test.
403 * Sent only while running Setup Wizard, in lieu of showing a user
404 * notification.
405 * @hide
406 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800407 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800408 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
409 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
410 /**
411 * The lookup key for a boolean that indicates whether a captive portal was detected.
412 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
413 * @hide
414 */
415 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
416
417 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900418 * Action used to display a dialog that asks the user whether to connect to a network that is
419 * not validated. This intent is used to start the dialog in settings via startActivity.
420 *
421 * @hide
422 */
423 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
424
425 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900426 * Action used to display a dialog that asks the user whether to avoid a network that is no
427 * longer validated. This intent is used to start the dialog in settings via startActivity.
428 *
429 * @hide
430 */
431 public static final String ACTION_PROMPT_LOST_VALIDATION =
432 "android.net.conn.PROMPT_LOST_VALIDATION";
433
434 /**
lucaslin2240ef62019-03-12 13:08:03 +0800435 * Action used to display a dialog that asks the user whether to stay connected to a network
436 * that has not validated. This intent is used to start the dialog in settings via
437 * startActivity.
438 *
439 * @hide
440 */
441 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
442 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
443
444 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800445 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900446 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800447 * @hide
448 */
markchiena0f8fd92019-12-25 19:40:32 +0800449 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800450
451 /**
452 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900453 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800454 * @hide
455 */
456 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900457 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800458
459 /**
460 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900461 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800462 * @hide
463 */
464 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900465 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800466
467 /**
468 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900469 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800470 * @hide
471 */
472 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900473 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800474
475 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800476 * Wifi P2p tethering type.
477 * Wifi P2p tethering is set through events automatically, and don't
478 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
479 * @hide
480 */
markchiena0f8fd92019-12-25 19:40:32 +0800481 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800482
483 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800484 * Extra used for communicating with the TetherService. Includes the type of tethering to
485 * enable if any.
486 * @hide
487 */
markchien6ae63e52020-01-21 13:11:06 +0800488 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800489
490 /**
491 * Extra used for communicating with the TetherService. Includes the type of tethering for
492 * which to cancel provisioning.
493 * @hide
494 */
markchien6ae63e52020-01-21 13:11:06 +0800495 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800496
497 /**
498 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
499 * provisioning.
500 * @hide
501 */
markchien6ae63e52020-01-21 13:11:06 +0800502 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800503
504 /**
505 * Tells the TetherService to run a provision check now.
506 * @hide
507 */
markchien6ae63e52020-01-21 13:11:06 +0800508 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800509
510 /**
511 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
512 * which will receive provisioning results. Can be left empty.
513 * @hide
514 */
markchien6ae63e52020-01-21 13:11:06 +0800515 public static final String EXTRA_PROVISION_CALLBACK =
516 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800517
518 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800519 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700520 * @hide
521 */
paulhu74357e72020-01-13 16:46:45 +0800522 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700523 public static final int TYPE_NONE = -1;
524
525 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900526 * A Mobile data connection. Devices may support more than one.
527 *
528 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
529 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
530 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700531 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900532 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700533 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900534
Robert Greenwalt2034b912009-08-12 16:08:25 -0700535 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900536 * A WIFI data connection. Devices may support more than one.
537 *
538 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
539 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
540 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700541 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900542 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700543 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900544
Robert Greenwalt2034b912009-08-12 16:08:25 -0700545 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800546 * An MMS-specific Mobile data connection. This network type may use the
547 * same network interface as {@link #TYPE_MOBILE} or it may use a different
548 * one. This is used by applications needing to talk to the carrier's
549 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900550 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900551 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900552 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900553 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700554 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700555 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700556 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900557
Robert Greenwalt2034b912009-08-12 16:08:25 -0700558 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800559 * A SUPL-specific Mobile data connection. This network type may use the
560 * same network interface as {@link #TYPE_MOBILE} or it may use a different
561 * one. This is used by applications needing to talk to the carrier's
562 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900563 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900564 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900565 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900566 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700567 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700568 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700569 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900570
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800572 * A DUN-specific Mobile data connection. This network type may use the
573 * same network interface as {@link #TYPE_MOBILE} or it may use a different
574 * one. This is sometimes by the system when setting up an upstream connection
575 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900576 *
577 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
578 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
579 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700580 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900581 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700582 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900583
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800585 * A High Priority Mobile data connection. This network type uses the
586 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900587 * is different.
588 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900589 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
590 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
591 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700592 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700593 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700594 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900595
jshbfa81722010-03-11 15:04:43 -0800596 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900597 * A WiMAX data connection.
598 *
599 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
600 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
601 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800602 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900603 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800604 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800605
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800606 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900607 * A Bluetooth data connection.
608 *
609 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
610 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
611 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800612 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900613 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800614 public static final int TYPE_BLUETOOTH = 7;
615
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700616 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800617 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900618 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700619 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900620 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800621 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800622
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700623 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900624 * An Ethernet 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.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700629 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900630 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800631 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700632
Wink Savilleb7c92c72011-03-12 14:52:01 -0800633 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800634 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900635 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800636 * {@hide}
637 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900638 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900639 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800640 public static final int TYPE_MOBILE_FOTA = 10;
641
642 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800643 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900644 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800645 * {@hide}
646 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900647 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100648 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800649 public static final int TYPE_MOBILE_IMS = 11;
650
651 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800652 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900653 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800654 * {@hide}
655 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900656 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900657 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800658 public static final int TYPE_MOBILE_CBS = 12;
659
repo syncf5de5572011-07-29 23:55:49 -0700660 /**
661 * A Wi-Fi p2p connection. Only requesting processes will have access to
662 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900663 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700664 * {@hide}
665 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900666 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800667 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700668 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800669
Wink Saville512c2202013-07-29 15:00:57 -0700670 /**
671 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900672 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700673 * {@hide}
674 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900675 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100676 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700677 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700678
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900679 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700680 * Emergency PDN connection for emergency services. This
681 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900682 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700683 * {@hide}
684 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900685 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900686 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700687 public static final int TYPE_MOBILE_EMERGENCY = 15;
688
Hui Lu865b70d2014-01-15 11:05:36 -0500689 /**
690 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900691 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500692 * {@hide}
693 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900694 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900695 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500696 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700697
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700698 /**
699 * A virtual network using one or more native bearers.
700 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900701 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700702 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900703 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700704 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500705
Benedict Wongbdfaa482018-11-14 17:40:55 -0800706 /**
707 * A network that is exclusively meant to be used for testing
708 *
709 * @deprecated Use {@link NetworkCapabilities} instead.
710 * @hide
711 */
712 @Deprecated
713 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700714
Chalard Jeanaea539a2020-03-25 01:24:04 +0900715 /**
716 * @deprecated Use {@link NetworkCapabilities} instead.
717 * @hide
718 */
719 @Deprecated
720 @Retention(RetentionPolicy.SOURCE)
721 @IntDef(prefix = { "TYPE_" }, value = {
722 TYPE_NONE,
723 TYPE_MOBILE,
724 TYPE_WIFI,
725 TYPE_MOBILE_MMS,
726 TYPE_MOBILE_SUPL,
727 TYPE_MOBILE_DUN,
728 TYPE_MOBILE_HIPRI,
729 TYPE_WIMAX,
730 TYPE_BLUETOOTH,
731 TYPE_DUMMY,
732 TYPE_ETHERNET,
733 TYPE_MOBILE_FOTA,
734 TYPE_MOBILE_IMS,
735 TYPE_MOBILE_CBS,
736 TYPE_WIFI_P2P,
737 TYPE_MOBILE_IA,
738 TYPE_MOBILE_EMERGENCY,
739 TYPE_PROXY,
740 TYPE_VPN,
741 TYPE_TEST
742 })
743 public @interface LegacyNetworkType {}
744
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900745 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
746 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
747 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
748 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
749 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
750
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700751 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800752 public static final int MAX_RADIO_TYPE = TYPE_TEST;
753
754 /** {@hide} */
755 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800756
Hugo Benichiad353f42017-06-20 14:07:59 +0900757 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
758
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800759 /**
760 * If you want to set the default network preference,you can directly
761 * change the networkAttributes array in framework's config.xml.
762 *
763 * @deprecated Since we support so many more networks now, the single
764 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800765 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800766 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800767 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800768 * from an App.
769 */
770 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800771 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
772
Jeff Sharkey8c870452012-09-26 22:03:49 -0700773 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700774 * @hide
775 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900776 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700777
Paul Jensen5dea4352014-07-11 12:28:19 -0400778 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900779 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
780 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900781 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900782 * @hide
783 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900784 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900785 new NetworkRequest.Builder().clearCapabilities().build();
786
787 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400788 * A NetID indicating no Network is selected.
789 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
790 * @hide
791 */
792 public static final int NETID_UNSET = 0;
793
Erik Klineb0be3e62017-10-30 15:29:44 +0900794 /**
795 * Private DNS Mode values.
796 *
797 * The "private_dns_mode" global setting stores a String value which is
798 * expected to be one of the following.
799 */
800
801 /**
802 * @hide
803 */
804 public static final String PRIVATE_DNS_MODE_OFF = "off";
805 /**
806 * @hide
807 */
808 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
809 /**
810 * @hide
811 */
812 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
813 /**
814 * The default Private DNS mode.
815 *
816 * This may change from release to release or may become dependent upon
817 * the capabilities of the underlying platform.
818 *
819 * @hide
820 */
Erik Klinea7edf6f2018-05-16 16:41:57 +0900821 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Klineb0be3e62017-10-30 15:29:44 +0900822
Chalard Jeana3b77512019-04-09 15:46:21 +0900823 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700824 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900825
Paul Jensenc0618a62014-12-10 15:12:18 -0500826 /**
827 * A kludge to facilitate static access where a Context pointer isn't available, like in the
828 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
829 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
830 * methods that take a Context argument.
831 */
832 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800833
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900834 private final Context mContext;
835
Felipe Leme30511352016-01-22 09:44:57 -0800836 private INetworkPolicyManager mNPManager;
Amos Bianchia9b415a2020-03-04 11:07:38 -0800837 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800838
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800839 /**
840 * Tests if a given integer represents a valid network type.
841 * @param networkType the type to be tested
842 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400843 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
844 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800845 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700846 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700847 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900848 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800849 }
850
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800851 /**
852 * Returns a non-localized string representing a given network type.
853 * ONLY used for debugging output.
854 * @param type the type needing naming
855 * @return a String for the given type, or a string version of the type ("87")
856 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900857 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800858 * {@hide}
859 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900860 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000861 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700862 public static String getNetworkTypeName(int type) {
863 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900864 case TYPE_NONE:
865 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700866 case TYPE_MOBILE:
867 return "MOBILE";
868 case TYPE_WIFI:
869 return "WIFI";
870 case TYPE_MOBILE_MMS:
871 return "MOBILE_MMS";
872 case TYPE_MOBILE_SUPL:
873 return "MOBILE_SUPL";
874 case TYPE_MOBILE_DUN:
875 return "MOBILE_DUN";
876 case TYPE_MOBILE_HIPRI:
877 return "MOBILE_HIPRI";
878 case TYPE_WIMAX:
879 return "WIMAX";
880 case TYPE_BLUETOOTH:
881 return "BLUETOOTH";
882 case TYPE_DUMMY:
883 return "DUMMY";
884 case TYPE_ETHERNET:
885 return "ETHERNET";
886 case TYPE_MOBILE_FOTA:
887 return "MOBILE_FOTA";
888 case TYPE_MOBILE_IMS:
889 return "MOBILE_IMS";
890 case TYPE_MOBILE_CBS:
891 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700892 case TYPE_WIFI_P2P:
893 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700894 case TYPE_MOBILE_IA:
895 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700896 case TYPE_MOBILE_EMERGENCY:
897 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500898 case TYPE_PROXY:
899 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900900 case TYPE_VPN:
901 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700902 default:
903 return Integer.toString(type);
904 }
905 }
906
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800907 /**
Aaron Huang96011892020-06-27 07:18:23 +0800908 * @hide
909 * TODO: Expose for SystemServer when becomes a module.
910 */
911 public void systemReady() {
912 try {
913 mService.systemReady();
914 } catch (RemoteException e) {
915 throw e.rethrowFromSystemServer();
916 }
917 }
918
919 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800920 * Checks if a given type uses the cellular data connection.
921 * This should be replaced in the future by a network property.
922 * @param networkType the type to check
923 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900924 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800925 * {@hide}
926 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900927 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900928 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700929 public static boolean isNetworkTypeMobile(int networkType) {
930 switch (networkType) {
931 case TYPE_MOBILE:
932 case TYPE_MOBILE_MMS:
933 case TYPE_MOBILE_SUPL:
934 case TYPE_MOBILE_DUN:
935 case TYPE_MOBILE_HIPRI:
936 case TYPE_MOBILE_FOTA:
937 case TYPE_MOBILE_IMS:
938 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -0700939 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -0700940 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700941 return true;
942 default:
943 return false;
944 }
945 }
946
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800947 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700948 * Checks if the given network type is backed by a Wi-Fi radio.
949 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900950 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700951 * @hide
952 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900953 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700954 public static boolean isNetworkTypeWifi(int networkType) {
955 switch (networkType) {
956 case TYPE_WIFI:
957 case TYPE_WIFI_P2P:
958 return true;
959 default:
960 return false;
961 }
962 }
963
964 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800965 * Specifies the preferred network type. When the device has more
966 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800967 *
968 * @param preference the network type to prefer over all others. It is
969 * unspecified what happens to the old preferred network in the
970 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700971 * @deprecated Functionality has been removed as it no longer makes sense,
972 * with many more than two networks - we'd need an array to express
973 * preference. Instead we use dynamic network properties of
974 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800975 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700976 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800977 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800978 }
979
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800980 /**
981 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800982 *
983 * @return an integer representing the preferred network type
984 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700985 * @deprecated Functionality has been removed as it no longer makes sense,
986 * with many more than two networks - we'd need an array to express
987 * preference. Instead we use dynamic network properties of
988 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800989 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700990 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -0600991 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -0800992 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700993 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800994 }
995
Scott Mainf58b7d82011-10-06 19:02:28 -0700996 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800997 * Returns details about the currently active default data network. When
998 * connected, this network is the default route for outgoing connections.
999 * You should always check {@link NetworkInfo#isConnected()} before initiating
1000 * network traffic. This may return {@code null} when there is no default
1001 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001002 * Note that if the default network is a VPN, this method will return the
1003 * NetworkInfo for one of its underlying networks instead, or null if the
1004 * VPN agent did not specify any. Apps interested in learning about VPNs
1005 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001006 *
1007 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001008 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001009 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001010 */
junyulai9826e7f2018-12-13 12:47:51 +08001011 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001012 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001013 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001014 public NetworkInfo getActiveNetworkInfo() {
1015 try {
1016 return mService.getActiveNetworkInfo();
1017 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001018 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001019 }
1020 }
1021
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001022 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001023 * Returns a {@link Network} object corresponding to the currently active
1024 * default data network. In the event that the current active default data
1025 * network disconnects, the returned {@code Network} object will no longer
1026 * be usable. This will return {@code null} when there is no default
1027 * network.
1028 *
1029 * @return a {@link Network} object for the current default network or
1030 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001031 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001032 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001033 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001034 public Network getActiveNetwork() {
1035 try {
1036 return mService.getActiveNetwork();
1037 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001038 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001039 }
1040 }
1041
1042 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001043 * Returns a {@link Network} object corresponding to the currently active
1044 * default data network for a specific UID. In the event that the default data
1045 * network disconnects, the returned {@code Network} object will no longer
1046 * be usable. This will return {@code null} when there is no default
1047 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001048 *
1049 * @return a {@link Network} object for the current default network for the
1050 * given UID or {@code null} if no default network is currently active
1051 *
1052 * @hide
1053 */
paulhu8e96a752019-08-12 16:25:11 +08001054 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001055 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001056 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001057 return getActiveNetworkForUid(uid, false);
1058 }
1059
1060 /** {@hide} */
1061 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001062 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001063 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001064 } catch (RemoteException e) {
1065 throw e.rethrowFromSystemServer();
1066 }
1067 }
1068
1069 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001070 * Adds or removes a requirement for given UID ranges to use the VPN.
1071 *
1072 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1073 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1074 * otherwise have permission to bypass the VPN (e.g., because they have the
1075 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1076 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1077 * set to {@code false}, a previously-added restriction is removed.
1078 * <p>
1079 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1080 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1081 * remove a previously-added range, the exact range must be removed as is.
1082 * <p>
1083 * The changes are applied asynchronously and may not have been applied by the time the method
1084 * returns. Apps will be notified about any changes that apply to them via
1085 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1086 * effect.
1087 * <p>
1088 * This method should be called only by the VPN code.
1089 *
1090 * @param ranges the UID ranges to restrict
1091 * @param requireVpn whether the specified UID ranges must use a VPN
1092 *
1093 * TODO: expose as @SystemApi.
1094 * @hide
1095 */
1096 @RequiresPermission(anyOf = {
1097 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1098 android.Manifest.permission.NETWORK_STACK})
1099 public void setRequireVpnForUids(boolean requireVpn,
1100 @NonNull Collection<Range<Integer>> ranges) {
1101 Objects.requireNonNull(ranges);
1102 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1103 // This method is not necessarily expected to be used outside the system server, so
1104 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1105 // stack process, or by tests.
1106 UidRange[] rangesArray = new UidRange[ranges.size()];
1107 int index = 0;
1108 for (Range<Integer> range : ranges) {
1109 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1110 }
1111 try {
1112 mService.setRequireVpnForUids(requireVpn, rangesArray);
1113 } catch (RemoteException e) {
1114 throw e.rethrowFromSystemServer();
1115 }
1116 }
1117
1118 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001119 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1120 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1121 * but is still supported for backwards compatibility.
1122 * <p>
1123 * This type of VPN is assumed always to use the system default network, and must always declare
1124 * exactly one underlying network, which is the network that was the default when the VPN
1125 * connected.
1126 * <p>
1127 * Calling this method with {@code true} enables legacy behaviour, specifically:
1128 * <ul>
1129 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1130 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1131 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1132 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1133 * underlying the VPN.</li>
1134 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1135 * similarly replaced by the VPN network state.</li>
1136 * <li>Information on current network interfaces passed to NetworkStatsService will not
1137 * include any VPN interfaces.</li>
1138 * </ul>
1139 *
1140 * @param enabled whether legacy lockdown VPN is enabled or disabled
1141 *
1142 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1143 *
1144 * @hide
1145 */
1146 @RequiresPermission(anyOf = {
1147 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1148 android.Manifest.permission.NETWORK_SETTINGS})
1149 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1150 try {
1151 mService.setLegacyLockdownVpnEnabled(enabled);
1152 } catch (RemoteException e) {
1153 throw e.rethrowFromSystemServer();
1154 }
1155 }
1156
1157 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001158 * Returns details about the currently active default data network
1159 * for a given uid. This is for internal use only to avoid spying
1160 * other apps.
1161 *
1162 * @return a {@link NetworkInfo} object for the current default network
1163 * for the given uid or {@code null} if no default network is
1164 * available for the specified uid.
1165 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001166 * {@hide}
1167 */
paulhu8e96a752019-08-12 16:25:11 +08001168 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001169 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001170 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001171 return getActiveNetworkInfoForUid(uid, false);
1172 }
1173
1174 /** {@hide} */
1175 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001176 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001177 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001178 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001179 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001180 }
1181 }
1182
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001183 /**
1184 * Returns connection status information about a particular
1185 * network type.
1186 *
1187 * @param networkType integer specifying which networkType in
1188 * which you're interested.
1189 * @return a {@link NetworkInfo} object for the requested
1190 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001191 * supported by the device. If {@code networkType} is
1192 * TYPE_VPN and a VPN is active for the calling app,
1193 * then this method will try to return one of the
1194 * underlying networks for the VPN or null if the
1195 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001196 *
Paul Jensendda8e592015-03-18 12:23:02 -04001197 * @deprecated This method does not support multiple connected networks
1198 * of the same type. Use {@link #getAllNetworks} and
1199 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001200 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001201 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001202 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001203 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001204 public NetworkInfo getNetworkInfo(int networkType) {
1205 try {
1206 return mService.getNetworkInfo(networkType);
1207 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001208 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001209 }
1210 }
1211
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001212 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001213 * Returns connection status information about a particular
1214 * Network.
1215 *
1216 * @param network {@link Network} specifying which network
1217 * in which you're interested.
1218 * @return a {@link NetworkInfo} object for the requested
1219 * network or {@code null} if the {@code Network}
1220 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001221 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001222 */
junyulai9826e7f2018-12-13 12:47:51 +08001223 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001224 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001225 @Nullable
1226 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001227 return getNetworkInfoForUid(network, Process.myUid(), false);
1228 }
1229
1230 /** {@hide} */
1231 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001232 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001233 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001234 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001235 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001236 }
1237 }
1238
1239 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001240 * Returns connection status information about all network
1241 * types supported by the device.
1242 *
1243 * @return an array of {@link NetworkInfo} objects. Check each
1244 * {@link NetworkInfo#getType} for which type each applies.
1245 *
Paul Jensendda8e592015-03-18 12:23:02 -04001246 * @deprecated This method does not support multiple connected networks
1247 * of the same type. Use {@link #getAllNetworks} and
1248 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001249 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001250 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001251 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001252 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001253 public NetworkInfo[] getAllNetworkInfo() {
1254 try {
1255 return mService.getAllNetworkInfo();
1256 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001257 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001258 }
1259 }
1260
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001261 /**
junyulaiebd15162021-03-03 12:09:05 +08001262 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1263 * connected.
1264 * @hide
1265 */
1266 @SystemApi(client = MODULE_LIBRARIES)
1267 @RequiresPermission(anyOf = {
1268 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1269 android.Manifest.permission.NETWORK_STACK,
1270 android.Manifest.permission.NETWORK_SETTINGS})
1271 @NonNull
1272 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1273 try {
1274 return mService.getAllNetworkStateSnapshot();
1275 } catch (RemoteException e) {
1276 throw e.rethrowFromSystemServer();
1277 }
1278 }
1279
1280 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001281 * Returns the {@link Network} object currently serving a given type, or
1282 * null if the given type is not connected.
1283 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001284 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001285 * @deprecated This method does not support multiple connected networks
1286 * of the same type. Use {@link #getAllNetworks} and
1287 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001288 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001289 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001290 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001291 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001292 public Network getNetworkForType(int networkType) {
1293 try {
1294 return mService.getNetworkForType(networkType);
1295 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001296 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001297 }
1298 }
1299
1300 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001301 * Returns an array of all {@link Network} currently tracked by the
1302 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001303 *
1304 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001305 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001306 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001307 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001308 public Network[] getAllNetworks() {
1309 try {
1310 return mService.getAllNetworks();
1311 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001312 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001313 }
1314 }
1315
1316 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001317 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001318 * the Networks that applications run by the given user will use by default.
1319 * @hide
1320 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001321 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001322 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1323 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001324 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001325 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001326 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001327 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001328 }
1329 }
1330
1331 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001332 * Returns the IP information for the current default network.
1333 *
1334 * @return a {@link LinkProperties} object describing the IP info
1335 * for the current default network, or {@code null} if there
1336 * is no current default network.
1337 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001338 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001339 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1340 * value of {@link #getActiveNetwork()} instead. In particular,
1341 * this method will return non-null LinkProperties even if the
1342 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001343 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001344 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001345 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001346 public LinkProperties getActiveLinkProperties() {
1347 try {
1348 return mService.getActiveLinkProperties();
1349 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001350 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001351 }
1352 }
1353
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001354 /**
1355 * Returns the IP information for a given network type.
1356 *
1357 * @param networkType the network type of interest.
1358 * @return a {@link LinkProperties} object describing the IP info
1359 * for the given networkType, or {@code null} if there is
1360 * no current default network.
1361 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001362 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001363 * @deprecated This method does not support multiple connected networks
1364 * of the same type. Use {@link #getAllNetworks},
1365 * {@link #getNetworkInfo(android.net.Network)}, and
1366 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001367 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001368 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001369 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001370 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001371 public LinkProperties getLinkProperties(int networkType) {
1372 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001373 return mService.getLinkPropertiesForType(networkType);
1374 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001375 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001376 }
1377 }
1378
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001379 /**
1380 * Get the {@link LinkProperties} for the given {@link Network}. This
1381 * will return {@code null} if the network is unknown.
1382 *
1383 * @param network The {@link Network} object identifying the network in question.
1384 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001385 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001386 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001387 @Nullable
1388 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001389 try {
1390 return mService.getLinkProperties(network);
1391 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001392 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001393 }
1394 }
1395
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001396 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001397 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001398 * will return {@code null} if the network is unknown.
1399 *
1400 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001401 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001402 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001403 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001404 @Nullable
1405 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001406 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001407 return mService.getNetworkCapabilities(
1408 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001409 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001410 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001411 }
1412 }
1413
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001414 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001415 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001416 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1417 * portal is present.
1418 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1419 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1420 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001421 * The system network validation may be using different strategies to detect captive portals,
1422 * so this method does not necessarily return a URL used by the system. It only returns a URL
1423 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001424 *
Udam Sainicd645462016-01-04 12:16:14 -08001425 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001426 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1427 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001428 */
paulhu8e96a752019-08-12 16:25:11 +08001429 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001430 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001431 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001432 public String getCaptivePortalServerUrl() {
1433 try {
1434 return mService.getCaptivePortalServerUrl();
1435 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001436 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001437 }
1438 }
1439
1440 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001441 * Tells the underlying networking system that the caller wants to
1442 * begin using the named feature. The interpretation of {@code feature}
1443 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001444 *
1445 * <p>This method requires the caller to hold either the
1446 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1447 * or the ability to modify system settings as determined by
1448 * {@link android.provider.Settings.System#canWrite}.</p>
1449 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001450 * @param networkType specifies which network the request pertains to
1451 * @param feature the name of the feature to be used
1452 * @return an integer value representing the outcome of the request.
1453 * The interpretation of this value is specific to each networking
1454 * implementation+feature combination, except that the value {@code -1}
1455 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001456 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001457 * @deprecated Deprecated in favor of the cleaner
1458 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001459 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001460 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001461 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001462 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001463 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001464 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001465 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001466 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1467 if (netCap == null) {
1468 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1469 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001470 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001471 }
1472
1473 NetworkRequest request = null;
1474 synchronized (sLegacyRequests) {
1475 LegacyRequest l = sLegacyRequests.get(netCap);
1476 if (l != null) {
1477 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1478 renewRequestLocked(l);
1479 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001480 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001481 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001482 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001483 }
1484 }
1485
1486 request = requestNetworkForFeatureLocked(netCap);
1487 }
1488 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001489 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001490 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001491 } else {
1492 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001493 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001494 }
1495 }
1496
1497 /**
1498 * Tells the underlying networking system that the caller is finished
1499 * using the named feature. The interpretation of {@code feature}
1500 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001501 *
1502 * <p>This method requires the caller to hold either the
1503 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1504 * or the ability to modify system settings as determined by
1505 * {@link android.provider.Settings.System#canWrite}.</p>
1506 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001507 * @param networkType specifies which network the request pertains to
1508 * @param feature the name of the feature that is no longer needed
1509 * @return an integer value representing the outcome of the request.
1510 * The interpretation of this value is specific to each networking
1511 * implementation+feature combination, except that the value {@code -1}
1512 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001513 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001514 * @deprecated Deprecated in favor of the cleaner
1515 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001516 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001517 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001518 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001519 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001520 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001521 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001522 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001523 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1524 if (netCap == null) {
1525 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1526 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001527 return -1;
1528 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001529
Paul Jensen49f74a32014-12-17 10:39:34 -05001530 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001531 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001532 }
1533 return 1;
1534 }
1535
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001536 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001537 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1538 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001539 switch (feature) {
1540 case "enableCBS":
1541 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1542 case "enableDUN":
1543 case "enableDUNAlways":
1544 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1545 case "enableFOTA":
1546 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1547 case "enableHIPRI":
1548 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1549 case "enableIMS":
1550 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1551 case "enableMMS":
1552 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1553 case "enableSUPL":
1554 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1555 default:
1556 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001557 }
Erik Klinece55eb12017-01-26 18:08:28 +09001558 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1559 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001560 }
1561 return null;
1562 }
1563
Robert Greenwalt802c1102014-06-02 15:32:02 -07001564 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001565 if (netCap == null) return TYPE_NONE;
1566 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1567 return TYPE_MOBILE_CBS;
1568 }
1569 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1570 return TYPE_MOBILE_IMS;
1571 }
1572 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1573 return TYPE_MOBILE_FOTA;
1574 }
1575 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1576 return TYPE_MOBILE_DUN;
1577 }
1578 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1579 return TYPE_MOBILE_SUPL;
1580 }
1581 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1582 return TYPE_MOBILE_MMS;
1583 }
1584 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1585 return TYPE_MOBILE_HIPRI;
1586 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001587 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1588 return TYPE_WIFI_P2P;
1589 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001590 return TYPE_NONE;
1591 }
1592
1593 private static class LegacyRequest {
1594 NetworkCapabilities networkCapabilities;
1595 NetworkRequest networkRequest;
1596 int expireSequenceNumber;
1597 Network currentNetwork;
1598 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001599
1600 private void clearDnsBinding() {
1601 if (currentNetwork != null) {
1602 currentNetwork = null;
1603 setProcessDefaultNetworkForHostResolution(null);
1604 }
1605 }
1606
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001607 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001608 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001609 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001610 currentNetwork = network;
1611 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001612 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001613 }
1614 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001615 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001616 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001617 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1618 }
1619 };
1620 }
1621
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001622 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001623 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1624 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001625
1626 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1627 synchronized (sLegacyRequests) {
1628 LegacyRequest l = sLegacyRequests.get(netCap);
1629 if (l != null) return l.networkRequest;
1630 }
1631 return null;
1632 }
1633
1634 private void renewRequestLocked(LegacyRequest l) {
1635 l.expireSequenceNumber++;
1636 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1637 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1638 }
1639
1640 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1641 int ourSeqNum = -1;
1642 synchronized (sLegacyRequests) {
1643 LegacyRequest l = sLegacyRequests.get(netCap);
1644 if (l == null) return;
1645 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001646 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001647 }
1648 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1649 }
1650
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001651 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001652 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1653 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001654 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001655 try {
1656 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001657 } catch (RemoteException e) {
1658 throw e.rethrowFromSystemServer();
1659 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001660 LegacyRequest l = new LegacyRequest();
1661 l.networkCapabilities = netCap;
1662 l.delay = delay;
1663 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001664 l.networkRequest = sendRequestForNetwork(
1665 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001666 if (l.networkRequest == null) return null;
1667 sLegacyRequests.put(netCap, l);
1668 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1669 return l.networkRequest;
1670 }
1671
1672 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1673 if (delay >= 0) {
1674 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001675 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001676 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1677 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001678 }
1679 }
1680
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001681 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001682 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1683 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001684 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001685 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001686 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001687 if (l == null) return false;
1688 unregisterNetworkCallback(l.networkCallback);
1689 l.clearDnsBinding();
1690 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001691 }
1692
Erik Klinece55eb12017-01-26 18:08:28 +09001693 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1694 static {
1695 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1696 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1697 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1698 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1699 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1700 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1701 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1702 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1703 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1704 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1705 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1706 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1707 }
1708
1709 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1710 static {
1711 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1712 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1713 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1714 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1715 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1716 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1717 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1718 }
1719
1720 /**
1721 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1722 * instance suitable for registering a request or callback. Throws an
1723 * IllegalArgumentException if no mapping from the legacy type to
1724 * NetworkCapabilities is known.
1725 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001726 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1727 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001728 * @hide
1729 */
1730 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1731 final NetworkCapabilities nc = new NetworkCapabilities();
1732
1733 // Map from type to transports.
1734 final int NOT_FOUND = -1;
1735 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichibc1104b2017-05-09 15:19:01 +09001736 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001737 nc.addTransportType(transport);
1738
1739 // Map from type to capabilities.
1740 nc.addCapability(sLegacyTypeToCapability.get(
1741 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1742 nc.maybeMarkCapabilitiesRestricted();
1743 return nc;
1744 }
1745
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001746 /** @hide */
1747 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001748 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001749 public PacketKeepaliveCallback() {
1750 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001751 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001752 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001753 public void onStarted() {}
1754 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001755 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001756 public void onStopped() {}
1757 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001758 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001759 public void onError(int error) {}
1760 }
1761
1762 /**
1763 * Allows applications to request that the system periodically send specific packets on their
1764 * behalf, using hardware offload to save battery power.
1765 *
1766 * To request that the system send keepalives, call one of the methods that return a
1767 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1768 * passing in a non-null callback. If the callback is successfully started, the callback's
1769 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1770 * specifying one of the {@code ERROR_*} constants in this class.
1771 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001772 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1773 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1774 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001775 *
junyulai4c95b082018-12-27 17:25:29 +08001776 * @deprecated Use {@link SocketKeepalive} instead.
1777 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001778 * @hide
1779 */
1780 public class PacketKeepalive {
1781
1782 private static final String TAG = "PacketKeepalive";
1783
1784 /** @hide */
1785 public static final int SUCCESS = 0;
1786
1787 /** @hide */
1788 public static final int NO_KEEPALIVE = -1;
1789
1790 /** @hide */
1791 public static final int BINDER_DIED = -10;
1792
1793 /** The specified {@code Network} is not connected. */
1794 public static final int ERROR_INVALID_NETWORK = -20;
1795 /** The specified IP addresses are invalid. For example, the specified source IP address is
1796 * not configured on the specified {@code Network}. */
1797 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1798 /** The requested port is invalid. */
1799 public static final int ERROR_INVALID_PORT = -22;
1800 /** The packet length is invalid (e.g., too long). */
1801 public static final int ERROR_INVALID_LENGTH = -23;
1802 /** The packet transmission interval is invalid (e.g., too short). */
1803 public static final int ERROR_INVALID_INTERVAL = -24;
1804
1805 /** The hardware does not support this request. */
1806 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001807 /** The hardware returned an error. */
1808 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001809
Nathan Harold0990bc82018-02-14 13:09:45 -08001810 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001811 public static final int NATT_PORT = 4500;
1812
Nathan Harold0990bc82018-02-14 13:09:45 -08001813 /** The minimum interval in seconds between keepalive packet transmissions */
1814 public static final int MIN_INTERVAL = 10;
1815
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001816 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001817 private final ISocketKeepaliveCallback mCallback;
1818 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001819
1820 private volatile Integer mSlot;
1821
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001822 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001823 public void stop() {
1824 try {
junyulai070f9ff2019-01-16 20:23:34 +08001825 mExecutor.execute(() -> {
1826 try {
1827 if (mSlot != null) {
1828 mService.stopKeepalive(mNetwork, mSlot);
1829 }
1830 } catch (RemoteException e) {
1831 Log.e(TAG, "Error stopping packet keepalive: ", e);
1832 throw e.rethrowFromSystemServer();
1833 }
1834 });
1835 } catch (RejectedExecutionException e) {
1836 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001837 }
1838 }
1839
1840 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09001841 Preconditions.checkNotNull(network, "network cannot be null");
1842 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001843 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001844 mExecutor = Executors.newSingleThreadExecutor();
1845 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001846 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001847 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001848 final long token = Binder.clearCallingIdentity();
1849 try {
1850 mExecutor.execute(() -> {
1851 mSlot = slot;
1852 callback.onStarted();
1853 });
1854 } finally {
1855 Binder.restoreCallingIdentity(token);
1856 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001857 }
junyulai070f9ff2019-01-16 20:23:34 +08001858
1859 @Override
1860 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001861 final long token = Binder.clearCallingIdentity();
1862 try {
1863 mExecutor.execute(() -> {
1864 mSlot = null;
1865 callback.onStopped();
1866 });
1867 } finally {
1868 Binder.restoreCallingIdentity(token);
1869 }
junyulai070f9ff2019-01-16 20:23:34 +08001870 mExecutor.shutdown();
1871 }
1872
1873 @Override
1874 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001875 final long token = Binder.clearCallingIdentity();
1876 try {
1877 mExecutor.execute(() -> {
1878 mSlot = null;
1879 callback.onError(error);
1880 });
1881 } finally {
1882 Binder.restoreCallingIdentity(token);
1883 }
junyulai070f9ff2019-01-16 20:23:34 +08001884 mExecutor.shutdown();
1885 }
1886
1887 @Override
1888 public void onDataReceived() {
1889 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1890 // this callback when data is received.
1891 }
1892 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001893 }
1894 }
1895
1896 /**
1897 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1898 *
junyulai4c95b082018-12-27 17:25:29 +08001899 * @deprecated Use {@link #createSocketKeepalive} instead.
1900 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001901 * @hide
1902 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001903 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001904 public PacketKeepalive startNattKeepalive(
1905 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1906 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1907 final PacketKeepalive k = new PacketKeepalive(network, callback);
1908 try {
junyulai070f9ff2019-01-16 20:23:34 +08001909 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001910 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1911 } catch (RemoteException e) {
1912 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001913 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001914 }
1915 return k;
1916 }
1917
Chiachang Wang619319a2021-01-15 11:06:21 +08001918 // Construct an invalid fd.
1919 private ParcelFileDescriptor createInvalidFd() {
1920 final int invalidFd = -1;
1921 return ParcelFileDescriptor.adoptFd(invalidFd);
1922 }
1923
The Android Open Source Project28527d22009-03-03 19:31:44 -08001924 /**
junyulai4c95b082018-12-27 17:25:29 +08001925 * Request that keepalives be started on a IPsec NAT-T socket.
1926 *
1927 * @param network The {@link Network} the socket is on.
1928 * @param socket The socket that needs to be kept alive.
1929 * @param source The source address of the {@link UdpEncapsulationSocket}.
1930 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1931 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1932 * must run callback sequentially, otherwise the order of callbacks cannot be
1933 * guaranteed.
1934 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1935 * changes. Must be extended by applications that use this API.
1936 *
junyulai0835a1e2019-01-08 20:04:33 +08001937 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1938 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001939 **/
junyulai7e06ad42019-03-04 22:45:36 +08001940 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001941 @NonNull UdpEncapsulationSocket socket,
1942 @NonNull InetAddress source,
1943 @NonNull InetAddress destination,
1944 @NonNull @CallbackExecutor Executor executor,
1945 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001946 ParcelFileDescriptor dup;
1947 try {
junyulai828dad12019-03-27 11:00:37 +08001948 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1949 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001950 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1951 } catch (IOException ignored) {
1952 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1953 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001954 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001955 }
1956 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1957 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08001958 }
1959
1960 /**
1961 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1962 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1963 *
1964 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08001965 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1966 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1967 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08001968 * @param source The source address of the {@link UdpEncapsulationSocket}.
1969 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1970 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1971 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1972 * must run callback sequentially, otherwise the order of callbacks cannot be
1973 * guaranteed.
1974 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1975 * changes. Must be extended by applications that use this API.
1976 *
junyulai0835a1e2019-01-08 20:04:33 +08001977 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1978 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08001979 * @hide
1980 */
1981 @SystemApi
1982 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08001983 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1984 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08001985 @NonNull InetAddress source,
1986 @NonNull InetAddress destination,
1987 @NonNull @CallbackExecutor Executor executor,
1988 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001989 ParcelFileDescriptor dup;
1990 try {
junyulai828dad12019-03-27 11:00:37 +08001991 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08001992 dup = pfd.dup();
1993 } catch (IOException ignored) {
1994 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1995 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001996 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001997 }
1998 return new NattSocketKeepalive(mService, network, dup,
1999 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002000 }
2001
2002 /**
junyulai0835a1e2019-01-08 20:04:33 +08002003 * Request that keepalives be started on a TCP socket.
2004 * The socket must be established.
2005 *
2006 * @param network The {@link Network} the socket is on.
2007 * @param socket The socket that needs to be kept alive.
2008 * @param executor The executor on which callback will be invoked. This implementation assumes
2009 * the provided {@link Executor} runs the callbacks in sequence with no
2010 * concurrency. Failing this, no guarantee of correctness can be made. It is
2011 * the responsibility of the caller to ensure the executor provides this
2012 * guarantee. A simple way of creating such an executor is with the standard
2013 * tool {@code Executors.newSingleThreadExecutor}.
2014 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2015 * changes. Must be extended by applications that use this API.
2016 *
2017 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2018 * given socket.
2019 * @hide
2020 */
2021 @SystemApi
2022 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002023 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002024 @NonNull Socket socket,
2025 @NonNull Executor executor,
2026 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002027 ParcelFileDescriptor dup;
2028 try {
2029 dup = ParcelFileDescriptor.fromSocket(socket);
2030 } catch (UncheckedIOException ignored) {
2031 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2032 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002033 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002034 }
2035 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002036 }
2037
2038 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002039 * Ensure that a network route exists to deliver traffic to the specified
2040 * host via the specified network interface. An attempt to add a route that
2041 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002042 *
2043 * <p>This method requires the caller to hold either the
2044 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2045 * or the ability to modify system settings as determined by
2046 * {@link android.provider.Settings.System#canWrite}.</p>
2047 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002048 * @param networkType the type of the network over which traffic to the specified
2049 * host is to be routed
2050 * @param hostAddress the IP address of the host to which the route is desired
2051 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002052 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002053 * @deprecated Deprecated in favor of the
2054 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2055 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002056 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002057 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002058 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002059 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002060 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002061 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002062 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002063 }
2064
2065 /**
2066 * Ensure that a network route exists to deliver traffic to the specified
2067 * host via the specified network interface. An attempt to add a route that
2068 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002069 *
2070 * <p>This method requires the caller to hold either the
2071 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2072 * or the ability to modify system settings as determined by
2073 * {@link android.provider.Settings.System#canWrite}.</p>
2074 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002075 * @param networkType the type of the network over which traffic to the specified
2076 * host is to be routed
2077 * @param hostAddress the IP address of the host to which the route is desired
2078 * @return {@code true} on success, {@code false} on failure
2079 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002080 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002081 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002082 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002083 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002084 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002085 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002086 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002087 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002088 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2089 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002090 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002091 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002092 }
2093 }
2094
2095 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002096 * @return the context's attribution tag
2097 */
2098 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2099 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002100 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002101 }
2102
2103 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002104 * Returns the value of the setting for background data usage. If false,
2105 * applications should not use the network if the application is not in the
2106 * foreground. Developers should respect this setting, and check the value
2107 * of this before performing any background data operations.
2108 * <p>
2109 * All applications that have background services that use the network
2110 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002111 * <p>
Scott Main50589142011-10-06 18:32:43 -07002112 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002113 * background data depends on several combined factors, and this method will
2114 * always return {@code true}. Instead, when background data is unavailable,
2115 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002116 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002117 * @return Whether background data usage is allowed.
2118 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002119 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002120 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002121 // assume that background data is allowed; final authority is
2122 // NetworkInfo which may be blocked.
2123 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002124 }
2125
2126 /**
2127 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002128 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002129 * @param allowBackgroundData Whether an application should use data while
2130 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002131 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002132 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2133 * @see #getBackgroundDataSetting()
2134 * @hide
2135 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002136 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002137 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002138 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002139 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002140 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002141
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002142 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002143 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002144 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002145 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002146 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002147 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002148 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002149 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2150 if (tm != null) {
2151 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2152 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2153 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2154 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2155 + " retVal=" + retVal);
2156 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002157 }
Wink Saville689f7042014-12-05 11:10:30 -08002158 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002159 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002160 }
2161
The Android Open Source Project28527d22009-03-03 19:31:44 -08002162 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002163 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002164 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002165 */
2166 public interface OnNetworkActiveListener {
2167 /**
2168 * Called on the main thread of the process to report that the current data network
2169 * has become active, and it is now a good time to perform any pending network
2170 * operations. Note that this listener only tells you when the network becomes
2171 * active; if at any other time you want to know whether it is active (and thus okay
2172 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002173 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002174 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002175 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002176 }
2177
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002178 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002179 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002180
2181 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002182 * Start listening to reports when the system's default data network is active, meaning it is
2183 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2184 * to determine the current state of the system's default network after registering the
2185 * listener.
2186 * <p>
2187 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002188 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002189 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002190 *
2191 * @param l The listener to be told when the network is active.
2192 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002193 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002194 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2195 @Override
2196 public void onNetworkActive() throws RemoteException {
2197 l.onNetworkActive();
2198 }
2199 };
2200
2201 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002202 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002203 mNetworkActivityListeners.put(l, rl);
2204 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002205 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002206 }
2207 }
2208
2209 /**
2210 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002211 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002212 *
2213 * @param l Previously registered listener.
2214 */
Chalard Jean158702d2019-01-07 19:26:34 +09002215 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002216 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichibc1104b2017-05-09 15:19:01 +09002217 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002218 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002219 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002220 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002221 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002222 }
2223 }
2224
2225 /**
2226 * Return whether the data network is currently active. An active network means that
2227 * it is currently in a high power state for performing data transmission. On some
2228 * types of networks, it may be expensive to move and stay in such a state, so it is
2229 * more power efficient to batch network traffic together when the radio is already in
2230 * this state. This method tells you whether right now is currently a good time to
2231 * initiate network traffic, as the network is already active.
2232 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002233 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002234 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002235 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002236 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002237 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002238 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002239 }
2240
2241 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242 * {@hide}
2243 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002244 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002245 mContext = Preconditions.checkNotNull(context, "missing context");
2246 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002247 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002248 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002249 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002250
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002251 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002252 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002253 public static ConnectivityManager from(Context context) {
2254 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2255 }
2256
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002257 /** @hide */
2258 public NetworkRequest getDefaultRequest() {
2259 try {
2260 // This is not racy as the default request is final in ConnectivityService.
2261 return mService.getDefaultRequest();
2262 } catch (RemoteException e) {
2263 throw e.rethrowFromSystemServer();
2264 }
2265 }
2266
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002267 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002268 * Check if the package is a allowed to write settings. This also accounts that such an access
2269 * happened.
2270 *
2271 * @return {@code true} iff the package is allowed to write settings.
2272 */
2273 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2274 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2275 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2276 boolean throwException) {
2277 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2278 throwException);
2279 }
2280
2281 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002282 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2283 * situations where a Context pointer is unavailable.
2284 * @hide
2285 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002286 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002287 static ConnectivityManager getInstanceOrNull() {
2288 return sInstance;
2289 }
2290
2291 /**
2292 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2293 * situations where a Context pointer is unavailable.
2294 * @hide
2295 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002296 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002297 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002298 private static ConnectivityManager getInstance() {
2299 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002300 throw new IllegalStateException("No ConnectivityManager yet constructed");
2301 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002302 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002303 }
2304
2305 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002306 * Get the set of tetherable, available interfaces. This list is limited by
2307 * device configuration and current interface existence.
2308 *
2309 * @return an array of 0 or more Strings of tetherable interface names.
2310 *
markchien6ae63e52020-01-21 13:11:06 +08002311 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002312 * {@hide}
2313 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002314 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002315 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002316 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002317 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002318 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002319 }
2320
2321 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002322 * Get the set of tethered interfaces.
2323 *
2324 * @return an array of 0 or more String of currently tethered interface names.
2325 *
markchien6ae63e52020-01-21 13:11:06 +08002326 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002327 * {@hide}
2328 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002329 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002330 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002331 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002332 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002333 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002334 }
2335
2336 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002337 * Get the set of interface names which attempted to tether but
2338 * failed. Re-attempting to tether may cause them to reset to the Tethered
2339 * state. Alternatively, causing the interface to be destroyed and recreated
2340 * may cause them to reset to the available state.
2341 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2342 * information on the cause of the errors.
2343 *
2344 * @return an array of 0 or more String indicating the interface names
2345 * which failed to tether.
2346 *
markchien6ae63e52020-01-21 13:11:06 +08002347 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002348 * {@hide}
2349 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002350 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002351 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002352 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002353 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002354 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002355 }
2356
2357 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002358 * Get the set of tethered dhcp ranges.
2359 *
markchien2e6ba522020-02-14 11:55:48 +08002360 * @deprecated This method is not supported.
2361 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002362 * {@hide}
2363 */
paulhu8e96a752019-08-12 16:25:11 +08002364 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002365 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002366 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002367 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002368 }
2369
2370 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002371 * Attempt to tether the named interface. This will setup a dhcp server
2372 * on the interface, forward and NAT IP packets and forward DNS requests
2373 * to the best active upstream network interface. Note that if no upstream
2374 * IP network interface is available, dhcp will still run and traffic will be
2375 * allowed between the tethered devices and this device, though upstream net
2376 * access will of course fail until an upstream network interface becomes
2377 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002378 *
2379 * <p>This method requires the caller to hold either the
2380 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2381 * or the ability to modify system settings as determined by
2382 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002383 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002384 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2385 * and WifiStateMachine which need direct access. All other clients should use
2386 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2387 * logic.</p>
2388 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002389 * @param iface the interface name to tether.
2390 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002391 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002392 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002393 * {@hide}
2394 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002395 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002396 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002397 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002398 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002399 }
2400
2401 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002402 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002403 *
2404 * <p>This method requires the caller to hold either the
2405 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2406 * or the ability to modify system settings as determined by
2407 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002408 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002409 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2410 * and WifiStateMachine which need direct access. All other clients should use
2411 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2412 * logic.</p>
2413 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002414 * @param iface the interface name to untether.
2415 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2416 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002417 * {@hide}
2418 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002419 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002420 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002421 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002422 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002423 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002424
2425 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002426 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002427 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002428 * due to device configuration.
2429 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002430 * <p>If this app does not have permission to use this API, it will always
2431 * return false rather than throw an exception.</p>
2432 *
2433 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2434 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2435 *
2436 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2437 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2438 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002439 * @return a boolean - {@code true} indicating Tethering is supported.
2440 *
markchien6ae63e52020-01-21 13:11:06 +08002441 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002442 * {@hide}
2443 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002444 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002445 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2446 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002447 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002448 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002449 }
2450
2451 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002452 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002453 *
2454 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002455 * @hide
2456 */
2457 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002458 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002459 public static abstract class OnStartTetheringCallback {
2460 /**
2461 * Called when tethering has been successfully started.
2462 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002463 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002464
2465 /**
2466 * Called when starting tethering failed.
2467 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002468 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002469 }
2470
2471 /**
2472 * Convenient overload for
2473 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2474 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002475 *
2476 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002477 * @hide
2478 */
2479 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002480 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002481 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002482 public void startTethering(int type, boolean showProvisioningUi,
2483 final OnStartTetheringCallback callback) {
2484 startTethering(type, showProvisioningUi, callback, null);
2485 }
2486
2487 /**
2488 * Runs tether provisioning for the given type if needed and then starts tethering if
2489 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2490 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2491 * schedules tether provisioning re-checks if appropriate.
2492 *
2493 * @param type The type of tethering to start. Must be one of
2494 * {@link ConnectivityManager.TETHERING_WIFI},
2495 * {@link ConnectivityManager.TETHERING_USB}, or
2496 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2497 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2498 * is one. This should be true the first time this function is called and also any time
2499 * the user can see this UI. It gives users information from their carrier about the
2500 * check failing and how they can sign up for tethering if possible.
2501 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2502 * of the result of trying to tether.
2503 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002504 *
2505 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002506 * @hide
2507 */
2508 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002509 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002510 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002511 public void startTethering(int type, boolean showProvisioningUi,
2512 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002513 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002514
markchien91c78e52020-01-20 19:31:56 +08002515 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002516 @Override
markchien91c78e52020-01-20 19:31:56 +08002517 public void execute(Runnable command) {
2518 if (handler == null) {
2519 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002520 } else {
markchien91c78e52020-01-20 19:31:56 +08002521 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002522 }
2523 }
2524 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002525
markchien91c78e52020-01-20 19:31:56 +08002526 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2527 @Override
2528 public void onTetheringStarted() {
2529 callback.onTetheringStarted();
2530 }
2531
2532 @Override
markchienf47d8342020-03-19 13:37:43 +08002533 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002534 callback.onTetheringFailed();
2535 }
2536 };
2537
2538 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002539 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002540
Amos Bianchia9b415a2020-03-04 11:07:38 -08002541 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002542 }
2543
2544 /**
2545 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2546 * applicable.
2547 *
2548 * @param type The type of tethering to stop. Must be one of
2549 * {@link ConnectivityManager.TETHERING_WIFI},
2550 * {@link ConnectivityManager.TETHERING_USB}, or
2551 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002552 *
2553 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002554 * @hide
2555 */
2556 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002557 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002558 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002559 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002560 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002561 }
2562
2563 /**
markchien4ef53e82019-02-27 14:56:11 +08002564 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2565 * upstream status.
2566 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002567 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002568 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002569 */
2570 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002571 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002572 public abstract static class OnTetheringEventCallback {
2573
2574 /**
2575 * Called when tethering upstream changed. This can be called multiple times and can be
2576 * called any time.
2577 *
2578 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2579 * have any upstream.
2580 */
2581 public void onUpstreamChanged(@Nullable Network network) {}
2582 }
2583
markchien6ae63e52020-01-21 13:11:06 +08002584 @GuardedBy("mTetheringEventCallbacks")
2585 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2586 mTetheringEventCallbacks = new ArrayMap<>();
2587
markchien4ef53e82019-02-27 14:56:11 +08002588 /**
2589 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002590 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002591 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2592 * with a null argument. The same callback object cannot be registered twice.
2593 *
2594 * @param executor the executor on which callback will be invoked.
2595 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002596 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002597 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002598 * @hide
2599 */
2600 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002601 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002602 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2603 public void registerTetheringEventCallback(
2604 @NonNull @CallbackExecutor Executor executor,
2605 @NonNull final OnTetheringEventCallback callback) {
2606 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2607
markchien6ae63e52020-01-21 13:11:06 +08002608 final TetheringEventCallback tetherCallback =
2609 new TetheringEventCallback() {
2610 @Override
2611 public void onUpstreamChanged(@Nullable Network network) {
2612 callback.onUpstreamChanged(network);
2613 }
2614 };
2615
2616 synchronized (mTetheringEventCallbacks) {
2617 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002618 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002619 }
markchien4ef53e82019-02-27 14:56:11 +08002620 }
2621
2622 /**
2623 * Remove tethering event callback previously registered with
2624 * {@link #registerTetheringEventCallback}.
2625 *
2626 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002627 *
2628 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002629 * @hide
2630 */
2631 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002632 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002633 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2634 public void unregisterTetheringEventCallback(
2635 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002636 Objects.requireNonNull(callback, "The callback must be non-null");
2637 synchronized (mTetheringEventCallbacks) {
2638 final TetheringEventCallback tetherCallback =
2639 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002640 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002641 }
markchien4ef53e82019-02-27 14:56:11 +08002642 }
2643
2644
2645 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002646 * Get the list of regular expressions that define any tetherable
2647 * USB network interfaces. If USB tethering is not supported by the
2648 * device, this list should be empty.
2649 *
2650 * @return an array of 0 or more regular expression Strings defining
2651 * what interfaces are considered tetherable usb interfaces.
2652 *
markchien6ae63e52020-01-21 13:11:06 +08002653 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002654 * {@hide}
2655 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002656 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002657 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002658 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002659 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002660 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002661 }
2662
2663 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002664 * Get the list of regular expressions that define any tetherable
2665 * Wifi network interfaces. If Wifi tethering is not supported by the
2666 * device, this list should be empty.
2667 *
2668 * @return an array of 0 or more regular expression Strings defining
2669 * what interfaces are considered tetherable wifi interfaces.
2670 *
markchien6ae63e52020-01-21 13:11:06 +08002671 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002672 * {@hide}
2673 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002674 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002675 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002676 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002677 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002678 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002679 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002680
Danica Chang96567052010-08-11 14:54:43 -07002681 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002682 * Get the list of regular expressions that define any tetherable
2683 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2684 * device, this list should be empty.
2685 *
2686 * @return an array of 0 or more regular expression Strings defining
2687 * what interfaces are considered tetherable bluetooth interfaces.
2688 *
markchien6ae63e52020-01-21 13:11:06 +08002689 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2690 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002691 * {@hide}
2692 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002693 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002694 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002695 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002696 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002697 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002698 }
2699
Mike Lockwooded4a1742011-07-19 13:04:47 -07002700 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002701 * Attempt to both alter the mode of USB and Tethering of USB. A
2702 * utility method to deal with some of the complexity of USB - will
2703 * attempt to switch to Rndis and subsequently tether the resulting
2704 * interface on {@code true} or turn off tethering and switch off
2705 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002706 *
2707 * <p>This method requires the caller to hold either the
2708 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2709 * or the ability to modify system settings as determined by
2710 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002711 *
2712 * @param enable a boolean - {@code true} to enable tethering
2713 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002714 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002715 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002716 * {@hide}
2717 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002718 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002719 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002720 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002721 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002722 }
2723
markchien6ae63e52020-01-21 13:11:06 +08002724 /**
2725 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2726 * {@hide}
2727 */
markchien0f45bb92019-01-16 17:44:13 +08002728 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002729 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002730 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002731 /**
2732 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2733 * {@hide}
2734 */
2735 @Deprecated
2736 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2737 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2738 /**
2739 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2740 * {@hide}
2741 */
2742 @Deprecated
2743 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2744 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2745 /**
2746 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2747 * {@hide}
2748 */
2749 @Deprecated
2750 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2751 /**
2752 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2753 * {@hide}
2754 */
2755 @Deprecated
2756 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2757 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2758 /**
markchienf47d8342020-03-19 13:37:43 +08002759 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002760 * {@hide}
2761 */
2762 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002763 public static final int TETHER_ERROR_MASTER_ERROR =
2764 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002765 /**
2766 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2767 * {@hide}
2768 */
2769 @Deprecated
2770 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2771 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2772 /**
2773 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2774 * {@hide}
2775 */
2776 @Deprecated
2777 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2778 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2779 /**
markchienf47d8342020-03-19 13:37:43 +08002780 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002781 * {@hide}
2782 */
2783 @Deprecated
2784 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002785 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002786 /**
markchienf47d8342020-03-19 13:37:43 +08002787 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002788 * {@hide}
2789 */
2790 @Deprecated
2791 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002792 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002793 /**
2794 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2795 * {@hide}
2796 */
2797 @Deprecated
2798 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2799 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2800 /**
markchienf47d8342020-03-19 13:37:43 +08002801 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002802 * {@hide}
2803 */
markchien0f45bb92019-01-16 17:44:13 +08002804 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002805 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002806 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002807 /**
2808 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2809 * {@hide}
2810 */
2811 @Deprecated
2812 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2813 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2814 /**
2815 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2816 * {@hide}
2817 */
markchien0f45bb92019-01-16 17:44:13 +08002818 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002819 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002820 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002821
2822 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002823 * Get a more detailed error code after a Tethering or Untethering
2824 * request asynchronously failed.
2825 *
2826 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002827 * @return error The error code of the last error tethering or untethering the named
2828 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002829 *
markchien6ae63e52020-01-21 13:11:06 +08002830 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002831 * {@hide}
2832 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002833 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002834 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002835 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002836 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002837 int error = mTetheringManager.getLastTetherError(iface);
2838 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2839 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2840 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2841 // instead.
2842 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2843 }
2844 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002845 }
2846
markchienbf5ab012019-03-06 16:25:00 +08002847 /** @hide */
2848 @Retention(RetentionPolicy.SOURCE)
2849 @IntDef(value = {
2850 TETHER_ERROR_NO_ERROR,
2851 TETHER_ERROR_PROVISION_FAILED,
2852 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2853 })
2854 public @interface EntitlementResultCode {
2855 }
2856
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002857 /**
markchienbf5ab012019-03-06 16:25:00 +08002858 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002859 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002860 *
2861 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002862 * @hide
2863 */
2864 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002865 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002866 public interface OnTetheringEntitlementResultListener {
2867 /**
2868 * Called to notify entitlement result.
2869 *
2870 * @param resultCode an int value of entitlement result. It may be one of
2871 * {@link #TETHER_ERROR_NO_ERROR},
2872 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2873 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2874 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002875 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002876 }
2877
2878 /**
markchien0f45bb92019-01-16 17:44:13 +08002879 * Get the last value of the entitlement check on this downstream. If the cached value is
2880 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2881 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2882 * guaranteed that the UI-based entitlement check will complete in any specific time period
2883 * and may in fact never complete. Any successful entitlement check the platform performs for
2884 * any reason will update the cached value.
2885 *
2886 * @param type the downstream type of tethering. Must be one of
2887 * {@link #TETHERING_WIFI},
2888 * {@link #TETHERING_USB}, or
2889 * {@link #TETHERING_BLUETOOTH}.
2890 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002891 * @param executor the executor on which callback will be invoked.
2892 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2893 * notify the caller of the result of entitlement check. The listener may be called zero
2894 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002895 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002896 * {@hide}
2897 */
2898 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002899 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002900 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002901 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2902 @NonNull @CallbackExecutor Executor executor,
2903 @NonNull final OnTetheringEntitlementResultListener listener) {
2904 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2905 ResultReceiver wrappedListener = new ResultReceiver(null) {
2906 @Override
2907 protected void onReceiveResult(int resultCode, Bundle resultData) {
2908 Binder.withCleanCallingIdentity(() ->
2909 executor.execute(() -> {
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002910 listener.onTetheringEntitlementResult(resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002911 }));
2912 }
2913 };
2914
Amos Bianchia9b415a2020-03-04 11:07:38 -08002915 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002916 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002917 }
2918
2919 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002920 * Report network connectivity status. This is currently used only
2921 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002922 * <p>This method requires the caller to hold the permission
2923 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002924 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002925 * @param networkType The type of network you want to report on
2926 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002927 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002928 * {@hide}
2929 */
2930 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002931 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002932 try {
2933 mService.reportInetCondition(networkType, percentage);
2934 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002935 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002936 }
2937 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002938
2939 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002940 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07002941 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002942 * the framework to re-evaluate network connectivity and/or switch to another
2943 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002944 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002945 * @param network The {@link Network} the application was attempting to use
2946 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04002947 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2948 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002949 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002950 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09002951 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002952 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002953 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04002954 // One of these will be ignored because it matches system's current state.
2955 // The other will trigger the necessary reevaluation.
2956 mService.reportNetworkConnectivity(network, true);
2957 mService.reportNetworkConnectivity(network, false);
2958 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002959 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04002960 }
2961 }
2962
2963 /**
2964 * Report to the framework whether a network has working connectivity.
2965 * This provides a hint to the system that a particular network is providing
2966 * working connectivity or not. In response the framework may re-evaluate
2967 * the network's connectivity and might take further action thereafter.
2968 *
2969 * @param network The {@link Network} the application was attempting to use
2970 * or {@code null} to indicate the current default network.
2971 * @param hasConnectivity {@code true} if the application was able to successfully access the
2972 * Internet using {@code network} or {@code false} if not.
2973 */
Chalard Jean158702d2019-01-07 19:26:34 +09002974 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002975 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04002976 try {
2977 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002978 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002979 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002980 }
2981 }
2982
2983 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002984 * Set a network-independent global http proxy. This is not normally what you want
2985 * for typical HTTP proxies - they are general network dependent. However if you're
2986 * doing something unusual like general internal filtering this may be useful. On
2987 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002988 *
2989 * @param p A {@link ProxyInfo} object defining the new global
2990 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002991 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002992 */
paulhu8e96a752019-08-12 16:25:11 +08002993 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04002994 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002995 try {
2996 mService.setGlobalProxy(p);
2997 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002998 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002999 }
3000 }
3001
3002 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003003 * Retrieve any network-independent global HTTP proxy.
3004 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003005 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003006 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003007 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003008 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003009 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003010 try {
3011 return mService.getGlobalProxy();
3012 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003013 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003014 }
3015 }
3016
3017 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003018 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3019 * network-specific HTTP proxy. If {@code network} is null, the
3020 * network-specific proxy returned is the proxy of the default active
3021 * network.
3022 *
3023 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3024 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3025 * or when {@code network} is {@code null},
3026 * the {@code ProxyInfo} for the default active network. Returns
3027 * {@code null} when no proxy applies or the caller doesn't have
3028 * permission to use {@code network}.
3029 * @hide
3030 */
3031 public ProxyInfo getProxyForNetwork(Network network) {
3032 try {
3033 return mService.getProxyForNetwork(network);
3034 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003035 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003036 }
3037 }
3038
3039 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003040 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3041 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003042 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003043 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003044 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003045 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003046 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003047 */
Chalard Jean158702d2019-01-07 19:26:34 +09003048 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003049 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003050 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003051 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003052
3053 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003054 * Returns true if the hardware supports the given network type
3055 * else it returns false. This doesn't indicate we have coverage
3056 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003057 * hardware supports it. For example a GSM phone without a SIM
3058 * should still return {@code true} for mobile data, but a wifi only
3059 * tablet would return {@code false}.
3060 *
3061 * @param networkType The network type we'd like to check
3062 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003063 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003064 * @hide
3065 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003066 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003067 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003068 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003069 public boolean isNetworkSupported(int networkType) {
3070 try {
3071 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003072 } catch (RemoteException e) {
3073 throw e.rethrowFromSystemServer();
3074 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003075 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003076
3077 /**
3078 * Returns if the currently active data network is metered. A network is
3079 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003080 * that connection due to monetary costs, data limitations or
3081 * battery/performance issues. You should check this before doing large
3082 * data transfers, and warn the user or delay the operation until another
3083 * network is available.
3084 *
3085 * @return {@code true} if large transfers should be avoided, otherwise
3086 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003087 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003088 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003089 public boolean isActiveNetworkMetered() {
3090 try {
3091 return mService.isActiveNetworkMetered();
3092 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003093 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003094 }
3095 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003096
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003097 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003098 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003099 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003100 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003101 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003102 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003103 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003104 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003105 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003106 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003107 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003108 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003109 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003110 }
3111 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003112
3113 /**
3114 * Set the value for enabling/disabling airplane mode
3115 *
3116 * @param enable whether to enable airplane mode or not
3117 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003118 * @hide
3119 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003120 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003121 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003122 android.Manifest.permission.NETWORK_SETTINGS,
3123 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3124 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003125 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003126 public void setAirplaneMode(boolean enable) {
3127 try {
3128 mService.setAirplaneMode(enable);
3129 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003130 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003131 }
3132 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003133
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003134 /**
3135 * Registers the specified {@link NetworkProvider}.
3136 * Each listener must only be registered once. The listener can be unregistered with
3137 * {@link #unregisterNetworkProvider}.
3138 *
3139 * @param provider the provider to register
3140 * @return the ID of the provider. This ID must be used by the provider when registering
3141 * {@link android.net.NetworkAgent}s.
3142 * @hide
3143 */
3144 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003145 @RequiresPermission(anyOf = {
3146 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3147 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003148 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3149 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003150 throw new IllegalStateException("NetworkProviders can only be registered once");
3151 }
3152
3153 try {
3154 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3155 provider.getName());
3156 provider.setProviderId(providerId);
3157 } catch (RemoteException e) {
3158 throw e.rethrowFromSystemServer();
3159 }
3160 return provider.getProviderId();
3161 }
3162
3163 /**
3164 * Unregisters the specified NetworkProvider.
3165 *
3166 * @param provider the provider to unregister
3167 * @hide
3168 */
3169 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003170 @RequiresPermission(anyOf = {
3171 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3172 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003173 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3174 try {
3175 mService.unregisterNetworkProvider(provider.getMessenger());
3176 } catch (RemoteException e) {
3177 throw e.rethrowFromSystemServer();
3178 }
3179 provider.setProviderId(NetworkProvider.ID_NONE);
3180 }
3181
3182
3183 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003184 @RequiresPermission(anyOf = {
3185 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3186 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003187 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3188 try {
3189 mService.declareNetworkRequestUnfulfillable(request);
3190 } catch (RemoteException e) {
3191 throw e.rethrowFromSystemServer();
3192 }
3193 }
3194
Chalard Jean29d06db2018-05-02 21:14:54 +09003195 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3196 // of dependent changes that would conflict throughout the automerger graph. Having this
3197 // temporarily helps with the process of going through with all these dependent changes across
3198 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003199 /**
3200 * @hide
3201 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003202 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003203 */
paulhub6ba8e82020-03-04 09:43:41 +08003204 @RequiresPermission(anyOf = {
3205 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3206 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003207 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003208 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003209 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003210 }
3211
3212 /**
3213 * @hide
3214 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003215 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003216 */
paulhub6ba8e82020-03-04 09:43:41 +08003217 @RequiresPermission(anyOf = {
3218 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3219 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003220 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003221 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003222 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003223 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003224 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003225 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003226 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003227 }
3228
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003229 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003230 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3231 * changes. Should be extended by applications wanting notifications.
3232 *
3233 * A {@code NetworkCallback} is registered by calling
3234 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3235 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003236 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003237 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3238 * A {@code NetworkCallback} should be registered at most once at any time.
3239 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003240 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003241 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003242 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003243 * Called when the framework connects to a new network to evaluate whether it satisfies this
3244 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3245 * callback. There is no guarantee that this new network will satisfy any requests, or that
3246 * the network will stay connected for longer than the time necessary to evaluate it.
3247 * <p>
3248 * Most applications <b>should not</b> act on this callback, and should instead use
3249 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3250 * the framework in properly evaluating the network &mdash; for example, an application that
3251 * can automatically log in to a captive portal without user intervention.
3252 *
3253 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003254 *
3255 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003256 */
paulhu1a407652019-03-22 16:35:06 +08003257 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003258
3259 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003260 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003261 * This callback may be called more than once if the {@link Network} that is
3262 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003263 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003264 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003265 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3266 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003267 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003268 * @hide
3269 */
paulhu1a407652019-03-22 16:35:06 +08003270 public void onAvailable(@NonNull Network network,
3271 @NonNull NetworkCapabilities networkCapabilities,
3272 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003273 // Internally only this method is called when a new network is available, and
3274 // it calls the callback in the same way and order that older versions used
3275 // to call so as not to change the behavior.
3276 onAvailable(network);
3277 if (!networkCapabilities.hasCapability(
3278 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3279 onNetworkSuspended(network);
3280 }
3281 onCapabilitiesChanged(network, networkCapabilities);
3282 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003283 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003284 }
3285
3286 /**
3287 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003288 *
3289 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3290 * be available at the same time, and onAvailable will be called for each of these as they
3291 * appear.
3292 *
3293 * <p>For callbacks registered with {@link #requestNetwork} and
3294 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3295 * is the new best network for this request and is now tracked by this callback ; this
3296 * callback will no longer receive method calls about other networks that may have been
3297 * passed to this method previously. The previously-best network may have disconnected, or
3298 * it may still be around and the newly-best network may simply be better.
3299 *
3300 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3301 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3302 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3303 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3304 *
3305 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3306 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3307 * this callback as this is prone to race conditions (there is no guarantee the objects
3308 * returned by these methods will be current). Instead, wait for a call to
3309 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3310 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3311 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003312 *
3313 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003314 */
paulhu1a407652019-03-22 16:35:06 +08003315 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003316
3317 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003318 * Called when the network is about to be lost, typically because there are no outstanding
3319 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3320 * with the new replacement network for graceful handover. This method is not guaranteed
3321 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3322 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003323 *
Chalard Jean01378b62019-08-30 16:27:28 +09003324 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3325 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3326 * this callback as this is prone to race conditions ; calling these methods while in a
3327 * callback may return an outdated or even a null object.
3328 *
3329 * @param network The {@link Network} that is about to be lost.
3330 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3331 * connected for graceful handover; note that the network may still
3332 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003333 */
paulhu1a407652019-03-22 16:35:06 +08003334 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003335
3336 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003337 * Called when a network disconnects or otherwise no longer satisfies this request or
3338 * callback.
3339 *
3340 * <p>If the callback was registered with requestNetwork() or
3341 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3342 * returned by onAvailable() when that network is lost and no other network satisfies
3343 * the criteria of the request.
3344 *
3345 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3346 * each network which no longer satisfies the criteria of the callback.
3347 *
3348 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3349 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3350 * this callback as this is prone to race conditions ; calling these methods while in a
3351 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003352 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003353 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003354 */
paulhu1a407652019-03-22 16:35:06 +08003355 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003356
3357 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003358 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003359 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3360 * requested network request cannot be fulfilled (whether or not a timeout was
3361 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003362 * {@link NetworkRequest} will have already been removed and released, as if
3363 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003364 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003365 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003366
3367 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003368 * Called when the network corresponding to this request changes capabilities but still
3369 * satisfies the requested criteria.
3370 *
3371 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3372 * to be called immediately after {@link #onAvailable}.
3373 *
3374 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3375 * ConnectivityManager methods in this callback as this is prone to race conditions :
3376 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003377 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003378 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003379 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3380 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003381 */
paulhu1a407652019-03-22 16:35:06 +08003382 public void onCapabilitiesChanged(@NonNull Network network,
3383 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003384
3385 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003386 * Called when the network corresponding to this request changes {@link LinkProperties}.
3387 *
3388 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3389 * to be called immediately after {@link #onAvailable}.
3390 *
3391 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3392 * ConnectivityManager methods in this callback as this is prone to race conditions :
3393 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003394 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003395 * @param network The {@link Network} whose link properties have changed.
3396 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003397 */
paulhu1a407652019-03-22 16:35:06 +08003398 public void onLinkPropertiesChanged(@NonNull Network network,
3399 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003400
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003401 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003402 * Called when the network the framework connected to for this request suspends data
3403 * transmission temporarily.
3404 *
3405 * <p>This generally means that while the TCP connections are still live temporarily
3406 * network data fails to transfer. To give a specific example, this is used on cellular
3407 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3408 * means read operations on sockets on this network will block once the buffers are
3409 * drained, and write operations will block once the buffers are full.
3410 *
3411 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3412 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3413 * this callback as this is prone to race conditions (there is no guarantee the objects
3414 * returned by these methods will be current).
3415 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003416 * @hide
3417 */
paulhu1a407652019-03-22 16:35:06 +08003418 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003419
3420 /**
3421 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003422 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3423 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003424
3425 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3426 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3427 * this callback as this is prone to race conditions : calling these methods while in a
3428 * callback may return an outdated or even a null object.
3429 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003430 * @hide
3431 */
paulhu1a407652019-03-22 16:35:06 +08003432 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003433
junyulaif2c67e42018-08-07 19:50:45 +08003434 /**
3435 * Called when access to the specified network is blocked or unblocked.
3436 *
Chalard Jean01378b62019-08-30 16:27:28 +09003437 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3438 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3439 * this callback as this is prone to race conditions : calling these methods while in a
3440 * callback may return an outdated or even a null object.
3441 *
junyulaif2c67e42018-08-07 19:50:45 +08003442 * @param network The {@link Network} whose blocked status has changed.
3443 * @param blocked The blocked status of this {@link Network}.
3444 */
junyulai7e06ad42019-03-04 22:45:36 +08003445 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003446
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003447 private NetworkRequest networkRequest;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003448 }
3449
Hugo Benichia590ab82017-05-11 13:16:17 +09003450 /**
3451 * Constant error codes used by ConnectivityService to communicate about failures and errors
3452 * across a Binder boundary.
3453 * @hide
3454 */
3455 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003456 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003457 }
3458
3459 /** @hide */
3460 public static class TooManyRequestsException extends RuntimeException {}
3461
3462 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3463 switch (e.errorCode) {
3464 case Errors.TOO_MANY_REQUESTS:
3465 return new TooManyRequestsException();
3466 default:
3467 Log.w(TAG, "Unknown service error code " + e.errorCode);
3468 return new RuntimeException(e);
3469 }
3470 }
3471
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003472 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003473 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003474 public static final int CALLBACK_PRECHECK = BASE + 1;
3475 /** @hide */
3476 public static final int CALLBACK_AVAILABLE = BASE + 2;
3477 /** @hide arg1 = TTL */
3478 public static final int CALLBACK_LOSING = BASE + 3;
3479 /** @hide */
3480 public static final int CALLBACK_LOST = BASE + 4;
3481 /** @hide */
3482 public static final int CALLBACK_UNAVAIL = BASE + 5;
3483 /** @hide */
3484 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3485 /** @hide */
3486 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003487 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003488 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003489 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003490 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003491 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003492 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003493 /** @hide */
3494 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003495
Erik Kline155a59a2015-11-25 12:49:38 +09003496 /** @hide */
3497 public static String getCallbackName(int whichCallback) {
3498 switch (whichCallback) {
3499 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3500 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3501 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3502 case CALLBACK_LOST: return "CALLBACK_LOST";
3503 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3504 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3505 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003506 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3507 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3508 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003509 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003510 default:
3511 return Integer.toString(whichCallback);
3512 }
3513 }
3514
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003515 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003516 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003517 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003518
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003519 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003520 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003521 }
3522
Hugo Benichifd44e912017-02-02 17:02:36 +09003523 CallbackHandler(Handler handler) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003524 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003525 }
3526
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003527 @Override
3528 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003529 if (message.what == EXPIRE_LEGACY_REQUEST) {
3530 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3531 return;
3532 }
3533
3534 final NetworkRequest request = getObject(message, NetworkRequest.class);
3535 final Network network = getObject(message, Network.class);
3536 final NetworkCallback callback;
3537 synchronized (sCallbacks) {
3538 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003539 if (callback == null) {
3540 Log.w(TAG,
3541 "callback not found for " + getCallbackName(message.what) + " message");
3542 return;
3543 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003544 if (message.what == CALLBACK_UNAVAIL) {
3545 sCallbacks.remove(request);
3546 callback.networkRequest = ALREADY_UNREGISTERED;
3547 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003548 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003549 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003550 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003551 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003552
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003553 switch (message.what) {
3554 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003555 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003556 break;
3557 }
3558 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003559 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3560 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003561 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003562 break;
3563 }
3564 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003565 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003566 break;
3567 }
3568 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003569 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003570 break;
3571 }
3572 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003573 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003574 break;
3575 }
3576 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003577 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3578 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003579 break;
3580 }
3581 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003582 LinkProperties lp = getObject(message, LinkProperties.class);
3583 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003584 break;
3585 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003586 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003587 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003588 break;
3589 }
3590 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003591 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003592 break;
3593 }
junyulaif2c67e42018-08-07 19:50:45 +08003594 case CALLBACK_BLK_CHANGED: {
3595 boolean blocked = message.arg1 != 0;
3596 callback.onBlockedStatusChanged(network, blocked);
3597 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003598 }
3599 }
3600
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003601 private <T> T getObject(Message msg, Class<T> c) {
3602 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003603 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003604 }
3605
Hugo Benichifd44e912017-02-02 17:02:36 +09003606 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003607 synchronized (sCallbacks) {
3608 if (sCallbackHandler == null) {
3609 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003610 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003611 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003612 }
3613 }
3614
Hugo Benichibc4ac972017-02-03 14:18:44 +09003615 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3616 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003617
Hugo Benichibc4ac972017-02-03 14:18:44 +09003618 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003619 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003620 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003621 checkCallbackNotNull(callback);
junyulaiad010792021-01-11 16:53:38 +08003622 Preconditions.checkArgument(
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09003623 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3624 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003625 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003626 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003627 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003628 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003629 if (callback.networkRequest != null
3630 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003631 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3632 // and requests (http://b/20701525).
3633 Log.e(TAG, "NetworkCallback was already registered");
3634 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003635 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003636 Binder binder = new Binder();
junyulaiad010792021-01-11 16:53:38 +08003637 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003638 request = mService.listenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003639 need, messenger, binder, callingPackageName,
3640 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003641 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003642 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003643 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3644 callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003645 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003646 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003647 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003648 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003649 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003650 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003651 } catch (RemoteException e) {
3652 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003653 } catch (ServiceSpecificException e) {
3654 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003655 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003656 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003657 }
3658
3659 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003660 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003661 *
markchienfac84a22020-03-18 21:16:15 +08003662 * This API is only for use in internal system code that requests networks with legacy type and
3663 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003664 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003665 *
markchiend6eeffd2020-01-14 00:55:21 +08003666 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003667 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3668 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3669 * be a positive value (i.e. >0).
3670 * @param legacyType to specify the network type(#TYPE_*).
3671 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003672 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3673 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003674 *
3675 * @hide
3676 */
markchiend6eeffd2020-01-14 00:55:21 +08003677 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003678 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003679 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003680 int timeoutMs, int legacyType, @NonNull Handler handler,
3681 @NonNull NetworkCallback networkCallback) {
3682 if (legacyType == TYPE_NONE) {
3683 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3684 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003685 CallbackHandler cbHandler = new CallbackHandler(handler);
3686 NetworkCapabilities nc = request.networkCapabilities;
3687 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003688 }
3689
3690 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003691 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003692 *
Chalard Jean01378b62019-08-30 16:27:28 +09003693 * <p>This method will attempt to find the best network that matches the passed
3694 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3695 * criteria. The platform will evaluate which network is the best at its own discretion.
3696 * Throughput, latency, cost per byte, policy, user preference and other considerations
3697 * may be factored in the decision of what is considered the best network.
3698 *
3699 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3700 * matching this request, while always attempting to match the request to a better network if
3701 * possible. If a better match is found, the platform will switch this request to the now-best
3702 * network and inform the app of the newly best network by invoking
3703 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3704 * will not try to maintain any other network than the best one currently matching the request:
3705 * a network not matching any network request may be disconnected at any time.
3706 *
3707 * <p>For example, an application could use this method to obtain a connected cellular network
3708 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3709 * radio to consume additional power. Or, an application could inform the system that it wants
3710 * a network supporting sending MMSes and have the system let it know about the currently best
3711 * MMS-supporting network through the provided {@link NetworkCallback}.
3712 *
3713 * <p>The status of the request can be followed by listening to the various callbacks described
3714 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3715 * used to direct traffic to the network (although accessing some networks may be subject to
3716 * holding specific permissions). Callers will learn about the specific characteristics of the
3717 * network through
3718 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3719 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3720 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3721 * matching the request at any given time; therefore when a better network matching the request
3722 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3723 * with the new network after which no further updates are given about the previously-best
3724 * network, unless it becomes the best again at some later time. All callbacks are invoked
3725 * in order on the same thread, which by default is a thread created by the framework running
3726 * in the app.
3727 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3728 * callbacks are invoked.
3729 *
3730 * <p>This{@link NetworkRequest} will live until released via
3731 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3732 * which point the system may let go of the network at any time.
3733 *
3734 * <p>A version of this method which takes a timeout is
3735 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3736 * wait for a limited amount of time for the network to become unavailable.
3737 *
Paul Jensenee52d232015-06-16 15:11:58 -04003738 * <p>It is presently unsupported to request a network with mutable
3739 * {@link NetworkCapabilities} such as
3740 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3741 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3742 * as these {@code NetworkCapabilities} represent states that a particular
3743 * network may never attain, and whether a network will attain these states
3744 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003745 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003746 *
3747 * <p>This method requires the caller to hold either the
3748 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3749 * or the ability to modify system settings as determined by
3750 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003751 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003752 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3753 * number of outstanding requests to 100 per app (identified by their UID), shared with
3754 * all variants of this method, of {@link #registerNetworkCallback} as well as
3755 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3756 * Requesting a network with this method will count toward this limit. If this limit is
3757 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3758 * make sure to unregister the callbacks with
3759 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3760 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003761 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003762 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3763 * the callback must not be shared - it uniquely specifies this request.
3764 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003765 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3766 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003767 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003768 */
Chalard Jean158702d2019-01-07 19:26:34 +09003769 public void requestNetwork(@NonNull NetworkRequest request,
3770 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003771 requestNetwork(request, networkCallback, getDefaultHandler());
3772 }
3773
3774 /**
3775 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3776 *
Chalard Jean01378b62019-08-30 16:27:28 +09003777 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3778 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003779 *
Chalard Jean01378b62019-08-30 16:27:28 +09003780 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003781 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3782 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003783 *
3784 * @param request {@link NetworkRequest} describing this request.
3785 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3786 * the callback must not be shared - it uniquely specifies this request.
3787 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003788 */
Chalard Jean158702d2019-01-07 19:26:34 +09003789 public void requestNetwork(@NonNull NetworkRequest request,
3790 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003791 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003792 NetworkCapabilities nc = request.networkCapabilities;
3793 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003794 }
3795
3796 /**
Etan Cohenf67bde92017-03-01 12:47:28 -08003797 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3798 * by a timeout.
3799 *
3800 * This function behaves identically to the non-timed-out version
3801 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3802 * is not found within the given time (in milliseconds) the
3803 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3804 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3805 * not have to be released if timed-out (it is automatically released). Unregistering a
3806 * request that timed out is not an error.
3807 *
3808 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3809 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3810 * for that purpose. Calling this method will attempt to bring up the requested network.
3811 *
Chalard Jean01378b62019-08-30 16:27:28 +09003812 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003813 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3814 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003815 *
3816 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003817 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3818 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003819 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3820 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3821 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003822 */
Chalard Jean158702d2019-01-07 19:26:34 +09003823 public void requestNetwork(@NonNull NetworkRequest request,
3824 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003825 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003826 NetworkCapabilities nc = request.networkCapabilities;
3827 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3828 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003829 }
3830
Hugo Benichifd44e912017-02-02 17:02:36 +09003831 /**
3832 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3833 * by a timeout.
3834 *
Chalard Jean01378b62019-08-30 16:27:28 +09003835 * This method behaves identically to
3836 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3837 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003838 *
Chalard Jean01378b62019-08-30 16:27:28 +09003839 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003840 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3841 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003842 *
3843 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003844 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3845 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003846 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003847 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3848 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003849 */
Chalard Jean158702d2019-01-07 19:26:34 +09003850 public void requestNetwork(@NonNull NetworkRequest request,
3851 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003852 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003853 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003854 NetworkCapabilities nc = request.networkCapabilities;
3855 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003856 }
3857
3858 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003859 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003860 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003861 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003862 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003863 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3864 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003865 */
Erik Kline8a826212014-11-19 12:12:24 +09003866 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003867
3868 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003869 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003870 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003871 * {@link android.content.Intent#getParcelableExtra(String)}.
3872 */
Erik Kline8a826212014-11-19 12:12:24 +09003873 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003874
3875
3876 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003877 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003878 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003879 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003880 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003881 * the request may outlive the calling application and get called back when a suitable
3882 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003883 * <p>
3884 * The operation is an Intent broadcast that goes to a broadcast receiver that
3885 * you registered with {@link Context#registerReceiver} or through the
3886 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3887 * <p>
3888 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003889 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3890 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003891 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003892 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003893 * Intent to reserve the network or it will be released shortly after the Intent
3894 * is processed.
3895 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003896 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003897 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003898 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003899 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003900 * The request may be released normally by calling
3901 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003902 * <p>It is presently unsupported to request a network with either
3903 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3904 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3905 * as these {@code NetworkCapabilities} represent states that a particular
3906 * network may never attain, and whether a network will attain these states
3907 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003908 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003909 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003910 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3911 * number of outstanding requests to 100 per app (identified by their UID), shared with
3912 * all variants of this method, of {@link #registerNetworkCallback} as well as
3913 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3914 * Requesting a network with this method will count toward this limit. If this limit is
3915 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3916 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3917 * or {@link #releaseNetworkRequest(PendingIntent)}.
3918 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003919 * <p>This method requires the caller to hold either the
3920 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3921 * or the ability to modify system settings as determined by
3922 * {@link android.provider.Settings.System#canWrite}.</p>
3923 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003924 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003925 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003926 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003927 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09003928 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3929 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003930 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003931 */
Chalard Jean158702d2019-01-07 19:26:34 +09003932 public void requestNetwork(@NonNull NetworkRequest request,
3933 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003934 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003935 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003936 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003937 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003938 request.networkCapabilities, operation, mContext.getOpPackageName(),
3939 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003940 } catch (RemoteException e) {
3941 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003942 } catch (ServiceSpecificException e) {
3943 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003944 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003945 }
3946
3947 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003948 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3949 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09003950 * This method has the same behavior as
3951 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003952 * releasing network resources and disconnecting.
3953 *
3954 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3955 * PendingIntent passed to
3956 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3957 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3958 */
Chalard Jean158702d2019-01-07 19:26:34 +09003959 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003960 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003961 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003962 try {
3963 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003964 } catch (RemoteException e) {
3965 throw e.rethrowFromSystemServer();
3966 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003967 }
3968
Hugo Benichibc1104b2017-05-09 15:19:01 +09003969 private static void checkPendingIntentNotNull(PendingIntent intent) {
3970 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3971 }
3972
3973 private static void checkCallbackNotNull(NetworkCallback callback) {
3974 Preconditions.checkNotNull(callback, "null NetworkCallback");
3975 }
3976
3977 private static void checkTimeout(int timeoutMs) {
3978 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003979 }
3980
3981 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003982 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003983 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08003984 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3985 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003986 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003987 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3988 * number of outstanding requests to 100 per app (identified by their UID), shared with
3989 * all variants of this method, of {@link #requestNetwork} as well as
3990 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3991 * Requesting a network with this method will count toward this limit. If this limit is
3992 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3993 * make sure to unregister the callbacks with
3994 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3995 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003996 * @param request {@link NetworkRequest} describing this request.
3997 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3998 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09003999 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004000 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004001 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004002 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004003 public void registerNetworkCallback(@NonNull NetworkRequest request,
4004 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004005 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4006 }
4007
4008 /**
4009 * Registers to receive notifications about all networks which satisfy the given
4010 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004011 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4012 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004013 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004014 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4015 * number of outstanding requests to 100 per app (identified by their UID), shared with
4016 * all variants of this method, of {@link #requestNetwork} as well as
4017 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4018 * Requesting a network with this method will count toward this limit. If this limit is
4019 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4020 * make sure to unregister the callbacks with
4021 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4022 *
4023 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004024 * @param request {@link NetworkRequest} describing this request.
4025 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4026 * networks change state.
4027 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004028 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004029 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004030 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004031 public void registerNetworkCallback(@NonNull NetworkRequest request,
4032 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004033 CallbackHandler cbHandler = new CallbackHandler(handler);
4034 NetworkCapabilities nc = request.networkCapabilities;
4035 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004036 }
4037
4038 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004039 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4040 * {@link NetworkRequest}.
4041 *
4042 * This function behaves identically to the version that takes a NetworkCallback, but instead
4043 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4044 * the request may outlive the calling application and get called back when a suitable
4045 * network is found.
4046 * <p>
4047 * The operation is an Intent broadcast that goes to a broadcast receiver that
4048 * you registered with {@link Context#registerReceiver} or through the
4049 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4050 * <p>
4051 * The operation Intent is delivered with two extras, a {@link Network} typed
4052 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4053 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4054 * the original requests parameters.
4055 * <p>
4056 * If there is already a request for this Intent registered (with the equality of
4057 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4058 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4059 * <p>
4060 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004061 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004062 *
4063 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4064 * number of outstanding requests to 100 per app (identified by their UID), shared with
4065 * all variants of this method, of {@link #requestNetwork} as well as
4066 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4067 * Requesting a network with this method will count toward this limit. If this limit is
4068 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4069 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4070 * or {@link #releaseNetworkRequest(PendingIntent)}.
4071 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004072 * @param request {@link NetworkRequest} describing this request.
4073 * @param operation Action to perform when the network is available (corresponds
4074 * to the {@link NetworkCallback#onAvailable} call. Typically
4075 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004076 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004077 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004078 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004079 public void registerNetworkCallback(@NonNull NetworkRequest request,
4080 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004081 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004082 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004083 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004084 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004085 request.networkCapabilities, operation, mContext.getOpPackageName(),
4086 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004087 } catch (RemoteException e) {
4088 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004089 } catch (ServiceSpecificException e) {
4090 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004091 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004092 }
4093
4094 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004095 * Registers to receive notifications about changes in the application's default network. This
4096 * may be a physical network or a virtual network, such as a VPN that applies to the
4097 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004098 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004099 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004100 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4101 * number of outstanding requests to 100 per app (identified by their UID), shared with
4102 * all variants of this method, of {@link #requestNetwork} as well as
4103 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4104 * Requesting a network with this method will count toward this limit. If this limit is
4105 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4106 * make sure to unregister the callbacks with
4107 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4108 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004109 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004110 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004111 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004112 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004113 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004114 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004115 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004116 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4117 }
4118
4119 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004120 * Registers to receive notifications about changes in the application's default network. This
4121 * may be a physical network or a virtual network, such as a VPN that applies to the
4122 * application. The callbacks will continue to be called until either the application exits or
4123 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4124 *
4125 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4126 * number of outstanding requests to 100 per app (identified by their UID), shared with
4127 * all variants of this method, of {@link #requestNetwork} as well as
4128 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4129 * Requesting a network with this method will count toward this limit. If this limit is
4130 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4131 * make sure to unregister the callbacks with
4132 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4133 *
4134 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4135 * application's default network changes.
4136 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4137 * @throws RuntimeException if the app already has too many callbacks registered.
4138 */
4139 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4140 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4141 @NonNull Handler handler) {
4142 CallbackHandler cbHandler = new CallbackHandler(handler);
4143 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4144 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4145 }
4146
4147 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004148 * Registers to receive notifications about changes in the system default network. The callbacks
4149 * will continue to be called until either the application exits or
4150 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004151 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004152 * This method should not be used to determine networking state seen by applications, because in
4153 * many cases, most or even all application traffic may not use the default network directly,
4154 * and traffic from different applications may go on different networks by default. As an
4155 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4156 * and not onto the system default network. Applications or system components desiring to do
4157 * determine network state as seen by applications should use other methods such as
4158 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4159 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004160 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4161 * number of outstanding requests to 100 per app (identified by their UID), shared with
4162 * all variants of this method, of {@link #requestNetwork} as well as
4163 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4164 * Requesting a network with this method will count toward this limit. If this limit is
4165 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4166 * make sure to unregister the callbacks with
4167 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4168 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004169 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4170 * system default network changes.
4171 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004172 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004173 *
4174 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004175 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004176 @SystemApi(client = MODULE_LIBRARIES)
4177 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4178 @RequiresPermission(anyOf = {
4179 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4180 android.Manifest.permission.NETWORK_SETTINGS})
4181 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004182 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004183 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004184 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004185 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004186 }
4187
4188 /**
fenglub00f4882015-04-21 17:12:05 -07004189 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4190 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4191 * network connection for updated bandwidth information. The caller will be notified via
4192 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004193 * method assumes that the caller has previously called
4194 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4195 * changes.
fenglu3f357402015-03-20 11:29:56 -07004196 *
fengluea2d9282015-04-27 14:28:04 -07004197 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004198 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004199 */
Chalard Jean158702d2019-01-07 19:26:34 +09004200 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004201 try {
fenglub00f4882015-04-21 17:12:05 -07004202 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004203 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004204 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004205 }
4206 }
4207
4208 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004209 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004210 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4211 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4212 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004213 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4214 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004215 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004216 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4217 * triggering it as soon as this call returns.
4218 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004219 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004220 */
Chalard Jean158702d2019-01-07 19:26:34 +09004221 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004222 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004223 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004224 final List<NetworkRequest> reqs = new ArrayList<>();
4225 // Find all requests associated to this callback and stop callback triggers immediately.
4226 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4227 synchronized (sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09004228 Preconditions.checkArgument(networkCallback.networkRequest != null,
4229 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004230 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4231 Log.d(TAG, "NetworkCallback was already unregistered");
4232 return;
4233 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004234 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4235 if (e.getValue() == networkCallback) {
4236 reqs.add(e.getKey());
4237 }
4238 }
4239 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4240 for (NetworkRequest r : reqs) {
4241 try {
4242 mService.releaseNetworkRequest(r);
4243 } catch (RemoteException e) {
4244 throw e.rethrowFromSystemServer();
4245 }
4246 // Only remove mapping if rpc was successful.
4247 sCallbacks.remove(r);
4248 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004249 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004250 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004251 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004252
4253 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004254 * Unregisters a callback previously registered via
4255 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4256 *
4257 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4258 * PendingIntent passed to
4259 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4260 * Cannot be null.
4261 */
Chalard Jean158702d2019-01-07 19:26:34 +09004262 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004263 releaseNetworkRequest(operation);
4264 }
4265
4266 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004267 * Informs the system whether it should switch to {@code network} regardless of whether it is
4268 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4269 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4270 * the system default network regardless of any other network that's currently connected. If
4271 * {@code always} is true, then the choice is remembered, so that the next time the user
4272 * connects to this network, the system will switch to it.
4273 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004274 * @param network The network to accept.
4275 * @param accept Whether to accept the network even if unvalidated.
4276 * @param always Whether to remember this choice in the future.
4277 *
4278 * @hide
4279 */
lucaslin2240ef62019-03-12 13:08:03 +08004280 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004281 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4282 try {
4283 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004284 } catch (RemoteException e) {
4285 throw e.rethrowFromSystemServer();
4286 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004287 }
4288
4289 /**
lucaslin2240ef62019-03-12 13:08:03 +08004290 * Informs the system whether it should consider the network as validated even if it only has
4291 * partial connectivity. If {@code accept} is true, then the network will be considered as
4292 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4293 * is remembered, so that the next time the user connects to this network, the system will
4294 * switch to it.
4295 *
4296 * @param network The network to accept.
4297 * @param accept Whether to consider the network as validated even if it has partial
4298 * connectivity.
4299 * @param always Whether to remember this choice in the future.
4300 *
4301 * @hide
4302 */
4303 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4304 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4305 try {
4306 mService.setAcceptPartialConnectivity(network, accept, always);
4307 } catch (RemoteException e) {
4308 throw e.rethrowFromSystemServer();
4309 }
4310 }
4311
4312 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004313 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4314 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4315 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4316 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4317 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004318 * @param network The network to accept.
4319 *
4320 * @hide
4321 */
lucaslin2240ef62019-03-12 13:08:03 +08004322 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004323 public void setAvoidUnvalidated(Network network) {
4324 try {
4325 mService.setAvoidUnvalidated(network);
4326 } catch (RemoteException e) {
4327 throw e.rethrowFromSystemServer();
4328 }
4329 }
4330
4331 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004332 * Requests that the system open the captive portal app on the specified network.
4333 *
4334 * @param network The network to log into.
4335 *
4336 * @hide
4337 */
paulhu8e96a752019-08-12 16:25:11 +08004338 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004339 public void startCaptivePortalApp(Network network) {
4340 try {
4341 mService.startCaptivePortalApp(network);
4342 } catch (RemoteException e) {
4343 throw e.rethrowFromSystemServer();
4344 }
4345 }
4346
4347 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004348 * Requests that the system open the captive portal app with the specified extras.
4349 *
4350 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4351 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004352 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004353 * @param appExtras Extras to include in the app start intent.
4354 * @hide
4355 */
4356 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004357 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004358 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004359 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004360 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004361 } catch (RemoteException e) {
4362 throw e.rethrowFromSystemServer();
4363 }
4364 }
4365
4366 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004367 * Determine whether the device is configured to avoid bad wifi.
4368 * @hide
4369 */
4370 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004371 @RequiresPermission(anyOf = {
4372 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4373 android.Manifest.permission.NETWORK_STACK})
4374 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004375 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004376 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004377 } catch (RemoteException e) {
4378 throw e.rethrowFromSystemServer();
4379 }
4380 }
4381
4382 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004383 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4384 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004385 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4386 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004387 *
4388 * An example of such an operation might be a time-sensitive foreground activity, such as a
4389 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4390 */
4391 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4392
4393 /**
4394 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4395 * a backup channel for traffic that is primarily going over another network.
4396 *
4397 * An example might be maintaining backup connections to peers or servers for the purpose of
4398 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4399 * on backup paths should be negligible compared to the traffic on the main path.
4400 */
4401 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4402
4403 /**
4404 * It is acceptable to use metered data to improve network latency and performance.
4405 */
4406 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4407
4408 /**
4409 * Return value to use for unmetered networks. On such networks we currently set all the flags
4410 * to true.
4411 * @hide
4412 */
4413 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4414 MULTIPATH_PREFERENCE_HANDOVER |
4415 MULTIPATH_PREFERENCE_RELIABILITY |
4416 MULTIPATH_PREFERENCE_PERFORMANCE;
4417
4418 /** @hide */
4419 @Retention(RetentionPolicy.SOURCE)
4420 @IntDef(flag = true, value = {
4421 MULTIPATH_PREFERENCE_HANDOVER,
4422 MULTIPATH_PREFERENCE_RELIABILITY,
4423 MULTIPATH_PREFERENCE_PERFORMANCE,
4424 })
4425 public @interface MultipathPreference {
4426 }
4427
4428 /**
4429 * Provides a hint to the calling application on whether it is desirable to use the
4430 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4431 * for multipath data transfer on this network when it is not the system default network.
4432 * Applications desiring to use multipath network protocols should call this method before
4433 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004434 *
4435 * @param network The network on which the application desires to use multipath data.
4436 * If {@code null}, this method will return the a preference that will generally
4437 * apply to metered networks.
4438 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4439 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004440 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004441 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004442 try {
4443 return mService.getMultipathPreference(network);
4444 } catch (RemoteException e) {
4445 throw e.rethrowFromSystemServer();
4446 }
4447 }
4448
4449 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004450 * Resets all connectivity manager settings back to factory defaults.
4451 * @hide
4452 */
paulhu8e96a752019-08-12 16:25:11 +08004453 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004454 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004455 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004456 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004457 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004458 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004459 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004460 }
4461 }
4462
4463 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004464 * Binds the current process to {@code network}. All Sockets created in the future
4465 * (and not explicitly bound via a bound SocketFactory from
4466 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4467 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4468 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4469 * work and all host name resolutions will fail. This is by design so an application doesn't
4470 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4471 * To clear binding pass {@code null} for {@code network}. Using individually bound
4472 * Sockets created by Network.getSocketFactory().createSocket() and
4473 * performing network-specific host name resolutions via
4474 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004475 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004476 *
4477 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4478 * the current binding.
4479 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4480 */
Chalard Jean158702d2019-01-07 19:26:34 +09004481 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004482 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004483 // instantiated.
4484 return setProcessDefaultNetwork(network);
4485 }
4486
4487 /**
4488 * Binds the current process to {@code network}. All Sockets created in the future
4489 * (and not explicitly bound via a bound SocketFactory from
4490 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4491 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4492 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4493 * work and all host name resolutions will fail. This is by design so an application doesn't
4494 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4495 * To clear binding pass {@code null} for {@code network}. Using individually bound
4496 * Sockets created by Network.getSocketFactory().createSocket() and
4497 * performing network-specific host name resolutions via
4498 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4499 * {@code setProcessDefaultNetwork}.
4500 *
4501 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4502 * the current binding.
4503 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4504 * @deprecated This function can throw {@link IllegalStateException}. Use
4505 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4506 * is a direct replacement.
4507 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004508 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004509 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004510 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004511 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4512
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004513 if (netId != NETID_UNSET) {
4514 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004515 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004516
4517 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4518 return false;
4519 }
4520
4521 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004522 // Set HTTP proxy system properties to match network.
4523 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004524 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004525 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004526 } catch (SecurityException e) {
4527 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4528 Log.e(TAG, "Can't set proxy properties", e);
4529 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004530 // Must flush DNS cache as new network may have different DNS resolutions.
4531 InetAddress.clearDnsCache();
4532 // Must flush socket pool as idle sockets will be bound to previous network and may
4533 // cause subsequent fetches to be performed on old network.
4534 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004535 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004536
4537 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004538 }
4539
4540 /**
4541 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004542 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004543 *
4544 * @return {@code Network} to which this process is bound, or {@code null}.
4545 */
Chalard Jean158702d2019-01-07 19:26:34 +09004546 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004547 public Network getBoundNetworkForProcess() {
4548 // Forcing callers to call thru non-static function ensures ConnectivityManager
4549 // instantiated.
4550 return getProcessDefaultNetwork();
4551 }
4552
4553 /**
4554 * Returns the {@link Network} currently bound to this process via
4555 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4556 *
4557 * @return {@code Network} to which this process is bound, or {@code null}.
4558 * @deprecated Using this function can lead to other functions throwing
4559 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4560 * {@code getBoundNetworkForProcess} is a direct replacement.
4561 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004562 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004563 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004564 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004565 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004566 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004567 return new Network(netId);
4568 }
4569
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004570 private void unsupportedStartingFrom(int version) {
4571 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004572 // The getApplicationInfo() call we make below is not supported in system context. Let
4573 // the call through here, and rely on the fact that ConnectivityService will refuse to
4574 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004575 return;
4576 }
4577
4578 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4579 throw new UnsupportedOperationException(
4580 "This method is not supported in target SDK version " + version + " and above");
4581 }
4582 }
4583
4584 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4585 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004586 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004587 // remove these exemptions. Note that this check is not secure, and apps can still access these
4588 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4589 // so is unsupported and may break in the future. http://b/22728205
4590 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004591 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004592 }
4593
Paul Jensen8cdda642014-05-29 10:12:39 -04004594 /**
4595 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004596 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004597 *
4598 * @param network The {@link Network} to bind host resolutions from the current process to, or
4599 * {@code null} to clear the current binding.
4600 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4601 * @hide
4602 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4603 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004604 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004605 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004606 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004607 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004608 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004609 }
Felipe Leme30511352016-01-22 09:44:57 -08004610
4611 /**
4612 * Device is not restricting metered network activity while application is running on
4613 * background.
4614 */
4615 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4616
4617 /**
4618 * Device is restricting metered network activity while application is running on background,
4619 * but application is allowed to bypass it.
4620 * <p>
4621 * In this state, application should take action to mitigate metered network access.
4622 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4623 */
4624 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4625
4626 /**
4627 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004628 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004629 * In this state, application should not try to use the network while running on background,
4630 * because it would be denied.
4631 */
4632 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4633
Felipe Lemed34c9af2016-01-27 14:46:39 -08004634 /**
4635 * A change in the background metered network activity restriction has occurred.
4636 * <p>
4637 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4638 * applies to them.
4639 * <p>
4640 * This is only sent to registered receivers, not manifest receivers.
4641 */
4642 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4643 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4644 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4645
Felipe Leme7e4c1852016-01-25 11:48:04 -08004646 /** @hide */
4647 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004648 @IntDef(flag = false, value = {
4649 RESTRICT_BACKGROUND_STATUS_DISABLED,
4650 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4651 RESTRICT_BACKGROUND_STATUS_ENABLED,
4652 })
Felipe Leme30511352016-01-22 09:44:57 -08004653 public @interface RestrictBackgroundStatus {
4654 }
4655
4656 private INetworkPolicyManager getNetworkPolicyManager() {
4657 synchronized (this) {
4658 if (mNPManager != null) {
4659 return mNPManager;
4660 }
4661 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4662 .getService(Context.NETWORK_POLICY_SERVICE));
4663 return mNPManager;
4664 }
4665 }
4666
4667 /**
4668 * Determines if the calling application is subject to metered network restrictions while
4669 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004670 *
4671 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4672 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4673 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004674 */
4675 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4676 try {
4677 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4678 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004679 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004680 }
4681 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004682
4683 /**
4684 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004685 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4686 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004687 *
4688 * @return Hash of network watchlist config file. Null if config does not exist.
4689 */
Chalard Jean158702d2019-01-07 19:26:34 +09004690 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004691 public byte[] getNetworkWatchlistConfigHash() {
4692 try {
4693 return mService.getNetworkWatchlistConfigHash();
4694 } catch (RemoteException e) {
4695 Log.e(TAG, "Unable to get watchlist config hash");
4696 throw e.rethrowFromSystemServer();
4697 }
4698 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004699
4700 /**
4701 * Returns the {@code uid} of the owner of a network connection.
4702 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004703 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4704 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004705 * @param local The local {@link InetSocketAddress} of a connection.
4706 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004707 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004708 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4709 * android.os.Process#INVALID_UID} if the connection is not found.
4710 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4711 * user.
4712 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004713 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004714 public int getConnectionOwnerUid(
4715 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004716 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4717 try {
4718 return mService.getConnectionOwnerUid(connectionInfo);
4719 } catch (RemoteException e) {
4720 throw e.rethrowFromSystemServer();
4721 }
4722 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004723
4724 private void printStackTrace() {
4725 if (DEBUG) {
4726 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4727 final StringBuffer sb = new StringBuffer();
4728 for (int i = 3; i < callStack.length; i++) {
4729 final String stackTrace = callStack[i].toString();
4730 if (stackTrace == null || stackTrace.contains("android.os")) {
4731 break;
4732 }
4733 sb.append(" [").append(stackTrace).append("]");
4734 }
4735 Log.d(TAG, "StackLog:" + sb.toString());
4736 }
4737 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004738
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004739 /** @hide */
4740 public TestNetworkManager startOrGetTestNetworkManager() {
4741 final IBinder tnBinder;
4742 try {
4743 tnBinder = mService.startOrGetTestNetworkService();
4744 } catch (RemoteException e) {
4745 throw e.rethrowFromSystemServer();
4746 }
4747
4748 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4749 }
4750
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004751 /** @hide */
4752 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4753 return new ConnectivityDiagnosticsManager(mContext, mService);
4754 }
4755
Cody Kestingf53a0752020-04-15 12:33:28 -07004756 /**
4757 * Simulates a Data Stall for the specified Network.
4758 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004759 * <p>This method should only be used for tests.
4760 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004761 * <p>The caller must be the owner of the specified Network.
4762 *
4763 * @param detectionMethod The detection method used to identify the Data Stall.
4764 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4765 * @param network The Network for which a Data Stall is being simluated.
4766 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4767 * @throws SecurityException if the caller is not the owner of the given network.
4768 * @hide
4769 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004770 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004771 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4772 android.Manifest.permission.NETWORK_STACK})
4773 public void simulateDataStall(int detectionMethod, long timestampMillis,
4774 @NonNull Network network, @NonNull PersistableBundle extras) {
4775 try {
4776 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4777 } catch (RemoteException e) {
4778 e.rethrowFromSystemServer();
4779 }
4780 }
James Mattis356a8792020-10-28 21:48:54 -07004781
Daniel Brightf9e945b2020-06-15 16:10:01 -07004782 @NonNull
4783 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4784
4785 /**
4786 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4787 * receive available QoS events related to the {@link Network} and local ip + port
4788 * specified within socketInfo.
4789 * <p/>
4790 * The same {@link QosCallback} must be unregistered before being registered a second time,
4791 * otherwise {@link QosCallbackRegistrationException} is thrown.
4792 * <p/>
4793 * This API does not, in itself, require any permission if called with a network that is not
4794 * restricted. However, the underlying implementation currently only supports the IMS network,
4795 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4796 * useful, because they'd never be called back on networks that they would have access to.
4797 *
4798 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4799 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4800 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4801 * @throws RuntimeException if the app already has too many callbacks registered.
4802 *
4803 * Exceptions after the time of registration is passed through
4804 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4805 *
4806 * @param socketInfo the socket information used to match QoS events
Daniel Brightf9e945b2020-06-15 16:10:01 -07004807 * @param executor The executor on which the callback will be invoked. The provided
4808 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright7ee5f522021-03-10 11:51:50 -08004809 * callbacks cannot be guaranteed.onQosCallbackRegistered
4810 * @param callback receives qos events that satisfy socketInfo
Daniel Brightf9e945b2020-06-15 16:10:01 -07004811 *
4812 * @hide
4813 */
4814 @SystemApi
4815 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright7ee5f522021-03-10 11:51:50 -08004816 @CallbackExecutor @NonNull final Executor executor,
4817 @NonNull final QosCallback callback) {
Daniel Brightf9e945b2020-06-15 16:10:01 -07004818 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07004819 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright7ee5f522021-03-10 11:51:50 -08004820 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07004821
4822 try {
4823 synchronized (mQosCallbackConnections) {
4824 if (getQosCallbackConnection(callback) == null) {
4825 final QosCallbackConnection connection =
4826 new QosCallbackConnection(this, callback, executor);
4827 mQosCallbackConnections.add(connection);
4828 mService.registerQosSocketCallback(socketInfo, connection);
4829 } else {
4830 Log.e(TAG, "registerQosCallback: Callback already registered");
4831 throw new QosCallbackRegistrationException();
4832 }
4833 }
4834 } catch (final RemoteException e) {
4835 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4836
4837 // The same unregister method method is called for consistency even though nothing
4838 // will be sent to the ConnectivityService since the callback was never successfully
4839 // registered.
4840 unregisterQosCallback(callback);
4841 e.rethrowFromSystemServer();
4842 } catch (final ServiceSpecificException e) {
4843 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4844 unregisterQosCallback(callback);
4845 throw convertServiceException(e);
4846 }
4847 }
4848
4849 /**
4850 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4851 * events once unregistered and can be registered a second time.
4852 * <p/>
4853 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4854 *
4855 * @param callback the callback being unregistered
4856 *
4857 * @hide
4858 */
4859 @SystemApi
4860 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4861 Objects.requireNonNull(callback, "The callback must be non-null");
4862 try {
4863 synchronized (mQosCallbackConnections) {
4864 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4865 if (connection != null) {
4866 connection.stopReceivingMessages();
4867 mService.unregisterQosCallback(connection);
4868 mQosCallbackConnections.remove(connection);
4869 } else {
4870 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4871 }
4872 }
4873 } catch (final RemoteException e) {
4874 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4875 e.rethrowFromSystemServer();
4876 }
4877 }
4878
4879 /**
4880 * Gets the connection related to the callback.
4881 *
4882 * @param callback the callback to look up
4883 * @return the related connection
4884 */
4885 @Nullable
4886 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4887 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4888 // Checking by reference here is intentional
4889 if (connection.getCallback() == callback) {
4890 return connection;
4891 }
4892 }
4893 return null;
4894 }
Junyu Laia62493f2021-01-19 11:10:56 +00004895
4896 /**
4897 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4898 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4899 * be used to request that the system provide a network without causing the network to be
4900 * in the foreground.
4901 *
4902 * <p>This method will attempt to find the best network that matches the passed
4903 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4904 * criteria. The platform will evaluate which network is the best at its own discretion.
4905 * Throughput, latency, cost per byte, policy, user preference and other considerations
4906 * may be factored in the decision of what is considered the best network.
4907 *
4908 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4909 * matching this request, while always attempting to match the request to a better network if
4910 * possible. If a better match is found, the platform will switch this request to the now-best
4911 * network and inform the app of the newly best network by invoking
4912 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4913 * will not try to maintain any other network than the best one currently matching the request:
4914 * a network not matching any network request may be disconnected at any time.
4915 *
4916 * <p>For example, an application could use this method to obtain a connected cellular network
4917 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4918 * radio to consume additional power. Or, an application could inform the system that it wants
4919 * a network supporting sending MMSes and have the system let it know about the currently best
4920 * MMS-supporting network through the provided {@link NetworkCallback}.
4921 *
4922 * <p>The status of the request can be followed by listening to the various callbacks described
4923 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4924 * used to direct traffic to the network (although accessing some networks may be subject to
4925 * holding specific permissions). Callers will learn about the specific characteristics of the
4926 * network through
4927 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4928 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4929 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4930 * matching the request at any given time; therefore when a better network matching the request
4931 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4932 * with the new network after which no further updates are given about the previously-best
4933 * network, unless it becomes the best again at some later time. All callbacks are invoked
4934 * in order on the same thread, which by default is a thread created by the framework running
4935 * in the app.
4936 *
4937 * <p>This{@link NetworkRequest} will live until released via
4938 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4939 * which point the system may let go of the network at any time.
4940 *
4941 * <p>It is presently unsupported to request a network with mutable
4942 * {@link NetworkCapabilities} such as
4943 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4944 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4945 * as these {@code NetworkCapabilities} represent states that a particular
4946 * network may never attain, and whether a network will attain these states
4947 * is unknown prior to bringing up the network so the framework does not
4948 * know how to go about satisfying a request with these capabilities.
4949 *
4950 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4951 * number of outstanding requests to 100 per app (identified by their UID), shared with
4952 * all variants of this method, of {@link #registerNetworkCallback} as well as
4953 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4954 * Requesting a network with this method will count toward this limit. If this limit is
4955 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4956 * make sure to unregister the callbacks with
4957 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4958 *
4959 * @param request {@link NetworkRequest} describing this request.
4960 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4961 * If null, the callback is invoked on the default internal Handler.
4962 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4963 * the callback must not be shared - it uniquely specifies this request.
4964 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4965 * @throws SecurityException if missing the appropriate permissions.
4966 * @throws RuntimeException if the app already has too many callbacks registered.
4967 *
4968 * @hide
4969 */
4970 @SystemApi(client = MODULE_LIBRARIES)
4971 @SuppressLint("ExecutorRegistration")
4972 @RequiresPermission(anyOf = {
4973 android.Manifest.permission.NETWORK_SETTINGS,
4974 android.Manifest.permission.NETWORK_STACK,
4975 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4976 })
4977 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
4978 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
4979 final NetworkCapabilities nc = request.networkCapabilities;
4980 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
4981 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
4982 }
James Mattis45d81842021-01-10 14:24:24 -08004983
4984 /**
4985 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
4986 * OnSetOemNetworkPreferenceListener)}.
James Mattisda32cfe2021-01-26 16:23:52 -08004987 * @hide
James Mattis45d81842021-01-10 14:24:24 -08004988 */
James Mattisda32cfe2021-01-26 16:23:52 -08004989 @SystemApi
4990 public interface OnSetOemNetworkPreferenceListener {
James Mattis45d81842021-01-10 14:24:24 -08004991 /**
4992 * Called when setOemNetworkPreference() successfully completes.
4993 */
4994 void onComplete();
4995 }
4996
4997 /**
4998 * Used by automotive devices to set the network preferences used to direct traffic at an
4999 * application level as per the given OemNetworkPreferences. An example use-case would be an
5000 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5001 * vehicle via a particular network.
5002 *
5003 * Calling this will overwrite the existing preference.
5004 *
5005 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5006 * @param executor the executor on which listener will be invoked.
5007 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5008 * communicate completion of setOemNetworkPreference(). This will only be
5009 * called once upon successful completion of setOemNetworkPreference().
5010 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5011 * @throws SecurityException if missing the appropriate permissions.
5012 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005013 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005014 */
James Mattisda32cfe2021-01-26 16:23:52 -08005015 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005016 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005017 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005018 @Nullable @CallbackExecutor final Executor executor,
5019 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5020 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5021 if (null != listener) {
5022 Objects.requireNonNull(executor, "Executor must be non-null");
5023 }
5024 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5025 new IOnSetOemNetworkPreferenceListener.Stub() {
5026 @Override
5027 public void onComplete() {
5028 executor.execute(listener::onComplete);
5029 }
5030 };
5031
5032 try {
5033 mService.setOemNetworkPreference(preference, listenerInternal);
5034 } catch (RemoteException e) {
5035 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5036 throw e.rethrowFromSystemServer();
5037 }
5038 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005039}