blob: 1f2975c8a3f261920a19a6b602243051da970989 [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 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001262 * Returns the {@link Network} object currently serving a given type, or
1263 * null if the given type is not connected.
1264 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001265 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001266 * @deprecated This method does not support multiple connected networks
1267 * of the same type. Use {@link #getAllNetworks} and
1268 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001269 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001270 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001271 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001272 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001273 public Network getNetworkForType(int networkType) {
1274 try {
1275 return mService.getNetworkForType(networkType);
1276 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001277 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001278 }
1279 }
1280
1281 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001282 * Returns an array of all {@link Network} currently tracked by the
1283 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001284 *
1285 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001286 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001287 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001288 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001289 public Network[] getAllNetworks() {
1290 try {
1291 return mService.getAllNetworks();
1292 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001293 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001294 }
1295 }
1296
1297 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001298 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001299 * the Networks that applications run by the given user will use by default.
1300 * @hide
1301 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001302 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001303 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1304 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001305 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001306 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001307 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001308 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001309 }
1310 }
1311
1312 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001313 * Returns the IP information for the current default network.
1314 *
1315 * @return a {@link LinkProperties} object describing the IP info
1316 * for the current default network, or {@code null} if there
1317 * is no current default network.
1318 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001319 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001320 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1321 * value of {@link #getActiveNetwork()} instead. In particular,
1322 * this method will return non-null LinkProperties even if the
1323 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001324 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001325 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001326 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001327 public LinkProperties getActiveLinkProperties() {
1328 try {
1329 return mService.getActiveLinkProperties();
1330 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001331 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001332 }
1333 }
1334
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001335 /**
1336 * Returns the IP information for a given network type.
1337 *
1338 * @param networkType the network type of interest.
1339 * @return a {@link LinkProperties} object describing the IP info
1340 * for the given networkType, or {@code null} if there is
1341 * no current default network.
1342 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001343 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001344 * @deprecated This method does not support multiple connected networks
1345 * of the same type. Use {@link #getAllNetworks},
1346 * {@link #getNetworkInfo(android.net.Network)}, and
1347 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001348 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001349 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001350 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001351 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001352 public LinkProperties getLinkProperties(int networkType) {
1353 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001354 return mService.getLinkPropertiesForType(networkType);
1355 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001356 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001357 }
1358 }
1359
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001360 /**
1361 * Get the {@link LinkProperties} for the given {@link Network}. This
1362 * will return {@code null} if the network is unknown.
1363 *
1364 * @param network The {@link Network} object identifying the network in question.
1365 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001366 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001367 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001368 @Nullable
1369 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001370 try {
1371 return mService.getLinkProperties(network);
1372 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001373 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001374 }
1375 }
1376
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001377 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001378 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001379 * will return {@code null} if the network is unknown.
1380 *
1381 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001382 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001383 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001384 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001385 @Nullable
1386 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001387 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001388 return mService.getNetworkCapabilities(
1389 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001390 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001391 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001392 }
1393 }
1394
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001395 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001396 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001397 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1398 * portal is present.
1399 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1400 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1401 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001402 * The system network validation may be using different strategies to detect captive portals,
1403 * so this method does not necessarily return a URL used by the system. It only returns a URL
1404 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001405 *
Udam Sainicd645462016-01-04 12:16:14 -08001406 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001407 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1408 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001409 */
paulhu8e96a752019-08-12 16:25:11 +08001410 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001411 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001412 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001413 public String getCaptivePortalServerUrl() {
1414 try {
1415 return mService.getCaptivePortalServerUrl();
1416 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001417 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001418 }
1419 }
1420
1421 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001422 * Tells the underlying networking system that the caller wants to
1423 * begin using the named feature. The interpretation of {@code feature}
1424 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001425 *
1426 * <p>This method requires the caller to hold either the
1427 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1428 * or the ability to modify system settings as determined by
1429 * {@link android.provider.Settings.System#canWrite}.</p>
1430 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001431 * @param networkType specifies which network the request pertains to
1432 * @param feature the name of the feature to be used
1433 * @return an integer value representing the outcome of the request.
1434 * The interpretation of this value is specific to each networking
1435 * implementation+feature combination, except that the value {@code -1}
1436 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001437 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001438 * @deprecated Deprecated in favor of the cleaner
1439 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001440 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001441 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001442 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001443 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001444 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001445 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001446 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001447 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1448 if (netCap == null) {
1449 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1450 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001451 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001452 }
1453
1454 NetworkRequest request = null;
1455 synchronized (sLegacyRequests) {
1456 LegacyRequest l = sLegacyRequests.get(netCap);
1457 if (l != null) {
1458 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1459 renewRequestLocked(l);
1460 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001461 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001462 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001463 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001464 }
1465 }
1466
1467 request = requestNetworkForFeatureLocked(netCap);
1468 }
1469 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001470 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001471 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001472 } else {
1473 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001474 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001475 }
1476 }
1477
1478 /**
1479 * Tells the underlying networking system that the caller is finished
1480 * using the named feature. The interpretation of {@code feature}
1481 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001482 *
1483 * <p>This method requires the caller to hold either the
1484 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1485 * or the ability to modify system settings as determined by
1486 * {@link android.provider.Settings.System#canWrite}.</p>
1487 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001488 * @param networkType specifies which network the request pertains to
1489 * @param feature the name of the feature that is no longer needed
1490 * @return an integer value representing the outcome of the request.
1491 * The interpretation of this value is specific to each networking
1492 * implementation+feature combination, except that the value {@code -1}
1493 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001494 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001495 * @deprecated Deprecated in favor of the cleaner
1496 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001497 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001498 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001499 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001500 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001501 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001502 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001503 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001504 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1505 if (netCap == null) {
1506 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1507 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001508 return -1;
1509 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001510
Paul Jensen49f74a32014-12-17 10:39:34 -05001511 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001512 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001513 }
1514 return 1;
1515 }
1516
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001517 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001518 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1519 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001520 switch (feature) {
1521 case "enableCBS":
1522 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1523 case "enableDUN":
1524 case "enableDUNAlways":
1525 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1526 case "enableFOTA":
1527 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1528 case "enableHIPRI":
1529 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1530 case "enableIMS":
1531 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1532 case "enableMMS":
1533 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1534 case "enableSUPL":
1535 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1536 default:
1537 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001538 }
Erik Klinece55eb12017-01-26 18:08:28 +09001539 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1540 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001541 }
1542 return null;
1543 }
1544
Robert Greenwalt802c1102014-06-02 15:32:02 -07001545 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001546 if (netCap == null) return TYPE_NONE;
1547 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1548 return TYPE_MOBILE_CBS;
1549 }
1550 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1551 return TYPE_MOBILE_IMS;
1552 }
1553 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1554 return TYPE_MOBILE_FOTA;
1555 }
1556 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1557 return TYPE_MOBILE_DUN;
1558 }
1559 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1560 return TYPE_MOBILE_SUPL;
1561 }
1562 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1563 return TYPE_MOBILE_MMS;
1564 }
1565 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1566 return TYPE_MOBILE_HIPRI;
1567 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001568 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1569 return TYPE_WIFI_P2P;
1570 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001571 return TYPE_NONE;
1572 }
1573
1574 private static class LegacyRequest {
1575 NetworkCapabilities networkCapabilities;
1576 NetworkRequest networkRequest;
1577 int expireSequenceNumber;
1578 Network currentNetwork;
1579 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001580
1581 private void clearDnsBinding() {
1582 if (currentNetwork != null) {
1583 currentNetwork = null;
1584 setProcessDefaultNetworkForHostResolution(null);
1585 }
1586 }
1587
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001588 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001589 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001590 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001591 currentNetwork = network;
1592 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001593 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001594 }
1595 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001596 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001597 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001598 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1599 }
1600 };
1601 }
1602
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001603 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001604 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1605 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001606
1607 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1608 synchronized (sLegacyRequests) {
1609 LegacyRequest l = sLegacyRequests.get(netCap);
1610 if (l != null) return l.networkRequest;
1611 }
1612 return null;
1613 }
1614
1615 private void renewRequestLocked(LegacyRequest l) {
1616 l.expireSequenceNumber++;
1617 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1618 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1619 }
1620
1621 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1622 int ourSeqNum = -1;
1623 synchronized (sLegacyRequests) {
1624 LegacyRequest l = sLegacyRequests.get(netCap);
1625 if (l == null) return;
1626 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001627 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001628 }
1629 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1630 }
1631
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001632 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001633 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1634 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001635 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001636 try {
1637 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001638 } catch (RemoteException e) {
1639 throw e.rethrowFromSystemServer();
1640 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001641 LegacyRequest l = new LegacyRequest();
1642 l.networkCapabilities = netCap;
1643 l.delay = delay;
1644 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001645 l.networkRequest = sendRequestForNetwork(
1646 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001647 if (l.networkRequest == null) return null;
1648 sLegacyRequests.put(netCap, l);
1649 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1650 return l.networkRequest;
1651 }
1652
1653 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1654 if (delay >= 0) {
1655 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001656 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001657 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1658 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001659 }
1660 }
1661
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001662 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001663 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1664 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001665 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001666 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001667 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001668 if (l == null) return false;
1669 unregisterNetworkCallback(l.networkCallback);
1670 l.clearDnsBinding();
1671 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001672 }
1673
Erik Klinece55eb12017-01-26 18:08:28 +09001674 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1675 static {
1676 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1677 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1678 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1679 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1680 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1681 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1682 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1683 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1684 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1685 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1686 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1687 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1688 }
1689
1690 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1691 static {
1692 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1693 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1694 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1695 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1696 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1697 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1698 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1699 }
1700
1701 /**
1702 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1703 * instance suitable for registering a request or callback. Throws an
1704 * IllegalArgumentException if no mapping from the legacy type to
1705 * NetworkCapabilities is known.
1706 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001707 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1708 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001709 * @hide
1710 */
1711 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1712 final NetworkCapabilities nc = new NetworkCapabilities();
1713
1714 // Map from type to transports.
1715 final int NOT_FOUND = -1;
1716 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichibc1104b2017-05-09 15:19:01 +09001717 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001718 nc.addTransportType(transport);
1719
1720 // Map from type to capabilities.
1721 nc.addCapability(sLegacyTypeToCapability.get(
1722 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1723 nc.maybeMarkCapabilitiesRestricted();
1724 return nc;
1725 }
1726
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001727 /** @hide */
1728 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001729 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001730 public PacketKeepaliveCallback() {
1731 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001732 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001733 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001734 public void onStarted() {}
1735 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001736 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001737 public void onStopped() {}
1738 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001739 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001740 public void onError(int error) {}
1741 }
1742
1743 /**
1744 * Allows applications to request that the system periodically send specific packets on their
1745 * behalf, using hardware offload to save battery power.
1746 *
1747 * To request that the system send keepalives, call one of the methods that return a
1748 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1749 * passing in a non-null callback. If the callback is successfully started, the callback's
1750 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1751 * specifying one of the {@code ERROR_*} constants in this class.
1752 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001753 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1754 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1755 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001756 *
junyulai4c95b082018-12-27 17:25:29 +08001757 * @deprecated Use {@link SocketKeepalive} instead.
1758 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001759 * @hide
1760 */
1761 public class PacketKeepalive {
1762
1763 private static final String TAG = "PacketKeepalive";
1764
1765 /** @hide */
1766 public static final int SUCCESS = 0;
1767
1768 /** @hide */
1769 public static final int NO_KEEPALIVE = -1;
1770
1771 /** @hide */
1772 public static final int BINDER_DIED = -10;
1773
1774 /** The specified {@code Network} is not connected. */
1775 public static final int ERROR_INVALID_NETWORK = -20;
1776 /** The specified IP addresses are invalid. For example, the specified source IP address is
1777 * not configured on the specified {@code Network}. */
1778 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1779 /** The requested port is invalid. */
1780 public static final int ERROR_INVALID_PORT = -22;
1781 /** The packet length is invalid (e.g., too long). */
1782 public static final int ERROR_INVALID_LENGTH = -23;
1783 /** The packet transmission interval is invalid (e.g., too short). */
1784 public static final int ERROR_INVALID_INTERVAL = -24;
1785
1786 /** The hardware does not support this request. */
1787 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001788 /** The hardware returned an error. */
1789 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001790
Nathan Harold0990bc82018-02-14 13:09:45 -08001791 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001792 public static final int NATT_PORT = 4500;
1793
Nathan Harold0990bc82018-02-14 13:09:45 -08001794 /** The minimum interval in seconds between keepalive packet transmissions */
1795 public static final int MIN_INTERVAL = 10;
1796
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001797 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001798 private final ISocketKeepaliveCallback mCallback;
1799 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001800
1801 private volatile Integer mSlot;
1802
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001803 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001804 public void stop() {
1805 try {
junyulai070f9ff2019-01-16 20:23:34 +08001806 mExecutor.execute(() -> {
1807 try {
1808 if (mSlot != null) {
1809 mService.stopKeepalive(mNetwork, mSlot);
1810 }
1811 } catch (RemoteException e) {
1812 Log.e(TAG, "Error stopping packet keepalive: ", e);
1813 throw e.rethrowFromSystemServer();
1814 }
1815 });
1816 } catch (RejectedExecutionException e) {
1817 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001818 }
1819 }
1820
1821 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09001822 Preconditions.checkNotNull(network, "network cannot be null");
1823 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001824 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001825 mExecutor = Executors.newSingleThreadExecutor();
1826 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001827 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001828 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001829 final long token = Binder.clearCallingIdentity();
1830 try {
1831 mExecutor.execute(() -> {
1832 mSlot = slot;
1833 callback.onStarted();
1834 });
1835 } finally {
1836 Binder.restoreCallingIdentity(token);
1837 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001838 }
junyulai070f9ff2019-01-16 20:23:34 +08001839
1840 @Override
1841 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001842 final long token = Binder.clearCallingIdentity();
1843 try {
1844 mExecutor.execute(() -> {
1845 mSlot = null;
1846 callback.onStopped();
1847 });
1848 } finally {
1849 Binder.restoreCallingIdentity(token);
1850 }
junyulai070f9ff2019-01-16 20:23:34 +08001851 mExecutor.shutdown();
1852 }
1853
1854 @Override
1855 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001856 final long token = Binder.clearCallingIdentity();
1857 try {
1858 mExecutor.execute(() -> {
1859 mSlot = null;
1860 callback.onError(error);
1861 });
1862 } finally {
1863 Binder.restoreCallingIdentity(token);
1864 }
junyulai070f9ff2019-01-16 20:23:34 +08001865 mExecutor.shutdown();
1866 }
1867
1868 @Override
1869 public void onDataReceived() {
1870 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1871 // this callback when data is received.
1872 }
1873 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001874 }
1875 }
1876
1877 /**
1878 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1879 *
junyulai4c95b082018-12-27 17:25:29 +08001880 * @deprecated Use {@link #createSocketKeepalive} instead.
1881 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001882 * @hide
1883 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001884 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001885 public PacketKeepalive startNattKeepalive(
1886 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1887 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1888 final PacketKeepalive k = new PacketKeepalive(network, callback);
1889 try {
junyulai070f9ff2019-01-16 20:23:34 +08001890 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001891 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1892 } catch (RemoteException e) {
1893 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001894 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001895 }
1896 return k;
1897 }
1898
Chiachang Wang619319a2021-01-15 11:06:21 +08001899 // Construct an invalid fd.
1900 private ParcelFileDescriptor createInvalidFd() {
1901 final int invalidFd = -1;
1902 return ParcelFileDescriptor.adoptFd(invalidFd);
1903 }
1904
The Android Open Source Project28527d22009-03-03 19:31:44 -08001905 /**
junyulai4c95b082018-12-27 17:25:29 +08001906 * Request that keepalives be started on a IPsec NAT-T socket.
1907 *
1908 * @param network The {@link Network} the socket is on.
1909 * @param socket The socket that needs to be kept alive.
1910 * @param source The source address of the {@link UdpEncapsulationSocket}.
1911 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1912 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1913 * must run callback sequentially, otherwise the order of callbacks cannot be
1914 * guaranteed.
1915 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1916 * changes. Must be extended by applications that use this API.
1917 *
junyulai0835a1e2019-01-08 20:04:33 +08001918 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1919 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001920 **/
junyulai7e06ad42019-03-04 22:45:36 +08001921 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001922 @NonNull UdpEncapsulationSocket socket,
1923 @NonNull InetAddress source,
1924 @NonNull InetAddress destination,
1925 @NonNull @CallbackExecutor Executor executor,
1926 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001927 ParcelFileDescriptor dup;
1928 try {
junyulai828dad12019-03-27 11:00:37 +08001929 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1930 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001931 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1932 } catch (IOException ignored) {
1933 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1934 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001935 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001936 }
1937 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1938 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08001939 }
1940
1941 /**
1942 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1943 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1944 *
1945 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08001946 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1947 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1948 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08001949 * @param source The source address of the {@link UdpEncapsulationSocket}.
1950 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1951 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1952 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1953 * must run callback sequentially, otherwise the order of callbacks cannot be
1954 * guaranteed.
1955 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1956 * changes. Must be extended by applications that use this API.
1957 *
junyulai0835a1e2019-01-08 20:04:33 +08001958 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1959 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08001960 * @hide
1961 */
1962 @SystemApi
1963 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08001964 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1965 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08001966 @NonNull InetAddress source,
1967 @NonNull InetAddress destination,
1968 @NonNull @CallbackExecutor Executor executor,
1969 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001970 ParcelFileDescriptor dup;
1971 try {
junyulai828dad12019-03-27 11:00:37 +08001972 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08001973 dup = pfd.dup();
1974 } catch (IOException ignored) {
1975 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1976 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001977 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001978 }
1979 return new NattSocketKeepalive(mService, network, dup,
1980 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08001981 }
1982
1983 /**
junyulai0835a1e2019-01-08 20:04:33 +08001984 * Request that keepalives be started on a TCP socket.
1985 * The socket must be established.
1986 *
1987 * @param network The {@link Network} the socket is on.
1988 * @param socket The socket that needs to be kept alive.
1989 * @param executor The executor on which callback will be invoked. This implementation assumes
1990 * the provided {@link Executor} runs the callbacks in sequence with no
1991 * concurrency. Failing this, no guarantee of correctness can be made. It is
1992 * the responsibility of the caller to ensure the executor provides this
1993 * guarantee. A simple way of creating such an executor is with the standard
1994 * tool {@code Executors.newSingleThreadExecutor}.
1995 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1996 * changes. Must be extended by applications that use this API.
1997 *
1998 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1999 * given socket.
2000 * @hide
2001 */
2002 @SystemApi
2003 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002004 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002005 @NonNull Socket socket,
2006 @NonNull Executor executor,
2007 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002008 ParcelFileDescriptor dup;
2009 try {
2010 dup = ParcelFileDescriptor.fromSocket(socket);
2011 } catch (UncheckedIOException ignored) {
2012 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2013 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002014 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002015 }
2016 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002017 }
2018
2019 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002020 * Ensure that a network route exists to deliver traffic to the specified
2021 * host via the specified network interface. An attempt to add a route that
2022 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002023 *
2024 * <p>This method requires the caller to hold either the
2025 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2026 * or the ability to modify system settings as determined by
2027 * {@link android.provider.Settings.System#canWrite}.</p>
2028 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002029 * @param networkType the type of the network over which traffic to the specified
2030 * host is to be routed
2031 * @param hostAddress the IP address of the host to which the route is desired
2032 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002033 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002034 * @deprecated Deprecated in favor of the
2035 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2036 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002037 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002038 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002039 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002040 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002041 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002042 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002043 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002044 }
2045
2046 /**
2047 * Ensure that a network route exists to deliver traffic to the specified
2048 * host via the specified network interface. An attempt to add a route that
2049 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002050 *
2051 * <p>This method requires the caller to hold either the
2052 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2053 * or the ability to modify system settings as determined by
2054 * {@link android.provider.Settings.System#canWrite}.</p>
2055 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002056 * @param networkType the type of the network over which traffic to the specified
2057 * host is to be routed
2058 * @param hostAddress the IP address of the host to which the route is desired
2059 * @return {@code true} on success, {@code false} on failure
2060 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002061 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002062 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002063 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002064 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002065 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002066 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002067 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002068 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002069 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2070 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002071 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002072 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002073 }
2074 }
2075
2076 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002077 * @return the context's attribution tag
2078 */
2079 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2080 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002081 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002082 }
2083
2084 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002085 * Returns the value of the setting for background data usage. If false,
2086 * applications should not use the network if the application is not in the
2087 * foreground. Developers should respect this setting, and check the value
2088 * of this before performing any background data operations.
2089 * <p>
2090 * All applications that have background services that use the network
2091 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002092 * <p>
Scott Main50589142011-10-06 18:32:43 -07002093 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002094 * background data depends on several combined factors, and this method will
2095 * always return {@code true}. Instead, when background data is unavailable,
2096 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002097 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002098 * @return Whether background data usage is allowed.
2099 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002100 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002101 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002102 // assume that background data is allowed; final authority is
2103 // NetworkInfo which may be blocked.
2104 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002105 }
2106
2107 /**
2108 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002109 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002110 * @param allowBackgroundData Whether an application should use data while
2111 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002112 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002113 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2114 * @see #getBackgroundDataSetting()
2115 * @hide
2116 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002117 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002118 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002119 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002120 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002121 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002122
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002123 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002124 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002125 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002126 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002127 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002128 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002129 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002130 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2131 if (tm != null) {
2132 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2133 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2134 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2135 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2136 + " retVal=" + retVal);
2137 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002138 }
Wink Saville689f7042014-12-05 11:10:30 -08002139 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002140 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002141 }
2142
The Android Open Source Project28527d22009-03-03 19:31:44 -08002143 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002144 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002145 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002146 */
2147 public interface OnNetworkActiveListener {
2148 /**
2149 * Called on the main thread of the process to report that the current data network
2150 * has become active, and it is now a good time to perform any pending network
2151 * operations. Note that this listener only tells you when the network becomes
2152 * active; if at any other time you want to know whether it is active (and thus okay
2153 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002154 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002155 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002156 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002157 }
2158
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002159 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002160 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002161
2162 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002163 * Start listening to reports when the system's default data network is active, meaning it is
2164 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2165 * to determine the current state of the system's default network after registering the
2166 * listener.
2167 * <p>
2168 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002169 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002170 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002171 *
2172 * @param l The listener to be told when the network is active.
2173 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002174 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002175 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2176 @Override
2177 public void onNetworkActive() throws RemoteException {
2178 l.onNetworkActive();
2179 }
2180 };
2181
2182 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002183 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002184 mNetworkActivityListeners.put(l, rl);
2185 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002186 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002187 }
2188 }
2189
2190 /**
2191 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002192 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002193 *
2194 * @param l Previously registered listener.
2195 */
Chalard Jean158702d2019-01-07 19:26:34 +09002196 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002197 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichibc1104b2017-05-09 15:19:01 +09002198 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002199 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002200 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002201 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002202 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002203 }
2204 }
2205
2206 /**
2207 * Return whether the data network is currently active. An active network means that
2208 * it is currently in a high power state for performing data transmission. On some
2209 * types of networks, it may be expensive to move and stay in such a state, so it is
2210 * more power efficient to batch network traffic together when the radio is already in
2211 * this state. This method tells you whether right now is currently a good time to
2212 * initiate network traffic, as the network is already active.
2213 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002214 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002215 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002216 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002217 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002218 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002219 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002220 }
2221
2222 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002223 * {@hide}
2224 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002225 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002226 mContext = Preconditions.checkNotNull(context, "missing context");
2227 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002228 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002229 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002230 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002231
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002232 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002233 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002234 public static ConnectivityManager from(Context context) {
2235 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2236 }
2237
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002238 /** @hide */
2239 public NetworkRequest getDefaultRequest() {
2240 try {
2241 // This is not racy as the default request is final in ConnectivityService.
2242 return mService.getDefaultRequest();
2243 } catch (RemoteException e) {
2244 throw e.rethrowFromSystemServer();
2245 }
2246 }
2247
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002248 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002249 * Check if the package is a allowed to write settings. This also accounts that such an access
2250 * happened.
2251 *
2252 * @return {@code true} iff the package is allowed to write settings.
2253 */
2254 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2255 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2256 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2257 boolean throwException) {
2258 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2259 throwException);
2260 }
2261
2262 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002263 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2264 * situations where a Context pointer is unavailable.
2265 * @hide
2266 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002267 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002268 static ConnectivityManager getInstanceOrNull() {
2269 return sInstance;
2270 }
2271
2272 /**
2273 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2274 * situations where a Context pointer is unavailable.
2275 * @hide
2276 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002277 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002278 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002279 private static ConnectivityManager getInstance() {
2280 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002281 throw new IllegalStateException("No ConnectivityManager yet constructed");
2282 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002283 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002284 }
2285
2286 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002287 * Get the set of tetherable, available interfaces. This list is limited by
2288 * device configuration and current interface existence.
2289 *
2290 * @return an array of 0 or more Strings of tetherable interface names.
2291 *
markchien6ae63e52020-01-21 13:11:06 +08002292 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002293 * {@hide}
2294 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002295 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002296 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002297 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002298 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002299 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002300 }
2301
2302 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002303 * Get the set of tethered interfaces.
2304 *
2305 * @return an array of 0 or more String of currently tethered interface names.
2306 *
markchien6ae63e52020-01-21 13:11:06 +08002307 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002308 * {@hide}
2309 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002310 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002311 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002312 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002313 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002314 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002315 }
2316
2317 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002318 * Get the set of interface names which attempted to tether but
2319 * failed. Re-attempting to tether may cause them to reset to the Tethered
2320 * state. Alternatively, causing the interface to be destroyed and recreated
2321 * may cause them to reset to the available state.
2322 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2323 * information on the cause of the errors.
2324 *
2325 * @return an array of 0 or more String indicating the interface names
2326 * which failed to tether.
2327 *
markchien6ae63e52020-01-21 13:11:06 +08002328 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002329 * {@hide}
2330 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002331 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002332 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002333 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002334 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002335 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002336 }
2337
2338 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002339 * Get the set of tethered dhcp ranges.
2340 *
markchien2e6ba522020-02-14 11:55:48 +08002341 * @deprecated This method is not supported.
2342 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002343 * {@hide}
2344 */
paulhu8e96a752019-08-12 16:25:11 +08002345 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002346 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002347 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002348 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002349 }
2350
2351 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002352 * Attempt to tether the named interface. This will setup a dhcp server
2353 * on the interface, forward and NAT IP packets and forward DNS requests
2354 * to the best active upstream network interface. Note that if no upstream
2355 * IP network interface is available, dhcp will still run and traffic will be
2356 * allowed between the tethered devices and this device, though upstream net
2357 * access will of course fail until an upstream network interface becomes
2358 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002359 *
2360 * <p>This method requires the caller to hold either the
2361 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2362 * or the ability to modify system settings as determined by
2363 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002364 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002365 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2366 * and WifiStateMachine which need direct access. All other clients should use
2367 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2368 * logic.</p>
2369 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002370 * @param iface the interface name to tether.
2371 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002372 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002373 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002374 * {@hide}
2375 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002376 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002377 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002378 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002379 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002380 }
2381
2382 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002383 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002384 *
2385 * <p>This method requires the caller to hold either the
2386 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2387 * or the ability to modify system settings as determined by
2388 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002389 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002390 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2391 * and WifiStateMachine which need direct access. All other clients should use
2392 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2393 * logic.</p>
2394 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002395 * @param iface the interface name to untether.
2396 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2397 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002398 * {@hide}
2399 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002400 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002401 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002402 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002403 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002404 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002405
2406 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002407 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002408 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002409 * due to device configuration.
2410 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002411 * <p>If this app does not have permission to use this API, it will always
2412 * return false rather than throw an exception.</p>
2413 *
2414 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2415 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2416 *
2417 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2418 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2419 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002420 * @return a boolean - {@code true} indicating Tethering is supported.
2421 *
markchien6ae63e52020-01-21 13:11:06 +08002422 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002423 * {@hide}
2424 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002425 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002426 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2427 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002428 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002429 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002430 }
2431
2432 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002433 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002434 *
2435 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002436 * @hide
2437 */
2438 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002439 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002440 public static abstract class OnStartTetheringCallback {
2441 /**
2442 * Called when tethering has been successfully started.
2443 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002444 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002445
2446 /**
2447 * Called when starting tethering failed.
2448 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002449 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002450 }
2451
2452 /**
2453 * Convenient overload for
2454 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2455 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002456 *
2457 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002458 * @hide
2459 */
2460 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002461 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002462 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002463 public void startTethering(int type, boolean showProvisioningUi,
2464 final OnStartTetheringCallback callback) {
2465 startTethering(type, showProvisioningUi, callback, null);
2466 }
2467
2468 /**
2469 * Runs tether provisioning for the given type if needed and then starts tethering if
2470 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2471 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2472 * schedules tether provisioning re-checks if appropriate.
2473 *
2474 * @param type The type of tethering to start. Must be one of
2475 * {@link ConnectivityManager.TETHERING_WIFI},
2476 * {@link ConnectivityManager.TETHERING_USB}, or
2477 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2478 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2479 * is one. This should be true the first time this function is called and also any time
2480 * the user can see this UI. It gives users information from their carrier about the
2481 * check failing and how they can sign up for tethering if possible.
2482 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2483 * of the result of trying to tether.
2484 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002485 *
2486 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002487 * @hide
2488 */
2489 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002490 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002491 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002492 public void startTethering(int type, boolean showProvisioningUi,
2493 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002494 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002495
markchien91c78e52020-01-20 19:31:56 +08002496 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002497 @Override
markchien91c78e52020-01-20 19:31:56 +08002498 public void execute(Runnable command) {
2499 if (handler == null) {
2500 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002501 } else {
markchien91c78e52020-01-20 19:31:56 +08002502 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002503 }
2504 }
2505 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002506
markchien91c78e52020-01-20 19:31:56 +08002507 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2508 @Override
2509 public void onTetheringStarted() {
2510 callback.onTetheringStarted();
2511 }
2512
2513 @Override
markchienf47d8342020-03-19 13:37:43 +08002514 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002515 callback.onTetheringFailed();
2516 }
2517 };
2518
2519 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002520 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002521
Amos Bianchia9b415a2020-03-04 11:07:38 -08002522 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002523 }
2524
2525 /**
2526 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2527 * applicable.
2528 *
2529 * @param type The type of tethering to stop. Must be one of
2530 * {@link ConnectivityManager.TETHERING_WIFI},
2531 * {@link ConnectivityManager.TETHERING_USB}, or
2532 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002533 *
2534 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002535 * @hide
2536 */
2537 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002538 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002539 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002540 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002541 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002542 }
2543
2544 /**
markchien4ef53e82019-02-27 14:56:11 +08002545 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2546 * upstream status.
2547 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002548 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002549 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002550 */
2551 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002552 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002553 public abstract static class OnTetheringEventCallback {
2554
2555 /**
2556 * Called when tethering upstream changed. This can be called multiple times and can be
2557 * called any time.
2558 *
2559 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2560 * have any upstream.
2561 */
2562 public void onUpstreamChanged(@Nullable Network network) {}
2563 }
2564
markchien6ae63e52020-01-21 13:11:06 +08002565 @GuardedBy("mTetheringEventCallbacks")
2566 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2567 mTetheringEventCallbacks = new ArrayMap<>();
2568
markchien4ef53e82019-02-27 14:56:11 +08002569 /**
2570 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002571 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002572 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2573 * with a null argument. The same callback object cannot be registered twice.
2574 *
2575 * @param executor the executor on which callback will be invoked.
2576 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002577 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002578 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002579 * @hide
2580 */
2581 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002582 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002583 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2584 public void registerTetheringEventCallback(
2585 @NonNull @CallbackExecutor Executor executor,
2586 @NonNull final OnTetheringEventCallback callback) {
2587 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2588
markchien6ae63e52020-01-21 13:11:06 +08002589 final TetheringEventCallback tetherCallback =
2590 new TetheringEventCallback() {
2591 @Override
2592 public void onUpstreamChanged(@Nullable Network network) {
2593 callback.onUpstreamChanged(network);
2594 }
2595 };
2596
2597 synchronized (mTetheringEventCallbacks) {
2598 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002599 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002600 }
markchien4ef53e82019-02-27 14:56:11 +08002601 }
2602
2603 /**
2604 * Remove tethering event callback previously registered with
2605 * {@link #registerTetheringEventCallback}.
2606 *
2607 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002608 *
2609 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002610 * @hide
2611 */
2612 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002613 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002614 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2615 public void unregisterTetheringEventCallback(
2616 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002617 Objects.requireNonNull(callback, "The callback must be non-null");
2618 synchronized (mTetheringEventCallbacks) {
2619 final TetheringEventCallback tetherCallback =
2620 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002621 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002622 }
markchien4ef53e82019-02-27 14:56:11 +08002623 }
2624
2625
2626 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002627 * Get the list of regular expressions that define any tetherable
2628 * USB network interfaces. If USB tethering is not supported by the
2629 * device, this list should be empty.
2630 *
2631 * @return an array of 0 or more regular expression Strings defining
2632 * what interfaces are considered tetherable usb interfaces.
2633 *
markchien6ae63e52020-01-21 13:11:06 +08002634 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002635 * {@hide}
2636 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002637 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002638 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002639 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002640 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002641 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002642 }
2643
2644 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002645 * Get the list of regular expressions that define any tetherable
2646 * Wifi network interfaces. If Wifi tethering is not supported by the
2647 * device, this list should be empty.
2648 *
2649 * @return an array of 0 or more regular expression Strings defining
2650 * what interfaces are considered tetherable wifi interfaces.
2651 *
markchien6ae63e52020-01-21 13:11:06 +08002652 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002653 * {@hide}
2654 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002655 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002656 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002657 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002658 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002659 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002660 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002661
Danica Chang96567052010-08-11 14:54:43 -07002662 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002663 * Get the list of regular expressions that define any tetherable
2664 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2665 * device, this list should be empty.
2666 *
2667 * @return an array of 0 or more regular expression Strings defining
2668 * what interfaces are considered tetherable bluetooth interfaces.
2669 *
markchien6ae63e52020-01-21 13:11:06 +08002670 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2671 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002672 * {@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
Danica Chang96567052010-08-11 14:54:43 -07002677 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002678 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002679 }
2680
Mike Lockwooded4a1742011-07-19 13:04:47 -07002681 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002682 * Attempt to both alter the mode of USB and Tethering of USB. A
2683 * utility method to deal with some of the complexity of USB - will
2684 * attempt to switch to Rndis and subsequently tether the resulting
2685 * interface on {@code true} or turn off tethering and switch off
2686 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002687 *
2688 * <p>This method requires the caller to hold either the
2689 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2690 * or the ability to modify system settings as determined by
2691 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002692 *
2693 * @param enable a boolean - {@code true} to enable tethering
2694 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002695 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002696 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002697 * {@hide}
2698 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002699 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002700 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002701 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002702 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002703 }
2704
markchien6ae63e52020-01-21 13:11:06 +08002705 /**
2706 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2707 * {@hide}
2708 */
markchien0f45bb92019-01-16 17:44:13 +08002709 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002710 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002711 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002712 /**
2713 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2714 * {@hide}
2715 */
2716 @Deprecated
2717 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2718 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2719 /**
2720 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2721 * {@hide}
2722 */
2723 @Deprecated
2724 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2725 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2726 /**
2727 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2728 * {@hide}
2729 */
2730 @Deprecated
2731 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2732 /**
2733 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2734 * {@hide}
2735 */
2736 @Deprecated
2737 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2738 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2739 /**
markchienf47d8342020-03-19 13:37:43 +08002740 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002741 * {@hide}
2742 */
2743 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002744 public static final int TETHER_ERROR_MASTER_ERROR =
2745 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002746 /**
2747 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2748 * {@hide}
2749 */
2750 @Deprecated
2751 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2752 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2753 /**
2754 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2755 * {@hide}
2756 */
2757 @Deprecated
2758 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2759 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2760 /**
markchienf47d8342020-03-19 13:37:43 +08002761 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002762 * {@hide}
2763 */
2764 @Deprecated
2765 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002766 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002767 /**
markchienf47d8342020-03-19 13:37:43 +08002768 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002769 * {@hide}
2770 */
2771 @Deprecated
2772 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002773 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002774 /**
2775 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2776 * {@hide}
2777 */
2778 @Deprecated
2779 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2780 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2781 /**
markchienf47d8342020-03-19 13:37:43 +08002782 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002783 * {@hide}
2784 */
markchien0f45bb92019-01-16 17:44:13 +08002785 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002786 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002787 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002788 /**
2789 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2790 * {@hide}
2791 */
2792 @Deprecated
2793 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2794 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2795 /**
2796 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2797 * {@hide}
2798 */
markchien0f45bb92019-01-16 17:44:13 +08002799 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002800 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002801 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002802
2803 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002804 * Get a more detailed error code after a Tethering or Untethering
2805 * request asynchronously failed.
2806 *
2807 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002808 * @return error The error code of the last error tethering or untethering the named
2809 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002810 *
markchien6ae63e52020-01-21 13:11:06 +08002811 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002812 * {@hide}
2813 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002814 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002815 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002816 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002817 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002818 int error = mTetheringManager.getLastTetherError(iface);
2819 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2820 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2821 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2822 // instead.
2823 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2824 }
2825 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002826 }
2827
markchienbf5ab012019-03-06 16:25:00 +08002828 /** @hide */
2829 @Retention(RetentionPolicy.SOURCE)
2830 @IntDef(value = {
2831 TETHER_ERROR_NO_ERROR,
2832 TETHER_ERROR_PROVISION_FAILED,
2833 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2834 })
2835 public @interface EntitlementResultCode {
2836 }
2837
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002838 /**
markchienbf5ab012019-03-06 16:25:00 +08002839 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002840 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002841 *
2842 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002843 * @hide
2844 */
2845 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002846 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002847 public interface OnTetheringEntitlementResultListener {
2848 /**
2849 * Called to notify entitlement result.
2850 *
2851 * @param resultCode an int value of entitlement result. It may be one of
2852 * {@link #TETHER_ERROR_NO_ERROR},
2853 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2854 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2855 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002856 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002857 }
2858
2859 /**
markchien0f45bb92019-01-16 17:44:13 +08002860 * Get the last value of the entitlement check on this downstream. If the cached value is
2861 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2862 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2863 * guaranteed that the UI-based entitlement check will complete in any specific time period
2864 * and may in fact never complete. Any successful entitlement check the platform performs for
2865 * any reason will update the cached value.
2866 *
2867 * @param type the downstream type of tethering. Must be one of
2868 * {@link #TETHERING_WIFI},
2869 * {@link #TETHERING_USB}, or
2870 * {@link #TETHERING_BLUETOOTH}.
2871 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002872 * @param executor the executor on which callback will be invoked.
2873 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2874 * notify the caller of the result of entitlement check. The listener may be called zero
2875 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002876 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002877 * {@hide}
2878 */
2879 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002880 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002881 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002882 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2883 @NonNull @CallbackExecutor Executor executor,
2884 @NonNull final OnTetheringEntitlementResultListener listener) {
2885 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2886 ResultReceiver wrappedListener = new ResultReceiver(null) {
2887 @Override
2888 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08002889 final long token = Binder.clearCallingIdentity();
2890 try {
2891 executor.execute(() -> {
2892 listener.onTetheringEntitlementResult(resultCode);
2893 });
2894 } finally {
2895 Binder.restoreCallingIdentity(token);
2896 }
markchienbf5ab012019-03-06 16:25:00 +08002897 }
2898 };
2899
Amos Bianchia9b415a2020-03-04 11:07:38 -08002900 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002901 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002902 }
2903
2904 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002905 * Report network connectivity status. This is currently used only
2906 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002907 * <p>This method requires the caller to hold the permission
2908 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002909 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002910 * @param networkType The type of network you want to report on
2911 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002912 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002913 * {@hide}
2914 */
2915 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002916 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002917 try {
2918 mService.reportInetCondition(networkType, percentage);
2919 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002920 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002921 }
2922 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002923
2924 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002925 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07002926 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002927 * the framework to re-evaluate network connectivity and/or switch to another
2928 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002929 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002930 * @param network The {@link Network} the application was attempting to use
2931 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04002932 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2933 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002934 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002935 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09002936 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002937 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002938 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04002939 // One of these will be ignored because it matches system's current state.
2940 // The other will trigger the necessary reevaluation.
2941 mService.reportNetworkConnectivity(network, true);
2942 mService.reportNetworkConnectivity(network, false);
2943 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002944 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04002945 }
2946 }
2947
2948 /**
2949 * Report to the framework whether a network has working connectivity.
2950 * This provides a hint to the system that a particular network is providing
2951 * working connectivity or not. In response the framework may re-evaluate
2952 * the network's connectivity and might take further action thereafter.
2953 *
2954 * @param network The {@link Network} the application was attempting to use
2955 * or {@code null} to indicate the current default network.
2956 * @param hasConnectivity {@code true} if the application was able to successfully access the
2957 * Internet using {@code network} or {@code false} if not.
2958 */
Chalard Jean158702d2019-01-07 19:26:34 +09002959 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002960 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04002961 try {
2962 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002963 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002964 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002965 }
2966 }
2967
2968 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002969 * Set a network-independent global http proxy. This is not normally what you want
2970 * for typical HTTP proxies - they are general network dependent. However if you're
2971 * doing something unusual like general internal filtering this may be useful. On
2972 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002973 *
2974 * @param p A {@link ProxyInfo} object defining the new global
2975 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002976 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002977 */
paulhu8e96a752019-08-12 16:25:11 +08002978 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04002979 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002980 try {
2981 mService.setGlobalProxy(p);
2982 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002983 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002984 }
2985 }
2986
2987 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002988 * Retrieve any network-independent global HTTP proxy.
2989 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04002990 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002991 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002992 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002993 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04002994 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002995 try {
2996 return mService.getGlobalProxy();
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 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003003 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3004 * network-specific HTTP proxy. If {@code network} is null, the
3005 * network-specific proxy returned is the proxy of the default active
3006 * network.
3007 *
3008 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3009 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3010 * or when {@code network} is {@code null},
3011 * the {@code ProxyInfo} for the default active network. Returns
3012 * {@code null} when no proxy applies or the caller doesn't have
3013 * permission to use {@code network}.
3014 * @hide
3015 */
3016 public ProxyInfo getProxyForNetwork(Network network) {
3017 try {
3018 return mService.getProxyForNetwork(network);
3019 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003020 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003021 }
3022 }
3023
3024 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003025 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3026 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003027 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003028 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003029 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003030 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003031 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003032 */
Chalard Jean158702d2019-01-07 19:26:34 +09003033 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003034 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003035 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003036 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003037
3038 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003039 * Returns true if the hardware supports the given network type
3040 * else it returns false. This doesn't indicate we have coverage
3041 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003042 * hardware supports it. For example a GSM phone without a SIM
3043 * should still return {@code true} for mobile data, but a wifi only
3044 * tablet would return {@code false}.
3045 *
3046 * @param networkType The network type we'd like to check
3047 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003048 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003049 * @hide
3050 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003051 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003052 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003053 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003054 public boolean isNetworkSupported(int networkType) {
3055 try {
3056 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003057 } catch (RemoteException e) {
3058 throw e.rethrowFromSystemServer();
3059 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003060 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003061
3062 /**
3063 * Returns if the currently active data network is metered. A network is
3064 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003065 * that connection due to monetary costs, data limitations or
3066 * battery/performance issues. You should check this before doing large
3067 * data transfers, and warn the user or delay the operation until another
3068 * network is available.
3069 *
3070 * @return {@code true} if large transfers should be avoided, otherwise
3071 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003072 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003073 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003074 public boolean isActiveNetworkMetered() {
3075 try {
3076 return mService.isActiveNetworkMetered();
3077 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003078 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003079 }
3080 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003081
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003082 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003083 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003084 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003085 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003086 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003087 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003088 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003089 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003090 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003091 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003092 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003093 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003094 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003095 }
3096 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003097
3098 /**
3099 * Set the value for enabling/disabling airplane mode
3100 *
3101 * @param enable whether to enable airplane mode or not
3102 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003103 * @hide
3104 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003105 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003106 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003107 android.Manifest.permission.NETWORK_SETTINGS,
3108 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3109 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003110 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003111 public void setAirplaneMode(boolean enable) {
3112 try {
3113 mService.setAirplaneMode(enable);
3114 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003115 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003116 }
3117 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003118
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003119 /**
3120 * Registers the specified {@link NetworkProvider}.
3121 * Each listener must only be registered once. The listener can be unregistered with
3122 * {@link #unregisterNetworkProvider}.
3123 *
3124 * @param provider the provider to register
3125 * @return the ID of the provider. This ID must be used by the provider when registering
3126 * {@link android.net.NetworkAgent}s.
3127 * @hide
3128 */
3129 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003130 @RequiresPermission(anyOf = {
3131 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3132 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003133 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3134 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003135 throw new IllegalStateException("NetworkProviders can only be registered once");
3136 }
3137
3138 try {
3139 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3140 provider.getName());
3141 provider.setProviderId(providerId);
3142 } catch (RemoteException e) {
3143 throw e.rethrowFromSystemServer();
3144 }
3145 return provider.getProviderId();
3146 }
3147
3148 /**
3149 * Unregisters the specified NetworkProvider.
3150 *
3151 * @param provider the provider to unregister
3152 * @hide
3153 */
3154 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003155 @RequiresPermission(anyOf = {
3156 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3157 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003158 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3159 try {
3160 mService.unregisterNetworkProvider(provider.getMessenger());
3161 } catch (RemoteException e) {
3162 throw e.rethrowFromSystemServer();
3163 }
3164 provider.setProviderId(NetworkProvider.ID_NONE);
3165 }
3166
3167
3168 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003169 @RequiresPermission(anyOf = {
3170 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3171 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003172 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3173 try {
3174 mService.declareNetworkRequestUnfulfillable(request);
3175 } catch (RemoteException e) {
3176 throw e.rethrowFromSystemServer();
3177 }
3178 }
3179
Chalard Jean29d06db2018-05-02 21:14:54 +09003180 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3181 // of dependent changes that would conflict throughout the automerger graph. Having this
3182 // temporarily helps with the process of going through with all these dependent changes across
3183 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003184 /**
3185 * @hide
3186 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003187 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003188 */
paulhub6ba8e82020-03-04 09:43:41 +08003189 @RequiresPermission(anyOf = {
3190 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3191 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003192 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003193 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003194 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003195 }
3196
3197 /**
3198 * @hide
3199 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003200 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003201 */
paulhub6ba8e82020-03-04 09:43:41 +08003202 @RequiresPermission(anyOf = {
3203 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3204 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003205 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003206 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003207 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003208 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003209 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003210 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003211 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003212 }
3213
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003214 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003215 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3216 * changes. Should be extended by applications wanting notifications.
3217 *
3218 * A {@code NetworkCallback} is registered by calling
3219 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3220 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003221 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003222 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3223 * A {@code NetworkCallback} should be registered at most once at any time.
3224 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003225 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003226 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003227 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003228 * Called when the framework connects to a new network to evaluate whether it satisfies this
3229 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3230 * callback. There is no guarantee that this new network will satisfy any requests, or that
3231 * the network will stay connected for longer than the time necessary to evaluate it.
3232 * <p>
3233 * Most applications <b>should not</b> act on this callback, and should instead use
3234 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3235 * the framework in properly evaluating the network &mdash; for example, an application that
3236 * can automatically log in to a captive portal without user intervention.
3237 *
3238 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003239 *
3240 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003241 */
paulhu1a407652019-03-22 16:35:06 +08003242 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003243
3244 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003245 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003246 * This callback may be called more than once if the {@link Network} that is
3247 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003248 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003249 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003250 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3251 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003252 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003253 * @hide
3254 */
paulhu1a407652019-03-22 16:35:06 +08003255 public void onAvailable(@NonNull Network network,
3256 @NonNull NetworkCapabilities networkCapabilities,
3257 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003258 // Internally only this method is called when a new network is available, and
3259 // it calls the callback in the same way and order that older versions used
3260 // to call so as not to change the behavior.
3261 onAvailable(network);
3262 if (!networkCapabilities.hasCapability(
3263 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3264 onNetworkSuspended(network);
3265 }
3266 onCapabilitiesChanged(network, networkCapabilities);
3267 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003268 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003269 }
3270
3271 /**
3272 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003273 *
3274 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3275 * be available at the same time, and onAvailable will be called for each of these as they
3276 * appear.
3277 *
3278 * <p>For callbacks registered with {@link #requestNetwork} and
3279 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3280 * is the new best network for this request and is now tracked by this callback ; this
3281 * callback will no longer receive method calls about other networks that may have been
3282 * passed to this method previously. The previously-best network may have disconnected, or
3283 * it may still be around and the newly-best network may simply be better.
3284 *
3285 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3286 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3287 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3288 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3289 *
3290 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3291 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3292 * this callback as this is prone to race conditions (there is no guarantee the objects
3293 * returned by these methods will be current). Instead, wait for a call to
3294 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3295 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3296 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003297 *
3298 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003299 */
paulhu1a407652019-03-22 16:35:06 +08003300 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003301
3302 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003303 * Called when the network is about to be lost, typically because there are no outstanding
3304 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3305 * with the new replacement network for graceful handover. This method is not guaranteed
3306 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3307 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003308 *
Chalard Jean01378b62019-08-30 16:27:28 +09003309 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3310 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3311 * this callback as this is prone to race conditions ; calling these methods while in a
3312 * callback may return an outdated or even a null object.
3313 *
3314 * @param network The {@link Network} that is about to be lost.
3315 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3316 * connected for graceful handover; note that the network may still
3317 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003318 */
paulhu1a407652019-03-22 16:35:06 +08003319 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003320
3321 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003322 * Called when a network disconnects or otherwise no longer satisfies this request or
3323 * callback.
3324 *
3325 * <p>If the callback was registered with requestNetwork() or
3326 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3327 * returned by onAvailable() when that network is lost and no other network satisfies
3328 * the criteria of the request.
3329 *
3330 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3331 * each network which no longer satisfies the criteria of the callback.
3332 *
3333 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3334 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3335 * this callback as this is prone to race conditions ; calling these methods while in a
3336 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003337 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003338 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003339 */
paulhu1a407652019-03-22 16:35:06 +08003340 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003341
3342 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003343 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003344 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3345 * requested network request cannot be fulfilled (whether or not a timeout was
3346 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003347 * {@link NetworkRequest} will have already been removed and released, as if
3348 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003349 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003350 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003351
3352 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003353 * Called when the network corresponding to this request changes capabilities but still
3354 * satisfies the requested criteria.
3355 *
3356 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3357 * to be called immediately after {@link #onAvailable}.
3358 *
3359 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3360 * ConnectivityManager methods in this callback as this is prone to race conditions :
3361 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003362 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003363 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003364 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3365 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003366 */
paulhu1a407652019-03-22 16:35:06 +08003367 public void onCapabilitiesChanged(@NonNull Network network,
3368 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003369
3370 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003371 * Called when the network corresponding to this request changes {@link LinkProperties}.
3372 *
3373 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3374 * to be called immediately after {@link #onAvailable}.
3375 *
3376 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3377 * ConnectivityManager methods in this callback as this is prone to race conditions :
3378 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003379 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003380 * @param network The {@link Network} whose link properties have changed.
3381 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003382 */
paulhu1a407652019-03-22 16:35:06 +08003383 public void onLinkPropertiesChanged(@NonNull Network network,
3384 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003385
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003386 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003387 * Called when the network the framework connected to for this request suspends data
3388 * transmission temporarily.
3389 *
3390 * <p>This generally means that while the TCP connections are still live temporarily
3391 * network data fails to transfer. To give a specific example, this is used on cellular
3392 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3393 * means read operations on sockets on this network will block once the buffers are
3394 * drained, and write operations will block once the buffers are full.
3395 *
3396 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3397 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3398 * this callback as this is prone to race conditions (there is no guarantee the objects
3399 * returned by these methods will be current).
3400 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003401 * @hide
3402 */
paulhu1a407652019-03-22 16:35:06 +08003403 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003404
3405 /**
3406 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003407 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3408 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003409
3410 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3411 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3412 * this callback as this is prone to race conditions : calling these methods while in a
3413 * callback may return an outdated or even a null object.
3414 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003415 * @hide
3416 */
paulhu1a407652019-03-22 16:35:06 +08003417 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003418
junyulaif2c67e42018-08-07 19:50:45 +08003419 /**
3420 * Called when access to the specified network is blocked or unblocked.
3421 *
Chalard Jean01378b62019-08-30 16:27:28 +09003422 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3423 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3424 * this callback as this is prone to race conditions : calling these methods while in a
3425 * callback may return an outdated or even a null object.
3426 *
junyulaif2c67e42018-08-07 19:50:45 +08003427 * @param network The {@link Network} whose blocked status has changed.
3428 * @param blocked The blocked status of this {@link Network}.
3429 */
junyulai7e06ad42019-03-04 22:45:36 +08003430 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003431
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003432 private NetworkRequest networkRequest;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003433 }
3434
Hugo Benichia590ab82017-05-11 13:16:17 +09003435 /**
3436 * Constant error codes used by ConnectivityService to communicate about failures and errors
3437 * across a Binder boundary.
3438 * @hide
3439 */
3440 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003441 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003442 }
3443
3444 /** @hide */
3445 public static class TooManyRequestsException extends RuntimeException {}
3446
3447 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3448 switch (e.errorCode) {
3449 case Errors.TOO_MANY_REQUESTS:
3450 return new TooManyRequestsException();
3451 default:
3452 Log.w(TAG, "Unknown service error code " + e.errorCode);
3453 return new RuntimeException(e);
3454 }
3455 }
3456
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003457 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003458 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003459 public static final int CALLBACK_PRECHECK = BASE + 1;
3460 /** @hide */
3461 public static final int CALLBACK_AVAILABLE = BASE + 2;
3462 /** @hide arg1 = TTL */
3463 public static final int CALLBACK_LOSING = BASE + 3;
3464 /** @hide */
3465 public static final int CALLBACK_LOST = BASE + 4;
3466 /** @hide */
3467 public static final int CALLBACK_UNAVAIL = BASE + 5;
3468 /** @hide */
3469 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3470 /** @hide */
3471 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003472 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003473 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003474 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003475 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003476 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003477 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003478 /** @hide */
3479 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003480
Erik Kline155a59a2015-11-25 12:49:38 +09003481 /** @hide */
3482 public static String getCallbackName(int whichCallback) {
3483 switch (whichCallback) {
3484 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3485 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3486 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3487 case CALLBACK_LOST: return "CALLBACK_LOST";
3488 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3489 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3490 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003491 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3492 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3493 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003494 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003495 default:
3496 return Integer.toString(whichCallback);
3497 }
3498 }
3499
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003500 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003501 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003502 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003503
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003504 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003505 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003506 }
3507
Hugo Benichifd44e912017-02-02 17:02:36 +09003508 CallbackHandler(Handler handler) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003509 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003510 }
3511
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003512 @Override
3513 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003514 if (message.what == EXPIRE_LEGACY_REQUEST) {
3515 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3516 return;
3517 }
3518
3519 final NetworkRequest request = getObject(message, NetworkRequest.class);
3520 final Network network = getObject(message, Network.class);
3521 final NetworkCallback callback;
3522 synchronized (sCallbacks) {
3523 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003524 if (callback == null) {
3525 Log.w(TAG,
3526 "callback not found for " + getCallbackName(message.what) + " message");
3527 return;
3528 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003529 if (message.what == CALLBACK_UNAVAIL) {
3530 sCallbacks.remove(request);
3531 callback.networkRequest = ALREADY_UNREGISTERED;
3532 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003533 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003534 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003535 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003536 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003537
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003538 switch (message.what) {
3539 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003540 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003541 break;
3542 }
3543 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003544 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3545 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003546 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003547 break;
3548 }
3549 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003550 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003551 break;
3552 }
3553 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003554 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003555 break;
3556 }
3557 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003558 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003559 break;
3560 }
3561 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003562 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3563 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003564 break;
3565 }
3566 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003567 LinkProperties lp = getObject(message, LinkProperties.class);
3568 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003569 break;
3570 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003571 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003572 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003573 break;
3574 }
3575 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003576 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003577 break;
3578 }
junyulaif2c67e42018-08-07 19:50:45 +08003579 case CALLBACK_BLK_CHANGED: {
3580 boolean blocked = message.arg1 != 0;
3581 callback.onBlockedStatusChanged(network, blocked);
3582 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003583 }
3584 }
3585
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003586 private <T> T getObject(Message msg, Class<T> c) {
3587 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003588 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003589 }
3590
Hugo Benichifd44e912017-02-02 17:02:36 +09003591 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003592 synchronized (sCallbacks) {
3593 if (sCallbackHandler == null) {
3594 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003595 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003596 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003597 }
3598 }
3599
Hugo Benichibc4ac972017-02-03 14:18:44 +09003600 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3601 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003602
Hugo Benichibc4ac972017-02-03 14:18:44 +09003603 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003604 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003605 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003606 checkCallbackNotNull(callback);
junyulaiad010792021-01-11 16:53:38 +08003607 Preconditions.checkArgument(
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09003608 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3609 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003610 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003611 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003612 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003613 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003614 if (callback.networkRequest != null
3615 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003616 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3617 // and requests (http://b/20701525).
3618 Log.e(TAG, "NetworkCallback was already registered");
3619 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003620 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003621 Binder binder = new Binder();
junyulaiad010792021-01-11 16:53:38 +08003622 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003623 request = mService.listenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003624 need, messenger, binder, callingPackageName,
3625 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003626 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003627 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003628 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3629 callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003630 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003631 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003632 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003633 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003634 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003635 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003636 } catch (RemoteException e) {
3637 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003638 } catch (ServiceSpecificException e) {
3639 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003640 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003641 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003642 }
3643
3644 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003645 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003646 *
markchienfac84a22020-03-18 21:16:15 +08003647 * This API is only for use in internal system code that requests networks with legacy type and
3648 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003649 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003650 *
markchiend6eeffd2020-01-14 00:55:21 +08003651 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003652 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3653 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3654 * be a positive value (i.e. >0).
3655 * @param legacyType to specify the network type(#TYPE_*).
3656 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003657 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3658 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003659 *
3660 * @hide
3661 */
markchiend6eeffd2020-01-14 00:55:21 +08003662 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003663 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003664 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003665 int timeoutMs, int legacyType, @NonNull Handler handler,
3666 @NonNull NetworkCallback networkCallback) {
3667 if (legacyType == TYPE_NONE) {
3668 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3669 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003670 CallbackHandler cbHandler = new CallbackHandler(handler);
3671 NetworkCapabilities nc = request.networkCapabilities;
3672 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003673 }
3674
3675 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003676 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003677 *
Chalard Jean01378b62019-08-30 16:27:28 +09003678 * <p>This method will attempt to find the best network that matches the passed
3679 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3680 * criteria. The platform will evaluate which network is the best at its own discretion.
3681 * Throughput, latency, cost per byte, policy, user preference and other considerations
3682 * may be factored in the decision of what is considered the best network.
3683 *
3684 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3685 * matching this request, while always attempting to match the request to a better network if
3686 * possible. If a better match is found, the platform will switch this request to the now-best
3687 * network and inform the app of the newly best network by invoking
3688 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3689 * will not try to maintain any other network than the best one currently matching the request:
3690 * a network not matching any network request may be disconnected at any time.
3691 *
3692 * <p>For example, an application could use this method to obtain a connected cellular network
3693 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3694 * radio to consume additional power. Or, an application could inform the system that it wants
3695 * a network supporting sending MMSes and have the system let it know about the currently best
3696 * MMS-supporting network through the provided {@link NetworkCallback}.
3697 *
3698 * <p>The status of the request can be followed by listening to the various callbacks described
3699 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3700 * used to direct traffic to the network (although accessing some networks may be subject to
3701 * holding specific permissions). Callers will learn about the specific characteristics of the
3702 * network through
3703 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3704 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3705 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3706 * matching the request at any given time; therefore when a better network matching the request
3707 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3708 * with the new network after which no further updates are given about the previously-best
3709 * network, unless it becomes the best again at some later time. All callbacks are invoked
3710 * in order on the same thread, which by default is a thread created by the framework running
3711 * in the app.
3712 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3713 * callbacks are invoked.
3714 *
3715 * <p>This{@link NetworkRequest} will live until released via
3716 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3717 * which point the system may let go of the network at any time.
3718 *
3719 * <p>A version of this method which takes a timeout is
3720 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3721 * wait for a limited amount of time for the network to become unavailable.
3722 *
Paul Jensenee52d232015-06-16 15:11:58 -04003723 * <p>It is presently unsupported to request a network with mutable
3724 * {@link NetworkCapabilities} such as
3725 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3726 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3727 * as these {@code NetworkCapabilities} represent states that a particular
3728 * network may never attain, and whether a network will attain these states
3729 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003730 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003731 *
3732 * <p>This method requires the caller to hold either the
3733 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3734 * or the ability to modify system settings as determined by
3735 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003736 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003737 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3738 * number of outstanding requests to 100 per app (identified by their UID), shared with
3739 * all variants of this method, of {@link #registerNetworkCallback} as well as
3740 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3741 * Requesting a network with this method will count toward this limit. If this limit is
3742 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3743 * make sure to unregister the callbacks with
3744 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3745 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003746 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003747 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3748 * the callback must not be shared - it uniquely specifies this request.
3749 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003750 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3751 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003752 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003753 */
Chalard Jean158702d2019-01-07 19:26:34 +09003754 public void requestNetwork(@NonNull NetworkRequest request,
3755 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003756 requestNetwork(request, networkCallback, getDefaultHandler());
3757 }
3758
3759 /**
3760 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3761 *
Chalard Jean01378b62019-08-30 16:27:28 +09003762 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3763 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003764 *
Chalard Jean01378b62019-08-30 16:27:28 +09003765 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003766 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3767 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003768 *
3769 * @param request {@link NetworkRequest} describing this request.
3770 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3771 * the callback must not be shared - it uniquely specifies this request.
3772 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003773 */
Chalard Jean158702d2019-01-07 19:26:34 +09003774 public void requestNetwork(@NonNull NetworkRequest request,
3775 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003776 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003777 NetworkCapabilities nc = request.networkCapabilities;
3778 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003779 }
3780
3781 /**
Etan Cohenf67bde92017-03-01 12:47:28 -08003782 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3783 * by a timeout.
3784 *
3785 * This function behaves identically to the non-timed-out version
3786 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3787 * is not found within the given time (in milliseconds) the
3788 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3789 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3790 * not have to be released if timed-out (it is automatically released). Unregistering a
3791 * request that timed out is not an error.
3792 *
3793 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3794 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3795 * for that purpose. Calling this method will attempt to bring up the requested network.
3796 *
Chalard Jean01378b62019-08-30 16:27:28 +09003797 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003798 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3799 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003800 *
3801 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003802 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3803 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003804 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3805 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3806 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003807 */
Chalard Jean158702d2019-01-07 19:26:34 +09003808 public void requestNetwork(@NonNull NetworkRequest request,
3809 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003810 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003811 NetworkCapabilities nc = request.networkCapabilities;
3812 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3813 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003814 }
3815
Hugo Benichifd44e912017-02-02 17:02:36 +09003816 /**
3817 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3818 * by a timeout.
3819 *
Chalard Jean01378b62019-08-30 16:27:28 +09003820 * This method behaves identically to
3821 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3822 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003823 *
Chalard Jean01378b62019-08-30 16:27:28 +09003824 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003825 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3826 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003827 *
3828 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003829 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3830 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003831 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003832 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3833 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003834 */
Chalard Jean158702d2019-01-07 19:26:34 +09003835 public void requestNetwork(@NonNull NetworkRequest request,
3836 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003837 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003838 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003839 NetworkCapabilities nc = request.networkCapabilities;
3840 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003841 }
3842
3843 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003844 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003845 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003846 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003847 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003848 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3849 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003850 */
Erik Kline8a826212014-11-19 12:12:24 +09003851 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003852
3853 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003854 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003855 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003856 * {@link android.content.Intent#getParcelableExtra(String)}.
3857 */
Erik Kline8a826212014-11-19 12:12:24 +09003858 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003859
3860
3861 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003862 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003863 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003864 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003865 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003866 * the request may outlive the calling application and get called back when a suitable
3867 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003868 * <p>
3869 * The operation is an Intent broadcast that goes to a broadcast receiver that
3870 * you registered with {@link Context#registerReceiver} or through the
3871 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3872 * <p>
3873 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003874 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3875 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003876 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003877 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003878 * Intent to reserve the network or it will be released shortly after the Intent
3879 * is processed.
3880 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003881 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003882 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003883 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003884 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003885 * The request may be released normally by calling
3886 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003887 * <p>It is presently unsupported to request a network with either
3888 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3889 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3890 * as these {@code NetworkCapabilities} represent states that a particular
3891 * network may never attain, and whether a network will attain these states
3892 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003893 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003894 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003895 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3896 * number of outstanding requests to 100 per app (identified by their UID), shared with
3897 * all variants of this method, of {@link #registerNetworkCallback} as well as
3898 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3899 * Requesting a network with this method will count toward this limit. If this limit is
3900 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3901 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3902 * or {@link #releaseNetworkRequest(PendingIntent)}.
3903 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003904 * <p>This method requires the caller to hold either the
3905 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3906 * or the ability to modify system settings as determined by
3907 * {@link android.provider.Settings.System#canWrite}.</p>
3908 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003909 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003910 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003911 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003912 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09003913 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3914 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003915 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003916 */
Chalard Jean158702d2019-01-07 19:26:34 +09003917 public void requestNetwork(@NonNull NetworkRequest request,
3918 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003919 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003920 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003921 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003922 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003923 request.networkCapabilities, operation, mContext.getOpPackageName(),
3924 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003925 } catch (RemoteException e) {
3926 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003927 } catch (ServiceSpecificException e) {
3928 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003929 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003930 }
3931
3932 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003933 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3934 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09003935 * This method has the same behavior as
3936 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003937 * releasing network resources and disconnecting.
3938 *
3939 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3940 * PendingIntent passed to
3941 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3942 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3943 */
Chalard Jean158702d2019-01-07 19:26:34 +09003944 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003945 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003946 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003947 try {
3948 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003949 } catch (RemoteException e) {
3950 throw e.rethrowFromSystemServer();
3951 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003952 }
3953
Hugo Benichibc1104b2017-05-09 15:19:01 +09003954 private static void checkPendingIntentNotNull(PendingIntent intent) {
3955 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3956 }
3957
3958 private static void checkCallbackNotNull(NetworkCallback callback) {
3959 Preconditions.checkNotNull(callback, "null NetworkCallback");
3960 }
3961
3962 private static void checkTimeout(int timeoutMs) {
3963 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003964 }
3965
3966 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003967 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003968 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08003969 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3970 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003971 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003972 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3973 * number of outstanding requests to 100 per app (identified by their UID), shared with
3974 * all variants of this method, of {@link #requestNetwork} as well as
3975 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3976 * Requesting a network with this method will count toward this limit. If this limit is
3977 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3978 * make sure to unregister the callbacks with
3979 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3980 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003981 * @param request {@link NetworkRequest} describing this request.
3982 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3983 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09003984 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003985 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003986 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003987 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09003988 public void registerNetworkCallback(@NonNull NetworkRequest request,
3989 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003990 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3991 }
3992
3993 /**
3994 * Registers to receive notifications about all networks which satisfy the given
3995 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08003996 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3997 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003998 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003999 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4000 * number of outstanding requests to 100 per app (identified by their UID), shared with
4001 * all variants of this method, of {@link #requestNetwork} as well as
4002 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4003 * Requesting a network with this method will count toward this limit. If this limit is
4004 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4005 * make sure to unregister the callbacks with
4006 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4007 *
4008 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004009 * @param request {@link NetworkRequest} describing this request.
4010 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4011 * networks change state.
4012 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004013 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004014 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004015 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004016 public void registerNetworkCallback(@NonNull NetworkRequest request,
4017 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004018 CallbackHandler cbHandler = new CallbackHandler(handler);
4019 NetworkCapabilities nc = request.networkCapabilities;
4020 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004021 }
4022
4023 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004024 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4025 * {@link NetworkRequest}.
4026 *
4027 * This function behaves identically to the version that takes a NetworkCallback, but instead
4028 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4029 * the request may outlive the calling application and get called back when a suitable
4030 * network is found.
4031 * <p>
4032 * The operation is an Intent broadcast that goes to a broadcast receiver that
4033 * you registered with {@link Context#registerReceiver} or through the
4034 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4035 * <p>
4036 * The operation Intent is delivered with two extras, a {@link Network} typed
4037 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4038 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4039 * the original requests parameters.
4040 * <p>
4041 * If there is already a request for this Intent registered (with the equality of
4042 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4043 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4044 * <p>
4045 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004046 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004047 *
4048 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4049 * number of outstanding requests to 100 per app (identified by their UID), shared with
4050 * all variants of this method, of {@link #requestNetwork} as well as
4051 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4052 * Requesting a network with this method will count toward this limit. If this limit is
4053 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4054 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4055 * or {@link #releaseNetworkRequest(PendingIntent)}.
4056 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004057 * @param request {@link NetworkRequest} describing this request.
4058 * @param operation Action to perform when the network is available (corresponds
4059 * to the {@link NetworkCallback#onAvailable} call. Typically
4060 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004061 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004062 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004063 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004064 public void registerNetworkCallback(@NonNull NetworkRequest request,
4065 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004066 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004067 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004068 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004069 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004070 request.networkCapabilities, operation, mContext.getOpPackageName(),
4071 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004072 } catch (RemoteException e) {
4073 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004074 } catch (ServiceSpecificException e) {
4075 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004076 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004077 }
4078
4079 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004080 * Registers to receive notifications about changes in the application's default network. This
4081 * may be a physical network or a virtual network, such as a VPN that applies to the
4082 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004083 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004084 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004085 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4086 * number of outstanding requests to 100 per app (identified by their UID), shared with
4087 * all variants of this method, of {@link #requestNetwork} as well as
4088 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4089 * Requesting a network with this method will count toward this limit. If this limit is
4090 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4091 * make sure to unregister the callbacks with
4092 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4093 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004094 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004095 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004096 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004097 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004098 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004099 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004100 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004101 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4102 }
4103
4104 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004105 * Registers to receive notifications about changes in the application's default network. This
4106 * may be a physical network or a virtual network, such as a VPN that applies to the
4107 * application. The callbacks will continue to be called until either the application exits or
4108 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4109 *
4110 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4111 * number of outstanding requests to 100 per app (identified by their UID), shared with
4112 * all variants of this method, of {@link #requestNetwork} as well as
4113 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4114 * Requesting a network with this method will count toward this limit. If this limit is
4115 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4116 * make sure to unregister the callbacks with
4117 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4118 *
4119 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4120 * application's default network changes.
4121 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4122 * @throws RuntimeException if the app already has too many callbacks registered.
4123 */
4124 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4125 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4126 @NonNull Handler handler) {
4127 CallbackHandler cbHandler = new CallbackHandler(handler);
4128 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4129 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4130 }
4131
4132 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004133 * Registers to receive notifications about changes in the system default network. The callbacks
4134 * will continue to be called until either the application exits or
4135 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004136 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004137 * This method should not be used to determine networking state seen by applications, because in
4138 * many cases, most or even all application traffic may not use the default network directly,
4139 * and traffic from different applications may go on different networks by default. As an
4140 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4141 * and not onto the system default network. Applications or system components desiring to do
4142 * determine network state as seen by applications should use other methods such as
4143 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4144 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004145 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4146 * number of outstanding requests to 100 per app (identified by their UID), shared with
4147 * all variants of this method, of {@link #requestNetwork} as well as
4148 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4149 * Requesting a network with this method will count toward this limit. If this limit is
4150 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4151 * make sure to unregister the callbacks with
4152 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4153 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004154 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4155 * system default network changes.
4156 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004157 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004158 *
4159 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004160 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004161 @SystemApi(client = MODULE_LIBRARIES)
4162 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4163 @RequiresPermission(anyOf = {
4164 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4165 android.Manifest.permission.NETWORK_SETTINGS})
4166 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004167 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004168 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004169 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004170 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004171 }
4172
4173 /**
fenglub00f4882015-04-21 17:12:05 -07004174 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4175 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4176 * network connection for updated bandwidth information. The caller will be notified via
4177 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004178 * method assumes that the caller has previously called
4179 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4180 * changes.
fenglu3f357402015-03-20 11:29:56 -07004181 *
fengluea2d9282015-04-27 14:28:04 -07004182 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004183 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004184 */
Chalard Jean158702d2019-01-07 19:26:34 +09004185 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004186 try {
fenglub00f4882015-04-21 17:12:05 -07004187 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004188 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004189 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004190 }
4191 }
4192
4193 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004194 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004195 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4196 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4197 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004198 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4199 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004200 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004201 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4202 * triggering it as soon as this call returns.
4203 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004204 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004205 */
Chalard Jean158702d2019-01-07 19:26:34 +09004206 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004207 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004208 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004209 final List<NetworkRequest> reqs = new ArrayList<>();
4210 // Find all requests associated to this callback and stop callback triggers immediately.
4211 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4212 synchronized (sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09004213 Preconditions.checkArgument(networkCallback.networkRequest != null,
4214 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004215 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4216 Log.d(TAG, "NetworkCallback was already unregistered");
4217 return;
4218 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004219 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4220 if (e.getValue() == networkCallback) {
4221 reqs.add(e.getKey());
4222 }
4223 }
4224 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4225 for (NetworkRequest r : reqs) {
4226 try {
4227 mService.releaseNetworkRequest(r);
4228 } catch (RemoteException e) {
4229 throw e.rethrowFromSystemServer();
4230 }
4231 // Only remove mapping if rpc was successful.
4232 sCallbacks.remove(r);
4233 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004234 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004235 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004236 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004237
4238 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004239 * Unregisters a callback previously registered via
4240 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4241 *
4242 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4243 * PendingIntent passed to
4244 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4245 * Cannot be null.
4246 */
Chalard Jean158702d2019-01-07 19:26:34 +09004247 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004248 releaseNetworkRequest(operation);
4249 }
4250
4251 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004252 * Informs the system whether it should switch to {@code network} regardless of whether it is
4253 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4254 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4255 * the system default network regardless of any other network that's currently connected. If
4256 * {@code always} is true, then the choice is remembered, so that the next time the user
4257 * connects to this network, the system will switch to it.
4258 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004259 * @param network The network to accept.
4260 * @param accept Whether to accept the network even if unvalidated.
4261 * @param always Whether to remember this choice in the future.
4262 *
4263 * @hide
4264 */
lucaslin2240ef62019-03-12 13:08:03 +08004265 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004266 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4267 try {
4268 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004269 } catch (RemoteException e) {
4270 throw e.rethrowFromSystemServer();
4271 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004272 }
4273
4274 /**
lucaslin2240ef62019-03-12 13:08:03 +08004275 * Informs the system whether it should consider the network as validated even if it only has
4276 * partial connectivity. If {@code accept} is true, then the network will be considered as
4277 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4278 * is remembered, so that the next time the user connects to this network, the system will
4279 * switch to it.
4280 *
4281 * @param network The network to accept.
4282 * @param accept Whether to consider the network as validated even if it has partial
4283 * connectivity.
4284 * @param always Whether to remember this choice in the future.
4285 *
4286 * @hide
4287 */
4288 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4289 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4290 try {
4291 mService.setAcceptPartialConnectivity(network, accept, always);
4292 } catch (RemoteException e) {
4293 throw e.rethrowFromSystemServer();
4294 }
4295 }
4296
4297 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004298 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4299 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4300 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4301 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4302 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004303 * @param network The network to accept.
4304 *
4305 * @hide
4306 */
lucaslin2240ef62019-03-12 13:08:03 +08004307 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004308 public void setAvoidUnvalidated(Network network) {
4309 try {
4310 mService.setAvoidUnvalidated(network);
4311 } catch (RemoteException e) {
4312 throw e.rethrowFromSystemServer();
4313 }
4314 }
4315
4316 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004317 * Requests that the system open the captive portal app on the specified network.
4318 *
4319 * @param network The network to log into.
4320 *
4321 * @hide
4322 */
paulhu8e96a752019-08-12 16:25:11 +08004323 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004324 public void startCaptivePortalApp(Network network) {
4325 try {
4326 mService.startCaptivePortalApp(network);
4327 } catch (RemoteException e) {
4328 throw e.rethrowFromSystemServer();
4329 }
4330 }
4331
4332 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004333 * Requests that the system open the captive portal app with the specified extras.
4334 *
4335 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4336 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004337 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004338 * @param appExtras Extras to include in the app start intent.
4339 * @hide
4340 */
4341 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004342 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004343 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004344 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004345 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004346 } catch (RemoteException e) {
4347 throw e.rethrowFromSystemServer();
4348 }
4349 }
4350
4351 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004352 * Determine whether the device is configured to avoid bad wifi.
4353 * @hide
4354 */
4355 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004356 @RequiresPermission(anyOf = {
4357 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4358 android.Manifest.permission.NETWORK_STACK})
4359 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004360 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004361 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004362 } catch (RemoteException e) {
4363 throw e.rethrowFromSystemServer();
4364 }
4365 }
4366
4367 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004368 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4369 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004370 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4371 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004372 *
4373 * An example of such an operation might be a time-sensitive foreground activity, such as a
4374 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4375 */
4376 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4377
4378 /**
4379 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4380 * a backup channel for traffic that is primarily going over another network.
4381 *
4382 * An example might be maintaining backup connections to peers or servers for the purpose of
4383 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4384 * on backup paths should be negligible compared to the traffic on the main path.
4385 */
4386 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4387
4388 /**
4389 * It is acceptable to use metered data to improve network latency and performance.
4390 */
4391 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4392
4393 /**
4394 * Return value to use for unmetered networks. On such networks we currently set all the flags
4395 * to true.
4396 * @hide
4397 */
4398 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4399 MULTIPATH_PREFERENCE_HANDOVER |
4400 MULTIPATH_PREFERENCE_RELIABILITY |
4401 MULTIPATH_PREFERENCE_PERFORMANCE;
4402
4403 /** @hide */
4404 @Retention(RetentionPolicy.SOURCE)
4405 @IntDef(flag = true, value = {
4406 MULTIPATH_PREFERENCE_HANDOVER,
4407 MULTIPATH_PREFERENCE_RELIABILITY,
4408 MULTIPATH_PREFERENCE_PERFORMANCE,
4409 })
4410 public @interface MultipathPreference {
4411 }
4412
4413 /**
4414 * Provides a hint to the calling application on whether it is desirable to use the
4415 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4416 * for multipath data transfer on this network when it is not the system default network.
4417 * Applications desiring to use multipath network protocols should call this method before
4418 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004419 *
4420 * @param network The network on which the application desires to use multipath data.
4421 * If {@code null}, this method will return the a preference that will generally
4422 * apply to metered networks.
4423 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4424 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004425 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004426 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004427 try {
4428 return mService.getMultipathPreference(network);
4429 } catch (RemoteException e) {
4430 throw e.rethrowFromSystemServer();
4431 }
4432 }
4433
4434 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004435 * Resets all connectivity manager settings back to factory defaults.
4436 * @hide
4437 */
paulhu8e96a752019-08-12 16:25:11 +08004438 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004439 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004440 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004441 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004442 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004443 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004444 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004445 }
4446 }
4447
4448 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004449 * Binds the current process to {@code network}. All Sockets created in the future
4450 * (and not explicitly bound via a bound SocketFactory from
4451 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4452 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4453 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4454 * work and all host name resolutions will fail. This is by design so an application doesn't
4455 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4456 * To clear binding pass {@code null} for {@code network}. Using individually bound
4457 * Sockets created by Network.getSocketFactory().createSocket() and
4458 * performing network-specific host name resolutions via
4459 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004460 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004461 *
4462 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4463 * the current binding.
4464 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4465 */
Chalard Jean158702d2019-01-07 19:26:34 +09004466 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004467 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004468 // instantiated.
4469 return setProcessDefaultNetwork(network);
4470 }
4471
4472 /**
4473 * Binds the current process to {@code network}. All Sockets created in the future
4474 * (and not explicitly bound via a bound SocketFactory from
4475 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4476 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4477 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4478 * work and all host name resolutions will fail. This is by design so an application doesn't
4479 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4480 * To clear binding pass {@code null} for {@code network}. Using individually bound
4481 * Sockets created by Network.getSocketFactory().createSocket() and
4482 * performing network-specific host name resolutions via
4483 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4484 * {@code setProcessDefaultNetwork}.
4485 *
4486 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4487 * the current binding.
4488 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4489 * @deprecated This function can throw {@link IllegalStateException}. Use
4490 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4491 * is a direct replacement.
4492 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004493 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004494 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004495 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004496 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4497
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004498 if (netId != NETID_UNSET) {
4499 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004500 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004501
4502 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4503 return false;
4504 }
4505
4506 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004507 // Set HTTP proxy system properties to match network.
4508 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004509 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004510 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004511 } catch (SecurityException e) {
4512 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4513 Log.e(TAG, "Can't set proxy properties", e);
4514 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004515 // Must flush DNS cache as new network may have different DNS resolutions.
4516 InetAddress.clearDnsCache();
4517 // Must flush socket pool as idle sockets will be bound to previous network and may
4518 // cause subsequent fetches to be performed on old network.
4519 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004520 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004521
4522 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004523 }
4524
4525 /**
4526 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004527 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004528 *
4529 * @return {@code Network} to which this process is bound, or {@code null}.
4530 */
Chalard Jean158702d2019-01-07 19:26:34 +09004531 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004532 public Network getBoundNetworkForProcess() {
4533 // Forcing callers to call thru non-static function ensures ConnectivityManager
4534 // instantiated.
4535 return getProcessDefaultNetwork();
4536 }
4537
4538 /**
4539 * Returns the {@link Network} currently bound to this process via
4540 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4541 *
4542 * @return {@code Network} to which this process is bound, or {@code null}.
4543 * @deprecated Using this function can lead to other functions throwing
4544 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4545 * {@code getBoundNetworkForProcess} is a direct replacement.
4546 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004547 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004548 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004549 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004550 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004551 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004552 return new Network(netId);
4553 }
4554
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004555 private void unsupportedStartingFrom(int version) {
4556 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004557 // The getApplicationInfo() call we make below is not supported in system context. Let
4558 // the call through here, and rely on the fact that ConnectivityService will refuse to
4559 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004560 return;
4561 }
4562
4563 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4564 throw new UnsupportedOperationException(
4565 "This method is not supported in target SDK version " + version + " and above");
4566 }
4567 }
4568
4569 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4570 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004571 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004572 // remove these exemptions. Note that this check is not secure, and apps can still access these
4573 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4574 // so is unsupported and may break in the future. http://b/22728205
4575 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004576 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004577 }
4578
Paul Jensen8cdda642014-05-29 10:12:39 -04004579 /**
4580 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004581 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004582 *
4583 * @param network The {@link Network} to bind host resolutions from the current process to, or
4584 * {@code null} to clear the current binding.
4585 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4586 * @hide
4587 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4588 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004589 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004590 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004591 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004592 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004593 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004594 }
Felipe Leme30511352016-01-22 09:44:57 -08004595
4596 /**
4597 * Device is not restricting metered network activity while application is running on
4598 * background.
4599 */
4600 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4601
4602 /**
4603 * Device is restricting metered network activity while application is running on background,
4604 * but application is allowed to bypass it.
4605 * <p>
4606 * In this state, application should take action to mitigate metered network access.
4607 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4608 */
4609 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4610
4611 /**
4612 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004613 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004614 * In this state, application should not try to use the network while running on background,
4615 * because it would be denied.
4616 */
4617 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4618
Felipe Lemed34c9af2016-01-27 14:46:39 -08004619 /**
4620 * A change in the background metered network activity restriction has occurred.
4621 * <p>
4622 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4623 * applies to them.
4624 * <p>
4625 * This is only sent to registered receivers, not manifest receivers.
4626 */
4627 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4628 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4629 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4630
Felipe Leme7e4c1852016-01-25 11:48:04 -08004631 /** @hide */
4632 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004633 @IntDef(flag = false, value = {
4634 RESTRICT_BACKGROUND_STATUS_DISABLED,
4635 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4636 RESTRICT_BACKGROUND_STATUS_ENABLED,
4637 })
Felipe Leme30511352016-01-22 09:44:57 -08004638 public @interface RestrictBackgroundStatus {
4639 }
4640
4641 private INetworkPolicyManager getNetworkPolicyManager() {
4642 synchronized (this) {
4643 if (mNPManager != null) {
4644 return mNPManager;
4645 }
4646 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4647 .getService(Context.NETWORK_POLICY_SERVICE));
4648 return mNPManager;
4649 }
4650 }
4651
4652 /**
4653 * Determines if the calling application is subject to metered network restrictions while
4654 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004655 *
4656 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4657 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4658 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004659 */
4660 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4661 try {
4662 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4663 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004664 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004665 }
4666 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004667
4668 /**
4669 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004670 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4671 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004672 *
4673 * @return Hash of network watchlist config file. Null if config does not exist.
4674 */
Chalard Jean158702d2019-01-07 19:26:34 +09004675 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004676 public byte[] getNetworkWatchlistConfigHash() {
4677 try {
4678 return mService.getNetworkWatchlistConfigHash();
4679 } catch (RemoteException e) {
4680 Log.e(TAG, "Unable to get watchlist config hash");
4681 throw e.rethrowFromSystemServer();
4682 }
4683 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004684
4685 /**
4686 * Returns the {@code uid} of the owner of a network connection.
4687 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004688 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4689 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004690 * @param local The local {@link InetSocketAddress} of a connection.
4691 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004692 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004693 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4694 * android.os.Process#INVALID_UID} if the connection is not found.
4695 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4696 * user.
4697 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004698 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004699 public int getConnectionOwnerUid(
4700 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004701 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4702 try {
4703 return mService.getConnectionOwnerUid(connectionInfo);
4704 } catch (RemoteException e) {
4705 throw e.rethrowFromSystemServer();
4706 }
4707 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004708
4709 private void printStackTrace() {
4710 if (DEBUG) {
4711 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4712 final StringBuffer sb = new StringBuffer();
4713 for (int i = 3; i < callStack.length; i++) {
4714 final String stackTrace = callStack[i].toString();
4715 if (stackTrace == null || stackTrace.contains("android.os")) {
4716 break;
4717 }
4718 sb.append(" [").append(stackTrace).append("]");
4719 }
4720 Log.d(TAG, "StackLog:" + sb.toString());
4721 }
4722 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004723
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004724 /** @hide */
4725 public TestNetworkManager startOrGetTestNetworkManager() {
4726 final IBinder tnBinder;
4727 try {
4728 tnBinder = mService.startOrGetTestNetworkService();
4729 } catch (RemoteException e) {
4730 throw e.rethrowFromSystemServer();
4731 }
4732
4733 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4734 }
4735
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004736 /** @hide */
4737 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4738 return new ConnectivityDiagnosticsManager(mContext, mService);
4739 }
4740
Cody Kestingf53a0752020-04-15 12:33:28 -07004741 /**
4742 * Simulates a Data Stall for the specified Network.
4743 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004744 * <p>This method should only be used for tests.
4745 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004746 * <p>The caller must be the owner of the specified Network.
4747 *
4748 * @param detectionMethod The detection method used to identify the Data Stall.
4749 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4750 * @param network The Network for which a Data Stall is being simluated.
4751 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4752 * @throws SecurityException if the caller is not the owner of the given network.
4753 * @hide
4754 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004755 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004756 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4757 android.Manifest.permission.NETWORK_STACK})
4758 public void simulateDataStall(int detectionMethod, long timestampMillis,
4759 @NonNull Network network, @NonNull PersistableBundle extras) {
4760 try {
4761 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4762 } catch (RemoteException e) {
4763 e.rethrowFromSystemServer();
4764 }
4765 }
James Mattis356a8792020-10-28 21:48:54 -07004766
Daniel Brightf9e945b2020-06-15 16:10:01 -07004767 @NonNull
4768 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4769
4770 /**
4771 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4772 * receive available QoS events related to the {@link Network} and local ip + port
4773 * specified within socketInfo.
4774 * <p/>
4775 * The same {@link QosCallback} must be unregistered before being registered a second time,
4776 * otherwise {@link QosCallbackRegistrationException} is thrown.
4777 * <p/>
4778 * This API does not, in itself, require any permission if called with a network that is not
4779 * restricted. However, the underlying implementation currently only supports the IMS network,
4780 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4781 * useful, because they'd never be called back on networks that they would have access to.
4782 *
4783 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4784 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4785 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4786 * @throws RuntimeException if the app already has too many callbacks registered.
4787 *
4788 * Exceptions after the time of registration is passed through
4789 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4790 *
4791 * @param socketInfo the socket information used to match QoS events
4792 * @param callback receives qos events that satisfy socketInfo
4793 * @param executor The executor on which the callback will be invoked. The provided
4794 * {@link Executor} must run callback sequentially, otherwise the order of
4795 * callbacks cannot be guaranteed.
4796 *
4797 * @hide
4798 */
4799 @SystemApi
4800 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4801 @NonNull final QosCallback callback,
4802 @CallbackExecutor @NonNull final Executor executor) {
4803 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4804 Objects.requireNonNull(callback, "callback must be non-null");
4805 Objects.requireNonNull(executor, "executor must be non-null");
4806
4807 try {
4808 synchronized (mQosCallbackConnections) {
4809 if (getQosCallbackConnection(callback) == null) {
4810 final QosCallbackConnection connection =
4811 new QosCallbackConnection(this, callback, executor);
4812 mQosCallbackConnections.add(connection);
4813 mService.registerQosSocketCallback(socketInfo, connection);
4814 } else {
4815 Log.e(TAG, "registerQosCallback: Callback already registered");
4816 throw new QosCallbackRegistrationException();
4817 }
4818 }
4819 } catch (final RemoteException e) {
4820 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4821
4822 // The same unregister method method is called for consistency even though nothing
4823 // will be sent to the ConnectivityService since the callback was never successfully
4824 // registered.
4825 unregisterQosCallback(callback);
4826 e.rethrowFromSystemServer();
4827 } catch (final ServiceSpecificException e) {
4828 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4829 unregisterQosCallback(callback);
4830 throw convertServiceException(e);
4831 }
4832 }
4833
4834 /**
4835 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4836 * events once unregistered and can be registered a second time.
4837 * <p/>
4838 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4839 *
4840 * @param callback the callback being unregistered
4841 *
4842 * @hide
4843 */
4844 @SystemApi
4845 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4846 Objects.requireNonNull(callback, "The callback must be non-null");
4847 try {
4848 synchronized (mQosCallbackConnections) {
4849 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4850 if (connection != null) {
4851 connection.stopReceivingMessages();
4852 mService.unregisterQosCallback(connection);
4853 mQosCallbackConnections.remove(connection);
4854 } else {
4855 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4856 }
4857 }
4858 } catch (final RemoteException e) {
4859 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4860 e.rethrowFromSystemServer();
4861 }
4862 }
4863
4864 /**
4865 * Gets the connection related to the callback.
4866 *
4867 * @param callback the callback to look up
4868 * @return the related connection
4869 */
4870 @Nullable
4871 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4872 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4873 // Checking by reference here is intentional
4874 if (connection.getCallback() == callback) {
4875 return connection;
4876 }
4877 }
4878 return null;
4879 }
Junyu Laia62493f2021-01-19 11:10:56 +00004880
4881 /**
4882 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4883 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4884 * be used to request that the system provide a network without causing the network to be
4885 * in the foreground.
4886 *
4887 * <p>This method will attempt to find the best network that matches the passed
4888 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4889 * criteria. The platform will evaluate which network is the best at its own discretion.
4890 * Throughput, latency, cost per byte, policy, user preference and other considerations
4891 * may be factored in the decision of what is considered the best network.
4892 *
4893 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4894 * matching this request, while always attempting to match the request to a better network if
4895 * possible. If a better match is found, the platform will switch this request to the now-best
4896 * network and inform the app of the newly best network by invoking
4897 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4898 * will not try to maintain any other network than the best one currently matching the request:
4899 * a network not matching any network request may be disconnected at any time.
4900 *
4901 * <p>For example, an application could use this method to obtain a connected cellular network
4902 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4903 * radio to consume additional power. Or, an application could inform the system that it wants
4904 * a network supporting sending MMSes and have the system let it know about the currently best
4905 * MMS-supporting network through the provided {@link NetworkCallback}.
4906 *
4907 * <p>The status of the request can be followed by listening to the various callbacks described
4908 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4909 * used to direct traffic to the network (although accessing some networks may be subject to
4910 * holding specific permissions). Callers will learn about the specific characteristics of the
4911 * network through
4912 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4913 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4914 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4915 * matching the request at any given time; therefore when a better network matching the request
4916 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4917 * with the new network after which no further updates are given about the previously-best
4918 * network, unless it becomes the best again at some later time. All callbacks are invoked
4919 * in order on the same thread, which by default is a thread created by the framework running
4920 * in the app.
4921 *
4922 * <p>This{@link NetworkRequest} will live until released via
4923 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4924 * which point the system may let go of the network at any time.
4925 *
4926 * <p>It is presently unsupported to request a network with mutable
4927 * {@link NetworkCapabilities} such as
4928 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4929 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4930 * as these {@code NetworkCapabilities} represent states that a particular
4931 * network may never attain, and whether a network will attain these states
4932 * is unknown prior to bringing up the network so the framework does not
4933 * know how to go about satisfying a request with these capabilities.
4934 *
4935 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4936 * number of outstanding requests to 100 per app (identified by their UID), shared with
4937 * all variants of this method, of {@link #registerNetworkCallback} as well as
4938 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4939 * Requesting a network with this method will count toward this limit. If this limit is
4940 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4941 * make sure to unregister the callbacks with
4942 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4943 *
4944 * @param request {@link NetworkRequest} describing this request.
4945 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4946 * If null, the callback is invoked on the default internal Handler.
4947 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4948 * the callback must not be shared - it uniquely specifies this request.
4949 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4950 * @throws SecurityException if missing the appropriate permissions.
4951 * @throws RuntimeException if the app already has too many callbacks registered.
4952 *
4953 * @hide
4954 */
4955 @SystemApi(client = MODULE_LIBRARIES)
4956 @SuppressLint("ExecutorRegistration")
4957 @RequiresPermission(anyOf = {
4958 android.Manifest.permission.NETWORK_SETTINGS,
4959 android.Manifest.permission.NETWORK_STACK,
4960 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4961 })
4962 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
4963 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
4964 final NetworkCapabilities nc = request.networkCapabilities;
4965 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
4966 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
4967 }
James Mattis45d81842021-01-10 14:24:24 -08004968
4969 /**
4970 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
4971 * OnSetOemNetworkPreferenceListener)}.
James Mattisda32cfe2021-01-26 16:23:52 -08004972 * @hide
James Mattis45d81842021-01-10 14:24:24 -08004973 */
James Mattisda32cfe2021-01-26 16:23:52 -08004974 @SystemApi
4975 public interface OnSetOemNetworkPreferenceListener {
James Mattis45d81842021-01-10 14:24:24 -08004976 /**
4977 * Called when setOemNetworkPreference() successfully completes.
4978 */
4979 void onComplete();
4980 }
4981
4982 /**
4983 * Used by automotive devices to set the network preferences used to direct traffic at an
4984 * application level as per the given OemNetworkPreferences. An example use-case would be an
4985 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
4986 * vehicle via a particular network.
4987 *
4988 * Calling this will overwrite the existing preference.
4989 *
4990 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
4991 * @param executor the executor on which listener will be invoked.
4992 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
4993 * communicate completion of setOemNetworkPreference(). This will only be
4994 * called once upon successful completion of setOemNetworkPreference().
4995 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
4996 * @throws SecurityException if missing the appropriate permissions.
4997 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08004998 * @hide
James Mattis45d81842021-01-10 14:24:24 -08004999 */
James Mattisda32cfe2021-01-26 16:23:52 -08005000 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005001 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005002 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005003 @Nullable @CallbackExecutor final Executor executor,
5004 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5005 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5006 if (null != listener) {
5007 Objects.requireNonNull(executor, "Executor must be non-null");
5008 }
5009 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5010 new IOnSetOemNetworkPreferenceListener.Stub() {
5011 @Override
5012 public void onComplete() {
5013 executor.execute(listener::onComplete);
5014 }
5015 };
5016
5017 try {
5018 mService.setOemNetworkPreference(preference, listenerInternal);
5019 } catch (RemoteException e) {
5020 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5021 throw e.rethrowFromSystemServer();
5022 }
5023 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005024}