blob: 25b6460ddf8943b785becb711b0b7606b809794b [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;
52import android.os.INetworkActivityListener;
53import android.os.INetworkManagementService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070054import android.os.Looper;
55import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070056import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080057import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070058import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090059import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080060import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080061import android.os.ResultReceiver;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080062import android.os.ServiceManager;
Hugo Benichia590ab82017-05-11 13:16:17 +090063import android.os.ServiceSpecificException;
Jeff Sharkey971cd162011-08-29 16:02:57 -070064import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080065import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080066import android.telephony.TelephonyManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080067import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070068import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090069import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090070import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080071
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090072import com.android.connectivity.aidl.INetworkAgent;
markchien6ae63e52020-01-21 13:11:06 +080073import com.android.internal.annotations.GuardedBy;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090074import com.android.internal.util.Preconditions;
75import com.android.internal.util.Protocol;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070076
Paul Jensen3e2917c2014-08-27 12:38:45 -040077import libcore.net.event.NetworkEventDispatcher;
78
junyulai7e06ad42019-03-04 22:45:36 +080079import java.io.IOException;
80import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080081import java.lang.annotation.Retention;
82import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090083import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080084import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070085import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080086import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090087import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090088import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080089import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090090import java.util.List;
91import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080092import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080093import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080094import java.util.concurrent.ExecutorService;
95import java.util.concurrent.Executors;
96import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -080097
The Android Open Source Project28527d22009-03-03 19:31:44 -080098/**
99 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600100 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101 * <p>
102 * The primary responsibilities of this class are to:
103 * <ol>
104 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
105 * <li>Send broadcast intents when network connectivity changes</li>
106 * <li>Attempt to "fail over" to another network when connectivity to a network
107 * is lost</li>
108 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
109 * state of the available networks</li>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700110 * <li>Provide an API that allows applications to request and select networks for their data
111 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800112 * </ol>
113 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600114@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700115public class ConnectivityManager {
116 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900117 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700118
The Android Open Source Project28527d22009-03-03 19:31:44 -0800119 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700120 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121 * been established or lost. The NetworkInfo for the affected network is
122 * sent as an extra; it should be consulted to see what kind of
123 * connectivity event occurred.
124 * <p/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800125 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
126 * broadcast if they declare the broadcast receiver in their manifest. Apps
127 * will still receive broadcasts if they register their
128 * {@link android.content.BroadcastReceiver} with
129 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
130 * and that context is still valid.
131 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132 * If this is a connection that was the result of failing over from a
133 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
134 * set to true.
135 * <p/>
136 * For a loss of connectivity, if the connectivity manager is attempting
137 * to connect (or has already connected) to another network, the
138 * NetworkInfo for the new network is also passed as an extra. This lets
139 * any receivers of the broadcast know that they should not necessarily
140 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800141 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800142 * the failover attempt succeeded (and so there is still overall data
143 * connectivity), or that the failover attempt failed, meaning that all
144 * connectivity has been lost.
145 * <p/>
146 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
147 * is set to {@code true} if there are no connected networks at all.
Chalard Jean52e23962018-02-10 05:33:50 +0900148 *
149 * @deprecated apps should use the more versatile {@link #requestNetwork},
150 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
151 * functions instead for faster and more detailed updates about the network
152 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800153 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800154 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900155 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700157
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500159 * The device has connected to a network that has presented a captive
160 * portal, which is blocking Internet connectivity. The user was presented
161 * with a notification that network sign in is required,
162 * and the user invoked the notification's action indicating they
Paul Jensen75e0adb2015-05-22 10:50:39 -0400163 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500164 * facilitate signing in to the network. This action includes a
165 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
166 * the network presenting the captive portal; all communication with the
167 * captive portal must be done using this {@code Network} object.
168 * <p/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400169 * This activity includes a {@link CaptivePortal} extra named
170 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
171 * outcomes of the captive portal sign in to the system:
172 * <ul>
173 * <li> When the app handling this action believes the user has signed in to
174 * the network and the captive portal has been dismissed, the app should
175 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
176 * reevaluate the network. If reevaluation finds the network no longer
177 * subject to a captive portal, the network may become the default active
Chalard Jean9dd11612018-06-04 16:52:49 +0900178 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400179 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500180 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400181 * {@link CaptivePortal#ignoreNetwork}. </li>
182 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500183 */
184 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
185 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
186
187 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800188 * The lookup key for a {@link NetworkInfo} object. Retrieve with
189 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700190 *
Chalard Jean97021a12019-01-11 16:47:53 +0900191 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
192 * can't accurately represent modern network characteristics.
193 * Please obtain information about networks from the {@link NetworkCapabilities}
194 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800195 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700196 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800197 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700198
The Android Open Source Project28527d22009-03-03 19:31:44 -0800199 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700200 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700201 *
202 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900203 * @deprecated The network type is not rich enough to represent the characteristics
204 * of modern networks. Please use {@link NetworkCapabilities} instead,
205 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700206 */
Chalard Jean97021a12019-01-11 16:47:53 +0900207 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700208 public static final String EXTRA_NETWORK_TYPE = "networkType";
209
210 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800211 * The lookup key for a boolean that indicates whether a connect event
212 * is for a network to which the connectivity manager was failing over
213 * following a disconnect on another network.
214 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai9826e7f2018-12-13 12:47:51 +0800215 *
216 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800217 */
junyulai9826e7f2018-12-13 12:47:51 +0800218 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800219 public static final String EXTRA_IS_FAILOVER = "isFailover";
220 /**
221 * The lookup key for a {@link NetworkInfo} object. This is supplied when
222 * there is another network that it may be possible to connect to. Retrieve with
223 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800224 *
225 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800226 */
junyulai9826e7f2018-12-13 12:47:51 +0800227 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800228 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
229 /**
230 * The lookup key for a boolean that indicates whether there is a
231 * complete lack of connectivity, i.e., no network is available.
232 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
233 */
234 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
235 /**
236 * The lookup key for a string that indicates why an attempt to connect
237 * to a network failed. The string has no particular structure. It is
238 * intended to be used in notifications presented to users. Retrieve
239 * it with {@link android.content.Intent#getStringExtra(String)}.
240 */
241 public static final String EXTRA_REASON = "reason";
242 /**
243 * The lookup key for a string that provides optionally supplied
244 * extra information about the network state. The information
245 * may be passed up from the lower networking layers, and its
246 * meaning may be specific to a particular network type. Retrieve
247 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800248 *
249 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800250 */
junyulai9826e7f2018-12-13 12:47:51 +0800251 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800252 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700253 /**
254 * The lookup key for an int that provides information about
255 * our connection to the internet at large. 0 indicates no connection,
256 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700257 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700258 * {@hide}
259 */
260 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800261 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400262 * The lookup key for a {@link CaptivePortal} object included with the
263 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
264 * object can be used to either indicate to the system that the captive
265 * portal has been dismissed or that the user does not want to pursue
266 * signing in to captive portal. Retrieve it with
267 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500268 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400269 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700270
271 /**
272 * Key for passing a URL to the captive portal login activity.
273 */
274 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
275
Paul Jensen60df4aa2015-02-27 22:55:47 -0500276 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900277 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
278 * portal login activity.
279 * {@hide}
280 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900281 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900282 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
283 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
284
285 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900286 * Key for passing a user agent string to the captive portal login activity.
287 * {@hide}
288 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900289 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900290 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
291 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
292
293 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700294 * Broadcast action to indicate the change of data activity status
295 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800296 * The network becomes active when data transmission is started, or
297 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700298 * {@hide}
299 */
300 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900301 public static final String ACTION_DATA_ACTIVITY_CHANGE =
302 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700303 /**
304 * The lookup key for an enum that indicates the network device type on which this data activity
305 * change happens.
306 * {@hide}
307 */
308 public static final String EXTRA_DEVICE_TYPE = "deviceType";
309 /**
310 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
311 * it is actively sending or receiving data and {@code false} means it is idle.
312 * {@hide}
313 */
314 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700315 /**
316 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
317 * {@hide}
318 */
319 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700320
321 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800322 * Broadcast Action: The setting for background data usage has changed
323 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
324 * <p>
325 * If an application uses the network in the background, it should listen
326 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700327 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800328 * <p>
329 *
330 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
331 * of background data depends on several combined factors, and
332 * this broadcast is no longer sent. Instead, when background
333 * data is unavailable, {@link #getActiveNetworkInfo()} will now
334 * appear disconnected. During first boot after a platform
335 * upgrade, this broadcast will be sent once if
336 * {@link #getBackgroundDataSetting()} was {@code false} before
337 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800338 */
339 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800340 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800341 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
342 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
343
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700344 /**
345 * Broadcast Action: The network connection may not be good
346 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
347 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
348 * the network and it's condition.
349 * @hide
350 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800351 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100352 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700353 public static final String INET_CONDITION_ACTION =
354 "android.net.conn.INET_CONDITION_ACTION";
355
Robert Greenwalt2034b912009-08-12 16:08:25 -0700356 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800357 * Broadcast Action: A tetherable connection has come or gone.
358 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900359 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
360 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800361 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
362 * the current state of tethering. Each include a list of
363 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800364 * @hide
365 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800366 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000367 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800368 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800369 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800370
371 /**
372 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800373 * gives a String[] listing all the interfaces configured for
374 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800375 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000376 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800377 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800378
379 /**
380 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900381 * gives a String[] listing all the interfaces currently in local-only
382 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800383 */
markchiena0f8fd92019-12-25 19:40:32 +0800384 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900385
386 /**
387 * @hide
388 * gives a String[] listing all the interfaces currently tethered
389 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
390 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000391 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800392 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800393
394 /**
395 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800396 * gives a String[] listing all the interfaces we tried to tether and
397 * failed. Use {@link #getLastTetherError} to find the error code
398 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800399 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000400 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800401 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800402
403 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800404 * Broadcast Action: The captive portal tracker has finished its test.
405 * Sent only while running Setup Wizard, in lieu of showing a user
406 * notification.
407 * @hide
408 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800409 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800410 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
411 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
412 /**
413 * The lookup key for a boolean that indicates whether a captive portal was detected.
414 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
415 * @hide
416 */
417 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
418
419 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900420 * Action used to display a dialog that asks the user whether to connect to a network that is
421 * not validated. This intent is used to start the dialog in settings via startActivity.
422 *
423 * @hide
424 */
425 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
426
427 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900428 * Action used to display a dialog that asks the user whether to avoid a network that is no
429 * longer validated. This intent is used to start the dialog in settings via startActivity.
430 *
431 * @hide
432 */
433 public static final String ACTION_PROMPT_LOST_VALIDATION =
434 "android.net.conn.PROMPT_LOST_VALIDATION";
435
436 /**
lucaslin2240ef62019-03-12 13:08:03 +0800437 * Action used to display a dialog that asks the user whether to stay connected to a network
438 * that has not validated. This intent is used to start the dialog in settings via
439 * startActivity.
440 *
441 * @hide
442 */
443 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
444 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
445
446 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800447 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900448 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800449 * @hide
450 */
markchiena0f8fd92019-12-25 19:40:32 +0800451 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800452
453 /**
454 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900455 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800456 * @hide
457 */
458 @SystemApi
markchiena0f8fd92019-12-25 19:40:32 +0800459 public static final int TETHERING_WIFI = TetheringManager.TETHERING_WIFI;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800460
461 /**
462 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900463 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800464 * @hide
465 */
466 @SystemApi
markchiena0f8fd92019-12-25 19:40:32 +0800467 public static final int TETHERING_USB = TetheringManager.TETHERING_USB;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800468
469 /**
470 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900471 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800472 * @hide
473 */
474 @SystemApi
markchiena0f8fd92019-12-25 19:40:32 +0800475 public static final int TETHERING_BLUETOOTH = TetheringManager.TETHERING_BLUETOOTH;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800476
477 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800478 * Wifi P2p tethering type.
479 * Wifi P2p tethering is set through events automatically, and don't
480 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
481 * @hide
482 */
markchiena0f8fd92019-12-25 19:40:32 +0800483 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800484
485 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800486 * Extra used for communicating with the TetherService. Includes the type of tethering to
487 * enable if any.
488 * @hide
489 */
markchien6ae63e52020-01-21 13:11:06 +0800490 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800491
492 /**
493 * Extra used for communicating with the TetherService. Includes the type of tethering for
494 * which to cancel provisioning.
495 * @hide
496 */
markchien6ae63e52020-01-21 13:11:06 +0800497 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800498
499 /**
500 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
501 * provisioning.
502 * @hide
503 */
markchien6ae63e52020-01-21 13:11:06 +0800504 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800505
506 /**
507 * Tells the TetherService to run a provision check now.
508 * @hide
509 */
markchien6ae63e52020-01-21 13:11:06 +0800510 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800511
512 /**
513 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
514 * which will receive provisioning results. Can be left empty.
515 * @hide
516 */
markchien6ae63e52020-01-21 13:11:06 +0800517 public static final String EXTRA_PROVISION_CALLBACK =
518 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800519
520 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800521 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700522 * @hide
523 */
paulhu74357e72020-01-13 16:46:45 +0800524 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700525 public static final int TYPE_NONE = -1;
526
527 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900528 * A Mobile data connection. Devices may support more than one.
529 *
530 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
531 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
532 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700533 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900534 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700535 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900536
Robert Greenwalt2034b912009-08-12 16:08:25 -0700537 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900538 * A WIFI data connection. Devices may support more than one.
539 *
540 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
541 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
542 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700543 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900544 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700545 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900546
Robert Greenwalt2034b912009-08-12 16:08:25 -0700547 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800548 * An MMS-specific Mobile data connection. This network type may use the
549 * same network interface as {@link #TYPE_MOBILE} or it may use a different
550 * one. This is used by applications needing to talk to the carrier's
551 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900552 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900553 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900554 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900555 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700556 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700557 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700558 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900559
Robert Greenwalt2034b912009-08-12 16:08:25 -0700560 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800561 * A SUPL-specific Mobile data connection. This network type may use the
562 * same network interface as {@link #TYPE_MOBILE} or it may use a different
563 * one. This is used by applications needing to talk to the carrier's
564 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900565 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900566 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900567 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900568 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700569 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700570 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900572
Robert Greenwalt2034b912009-08-12 16:08:25 -0700573 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800574 * A DUN-specific Mobile data connection. This network type may use the
575 * same network interface as {@link #TYPE_MOBILE} or it may use a different
576 * one. This is sometimes by the system when setting up an upstream connection
577 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900578 *
579 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
580 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
581 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700582 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900583 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900585
Robert Greenwalt2034b912009-08-12 16:08:25 -0700586 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800587 * A High Priority Mobile data connection. This network type uses the
588 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900589 * is different.
590 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900591 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
592 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
593 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700594 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700595 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700596 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900597
jshbfa81722010-03-11 15:04:43 -0800598 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900599 * A WiMAX data connection.
600 *
601 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
602 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
603 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800604 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900605 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800606 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800607
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800608 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900609 * A Bluetooth data connection.
610 *
611 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
612 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
613 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800614 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900615 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800616 public static final int TYPE_BLUETOOTH = 7;
617
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700618 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800619 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900620 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700621 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900622 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800623 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800624
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700625 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900626 * An Ethernet data connection.
627 *
628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
630 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700631 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900632 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800633 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700634
Wink Savilleb7c92c72011-03-12 14:52:01 -0800635 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800636 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900637 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800638 * {@hide}
639 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900640 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900641 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800642 public static final int TYPE_MOBILE_FOTA = 10;
643
644 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800645 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900646 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800647 * {@hide}
648 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900649 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100650 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800651 public static final int TYPE_MOBILE_IMS = 11;
652
653 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800654 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900655 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800656 * {@hide}
657 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900658 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900659 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800660 public static final int TYPE_MOBILE_CBS = 12;
661
repo syncf5de5572011-07-29 23:55:49 -0700662 /**
663 * A Wi-Fi p2p connection. Only requesting processes will have access to
664 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900665 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700666 * {@hide}
667 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900668 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800669 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700670 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800671
Wink Saville512c2202013-07-29 15:00:57 -0700672 /**
673 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900674 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700675 * {@hide}
676 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900677 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100678 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700679 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700680
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900681 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700682 * Emergency PDN connection for emergency services. This
683 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900684 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700685 * {@hide}
686 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900687 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900688 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700689 public static final int TYPE_MOBILE_EMERGENCY = 15;
690
Hui Lu865b70d2014-01-15 11:05:36 -0500691 /**
692 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900693 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500694 * {@hide}
695 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900696 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900697 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500698 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700699
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700700 /**
701 * A virtual network using one or more native bearers.
702 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900703 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700704 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900705 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700706 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500707
Benedict Wongbdfaa482018-11-14 17:40:55 -0800708 /**
709 * A network that is exclusively meant to be used for testing
710 *
711 * @deprecated Use {@link NetworkCapabilities} instead.
712 * @hide
713 */
714 @Deprecated
715 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700716
Chalard Jeanaea539a2020-03-25 01:24:04 +0900717 /**
718 * @deprecated Use {@link NetworkCapabilities} instead.
719 * @hide
720 */
721 @Deprecated
722 @Retention(RetentionPolicy.SOURCE)
723 @IntDef(prefix = { "TYPE_" }, value = {
724 TYPE_NONE,
725 TYPE_MOBILE,
726 TYPE_WIFI,
727 TYPE_MOBILE_MMS,
728 TYPE_MOBILE_SUPL,
729 TYPE_MOBILE_DUN,
730 TYPE_MOBILE_HIPRI,
731 TYPE_WIMAX,
732 TYPE_BLUETOOTH,
733 TYPE_DUMMY,
734 TYPE_ETHERNET,
735 TYPE_MOBILE_FOTA,
736 TYPE_MOBILE_IMS,
737 TYPE_MOBILE_CBS,
738 TYPE_WIFI_P2P,
739 TYPE_MOBILE_IA,
740 TYPE_MOBILE_EMERGENCY,
741 TYPE_PROXY,
742 TYPE_VPN,
743 TYPE_TEST
744 })
745 public @interface LegacyNetworkType {}
746
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900747 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
748 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
749 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
750 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
751 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
752
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700753 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800754 public static final int MAX_RADIO_TYPE = TYPE_TEST;
755
756 /** {@hide} */
757 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800758
Hugo Benichiad353f42017-06-20 14:07:59 +0900759 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
760
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800761 /**
762 * If you want to set the default network preference,you can directly
763 * change the networkAttributes array in framework's config.xml.
764 *
765 * @deprecated Since we support so many more networks now, the single
766 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800767 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800768 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800769 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800770 * from an App.
771 */
772 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800773 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
774
Jeff Sharkey8c870452012-09-26 22:03:49 -0700775 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700776 * @hide
777 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900778 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700779
Paul Jensen5dea4352014-07-11 12:28:19 -0400780 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900781 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
782 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900783 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900784 * @hide
785 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900786 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900787 new NetworkRequest.Builder().clearCapabilities().build();
788
789 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400790 * A NetID indicating no Network is selected.
791 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
792 * @hide
793 */
794 public static final int NETID_UNSET = 0;
795
Erik Klineb0be3e62017-10-30 15:29:44 +0900796 /**
797 * Private DNS Mode values.
798 *
799 * The "private_dns_mode" global setting stores a String value which is
800 * expected to be one of the following.
801 */
802
803 /**
804 * @hide
805 */
806 public static final String PRIVATE_DNS_MODE_OFF = "off";
807 /**
808 * @hide
809 */
810 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
811 /**
812 * @hide
813 */
814 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
815 /**
816 * The default Private DNS mode.
817 *
818 * This may change from release to release or may become dependent upon
819 * the capabilities of the underlying platform.
820 *
821 * @hide
822 */
Erik Klinea7edf6f2018-05-16 16:41:57 +0900823 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Klineb0be3e62017-10-30 15:29:44 +0900824
Chalard Jeana3b77512019-04-09 15:46:21 +0900825 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700826 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900827
Paul Jensenc0618a62014-12-10 15:12:18 -0500828 /**
829 * A kludge to facilitate static access where a Context pointer isn't available, like in the
830 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
831 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
832 * methods that take a Context argument.
833 */
834 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800835
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900836 private final Context mContext;
837
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800838 private INetworkManagementService mNMService;
Felipe Leme30511352016-01-22 09:44:57 -0800839 private INetworkPolicyManager mNPManager;
Amos Bianchia9b415a2020-03-04 11:07:38 -0800840 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800841
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800842 /**
843 * Tests if a given integer represents a valid network type.
844 * @param networkType the type to be tested
845 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400846 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
847 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800848 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700849 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700850 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900851 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800852 }
853
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800854 /**
855 * Returns a non-localized string representing a given network type.
856 * ONLY used for debugging output.
857 * @param type the type needing naming
858 * @return a String for the given type, or a string version of the type ("87")
859 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900860 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800861 * {@hide}
862 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900863 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000864 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700865 public static String getNetworkTypeName(int type) {
866 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900867 case TYPE_NONE:
868 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700869 case TYPE_MOBILE:
870 return "MOBILE";
871 case TYPE_WIFI:
872 return "WIFI";
873 case TYPE_MOBILE_MMS:
874 return "MOBILE_MMS";
875 case TYPE_MOBILE_SUPL:
876 return "MOBILE_SUPL";
877 case TYPE_MOBILE_DUN:
878 return "MOBILE_DUN";
879 case TYPE_MOBILE_HIPRI:
880 return "MOBILE_HIPRI";
881 case TYPE_WIMAX:
882 return "WIMAX";
883 case TYPE_BLUETOOTH:
884 return "BLUETOOTH";
885 case TYPE_DUMMY:
886 return "DUMMY";
887 case TYPE_ETHERNET:
888 return "ETHERNET";
889 case TYPE_MOBILE_FOTA:
890 return "MOBILE_FOTA";
891 case TYPE_MOBILE_IMS:
892 return "MOBILE_IMS";
893 case TYPE_MOBILE_CBS:
894 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700895 case TYPE_WIFI_P2P:
896 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700897 case TYPE_MOBILE_IA:
898 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700899 case TYPE_MOBILE_EMERGENCY:
900 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500901 case TYPE_PROXY:
902 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900903 case TYPE_VPN:
904 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700905 default:
906 return Integer.toString(type);
907 }
908 }
909
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800910 /**
Aaron Huang96011892020-06-27 07:18:23 +0800911 * @hide
912 * TODO: Expose for SystemServer when becomes a module.
913 */
914 public void systemReady() {
915 try {
916 mService.systemReady();
917 } catch (RemoteException e) {
918 throw e.rethrowFromSystemServer();
919 }
920 }
921
922 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800923 * Checks if a given type uses the cellular data connection.
924 * This should be replaced in the future by a network property.
925 * @param networkType the type to check
926 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900927 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800928 * {@hide}
929 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900930 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900931 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700932 public static boolean isNetworkTypeMobile(int networkType) {
933 switch (networkType) {
934 case TYPE_MOBILE:
935 case TYPE_MOBILE_MMS:
936 case TYPE_MOBILE_SUPL:
937 case TYPE_MOBILE_DUN:
938 case TYPE_MOBILE_HIPRI:
939 case TYPE_MOBILE_FOTA:
940 case TYPE_MOBILE_IMS:
941 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -0700942 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -0700943 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700944 return true;
945 default:
946 return false;
947 }
948 }
949
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800950 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700951 * Checks if the given network type is backed by a Wi-Fi radio.
952 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900953 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700954 * @hide
955 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900956 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700957 public static boolean isNetworkTypeWifi(int networkType) {
958 switch (networkType) {
959 case TYPE_WIFI:
960 case TYPE_WIFI_P2P:
961 return true;
962 default:
963 return false;
964 }
965 }
966
967 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800968 * Specifies the preferred network type. When the device has more
969 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800970 *
971 * @param preference the network type to prefer over all others. It is
972 * unspecified what happens to the old preferred network in the
973 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700974 * @deprecated Functionality has been removed as it no longer makes sense,
975 * with many more than two networks - we'd need an array to express
976 * preference. Instead we use dynamic network properties of
977 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800978 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700979 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800980 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800981 }
982
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800983 /**
984 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800985 *
986 * @return an integer representing the preferred network type
987 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700988 * @deprecated Functionality has been removed as it no longer makes sense,
989 * with many more than two networks - we'd need an array to express
990 * preference. Instead we use dynamic network properties of
991 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800992 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700993 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -0600994 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -0800995 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700996 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800997 }
998
Scott Mainf58b7d82011-10-06 19:02:28 -0700999 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001000 * Returns details about the currently active default data network. When
1001 * connected, this network is the default route for outgoing connections.
1002 * You should always check {@link NetworkInfo#isConnected()} before initiating
1003 * network traffic. This may return {@code null} when there is no default
1004 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001005 * Note that if the default network is a VPN, this method will return the
1006 * NetworkInfo for one of its underlying networks instead, or null if the
1007 * VPN agent did not specify any. Apps interested in learning about VPNs
1008 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001009 *
1010 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001011 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001012 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001013 */
junyulai9826e7f2018-12-13 12:47:51 +08001014 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001015 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001016 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001017 public NetworkInfo getActiveNetworkInfo() {
1018 try {
1019 return mService.getActiveNetworkInfo();
1020 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001021 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001022 }
1023 }
1024
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001025 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001026 * Returns a {@link Network} object corresponding to the currently active
1027 * default data network. In the event that the current active default data
1028 * network disconnects, the returned {@code Network} object will no longer
1029 * be usable. This will return {@code null} when there is no default
1030 * network.
1031 *
1032 * @return a {@link Network} object for the current default network or
1033 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001034 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001035 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001036 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001037 public Network getActiveNetwork() {
1038 try {
1039 return mService.getActiveNetwork();
1040 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001041 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001042 }
1043 }
1044
1045 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001046 * Returns a {@link Network} object corresponding to the currently active
1047 * default data network for a specific UID. In the event that the default data
1048 * network disconnects, the returned {@code Network} object will no longer
1049 * be usable. This will return {@code null} when there is no default
1050 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001051 *
1052 * @return a {@link Network} object for the current default network for the
1053 * given UID or {@code null} if no default network is currently active
1054 *
1055 * @hide
1056 */
paulhu8e96a752019-08-12 16:25:11 +08001057 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001058 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001059 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001060 return getActiveNetworkForUid(uid, false);
1061 }
1062
1063 /** {@hide} */
1064 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001065 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001066 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001067 } catch (RemoteException e) {
1068 throw e.rethrowFromSystemServer();
1069 }
1070 }
1071
1072 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001073 * Calls VpnManager#isAlwaysOnVpnPackageSupportedForUser.
1074 * @deprecated TODO: remove when callers have migrated to VpnManager.
Charles He9369e612017-05-15 17:07:18 +01001075 * @hide
1076 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09001077 @Deprecated
Charles He9369e612017-05-15 17:07:18 +01001078 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001079 return getVpnManager().isAlwaysOnVpnPackageSupportedForUser(userId, vpnPackage);
Charles He9369e612017-05-15 17:07:18 +01001080 }
1081
1082 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001083 * Calls VpnManager#setAlwaysOnVpnPackageForUser.
1084 * @deprecated TODO: remove when callers have migrated to VpnManager.
Robin Leee5d5ed52016-01-05 18:03:46 +00001085 * @hide
1086 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09001087 @Deprecated
Robin Lee94e69be2016-05-03 13:23:03 +01001088 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001089 boolean lockdownEnabled, @Nullable List<String> lockdownAllowlist) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001090 return getVpnManager().setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdownEnabled,
1091 lockdownAllowlist);
Robin Leee5d5ed52016-01-05 18:03:46 +00001092 }
1093
Lorenzo Colitticd675292021-02-04 17:32:07 +09001094 /**
1095 * Calls VpnManager#getAlwaysOnVpnPackageForUser.
1096 * @deprecated TODO: remove when callers have migrated to VpnManager.
Robin Leee5d5ed52016-01-05 18:03:46 +00001097 * @hide
1098 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09001099 @Deprecated
Robin Leee5d5ed52016-01-05 18:03:46 +00001100 public String getAlwaysOnVpnPackageForUser(int userId) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001101 return getVpnManager().getAlwaysOnVpnPackageForUser(userId);
Robin Leee5d5ed52016-01-05 18:03:46 +00001102 }
1103
1104 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001105 * Calls VpnManager#isVpnLockdownEnabled.
1106 * @deprecated TODO: remove when callers have migrated to VpnManager.
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001107 * @hide
Lorenzo Colitticd675292021-02-04 17:32:07 +09001108 */
1109 @Deprecated
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001110 public boolean isVpnLockdownEnabled(int userId) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001111 return getVpnManager().isVpnLockdownEnabled(userId);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001112 }
1113
1114 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001115 * Calls VpnManager#getVpnLockdownAllowlist.
1116 * @deprecated TODO: remove when callers have migrated to VpnManager.
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001117 * @hide
Lorenzo Colitticd675292021-02-04 17:32:07 +09001118 */
1119 @Deprecated
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001120 public List<String> getVpnLockdownWhitelist(int userId) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001121 return getVpnManager().getVpnLockdownAllowlist(userId);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001122 }
1123
1124 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001125 * Adds or removes a requirement for given UID ranges to use the VPN.
1126 *
1127 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1128 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1129 * otherwise have permission to bypass the VPN (e.g., because they have the
1130 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1131 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1132 * set to {@code false}, a previously-added restriction is removed.
1133 * <p>
1134 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1135 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1136 * remove a previously-added range, the exact range must be removed as is.
1137 * <p>
1138 * The changes are applied asynchronously and may not have been applied by the time the method
1139 * returns. Apps will be notified about any changes that apply to them via
1140 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1141 * effect.
1142 * <p>
1143 * This method should be called only by the VPN code.
1144 *
1145 * @param ranges the UID ranges to restrict
1146 * @param requireVpn whether the specified UID ranges must use a VPN
1147 *
1148 * TODO: expose as @SystemApi.
1149 * @hide
1150 */
1151 @RequiresPermission(anyOf = {
1152 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1153 android.Manifest.permission.NETWORK_STACK})
1154 public void setRequireVpnForUids(boolean requireVpn,
1155 @NonNull Collection<Range<Integer>> ranges) {
1156 Objects.requireNonNull(ranges);
1157 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1158 // This method is not necessarily expected to be used outside the system server, so
1159 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1160 // stack process, or by tests.
1161 UidRange[] rangesArray = new UidRange[ranges.size()];
1162 int index = 0;
1163 for (Range<Integer> range : ranges) {
1164 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1165 }
1166 try {
1167 mService.setRequireVpnForUids(requireVpn, rangesArray);
1168 } catch (RemoteException e) {
1169 throw e.rethrowFromSystemServer();
1170 }
1171 }
1172
1173 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001174 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1175 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1176 * but is still supported for backwards compatibility.
1177 * <p>
1178 * This type of VPN is assumed always to use the system default network, and must always declare
1179 * exactly one underlying network, which is the network that was the default when the VPN
1180 * connected.
1181 * <p>
1182 * Calling this method with {@code true} enables legacy behaviour, specifically:
1183 * <ul>
1184 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1185 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1186 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1187 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1188 * underlying the VPN.</li>
1189 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1190 * similarly replaced by the VPN network state.</li>
1191 * <li>Information on current network interfaces passed to NetworkStatsService will not
1192 * include any VPN interfaces.</li>
1193 * </ul>
1194 *
1195 * @param enabled whether legacy lockdown VPN is enabled or disabled
1196 *
1197 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1198 *
1199 * @hide
1200 */
1201 @RequiresPermission(anyOf = {
1202 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1203 android.Manifest.permission.NETWORK_SETTINGS})
1204 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1205 try {
1206 mService.setLegacyLockdownVpnEnabled(enabled);
1207 } catch (RemoteException e) {
1208 throw e.rethrowFromSystemServer();
1209 }
1210 }
1211
1212 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001213 * Returns details about the currently active default data network
1214 * for a given uid. This is for internal use only to avoid spying
1215 * other apps.
1216 *
1217 * @return a {@link NetworkInfo} object for the current default network
1218 * for the given uid or {@code null} if no default network is
1219 * available for the specified uid.
1220 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001221 * {@hide}
1222 */
paulhu8e96a752019-08-12 16:25:11 +08001223 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001224 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001225 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001226 return getActiveNetworkInfoForUid(uid, false);
1227 }
1228
1229 /** {@hide} */
1230 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001231 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001232 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001233 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001234 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001235 }
1236 }
1237
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001238 /**
1239 * Returns connection status information about a particular
1240 * network type.
1241 *
1242 * @param networkType integer specifying which networkType in
1243 * which you're interested.
1244 * @return a {@link NetworkInfo} object for the requested
1245 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001246 * supported by the device. If {@code networkType} is
1247 * TYPE_VPN and a VPN is active for the calling app,
1248 * then this method will try to return one of the
1249 * underlying networks for the VPN or null if the
1250 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001251 *
Paul Jensendda8e592015-03-18 12:23:02 -04001252 * @deprecated This method does not support multiple connected networks
1253 * of the same type. Use {@link #getAllNetworks} and
1254 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001255 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001256 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001257 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001258 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001259 public NetworkInfo getNetworkInfo(int networkType) {
1260 try {
1261 return mService.getNetworkInfo(networkType);
1262 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001263 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001264 }
1265 }
1266
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001267 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001268 * Returns connection status information about a particular
1269 * Network.
1270 *
1271 * @param network {@link Network} specifying which network
1272 * in which you're interested.
1273 * @return a {@link NetworkInfo} object for the requested
1274 * network or {@code null} if the {@code Network}
1275 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001276 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001277 */
junyulai9826e7f2018-12-13 12:47:51 +08001278 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001279 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001280 @Nullable
1281 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001282 return getNetworkInfoForUid(network, Process.myUid(), false);
1283 }
1284
1285 /** {@hide} */
1286 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001287 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001288 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001289 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001290 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001291 }
1292 }
1293
1294 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001295 * Returns connection status information about all network
1296 * types supported by the device.
1297 *
1298 * @return an array of {@link NetworkInfo} objects. Check each
1299 * {@link NetworkInfo#getType} for which type each applies.
1300 *
Paul Jensendda8e592015-03-18 12:23:02 -04001301 * @deprecated This method does not support multiple connected networks
1302 * of the same type. Use {@link #getAllNetworks} and
1303 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001304 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001305 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001306 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001307 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001308 public NetworkInfo[] getAllNetworkInfo() {
1309 try {
1310 return mService.getAllNetworkInfo();
1311 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001312 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001313 }
1314 }
1315
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001316 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001317 * Returns the {@link Network} object currently serving a given type, or
1318 * null if the given type is not connected.
1319 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001320 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001321 * @deprecated This method does not support multiple connected networks
1322 * of the same type. Use {@link #getAllNetworks} and
1323 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001324 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001325 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001326 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001327 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001328 public Network getNetworkForType(int networkType) {
1329 try {
1330 return mService.getNetworkForType(networkType);
1331 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001332 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001333 }
1334 }
1335
1336 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001337 * Returns an array of all {@link Network} currently tracked by the
1338 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001339 *
1340 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001341 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001342 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001343 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001344 public Network[] getAllNetworks() {
1345 try {
1346 return mService.getAllNetworks();
1347 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001348 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001349 }
1350 }
1351
1352 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001353 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001354 * the Networks that applications run by the given user will use by default.
1355 * @hide
1356 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001357 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001358 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1359 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001360 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001361 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001362 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001363 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001364 }
1365 }
1366
1367 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001368 * Returns the IP information for the current default network.
1369 *
1370 * @return a {@link LinkProperties} object describing the IP info
1371 * for the current default network, or {@code null} if there
1372 * is no current default network.
1373 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001374 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001375 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1376 * value of {@link #getActiveNetwork()} instead. In particular,
1377 * this method will return non-null LinkProperties even if the
1378 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001379 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001380 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001381 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001382 public LinkProperties getActiveLinkProperties() {
1383 try {
1384 return mService.getActiveLinkProperties();
1385 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001386 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001387 }
1388 }
1389
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001390 /**
1391 * Returns the IP information for a given network type.
1392 *
1393 * @param networkType the network type of interest.
1394 * @return a {@link LinkProperties} object describing the IP info
1395 * for the given networkType, or {@code null} if there is
1396 * no current default network.
1397 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001398 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001399 * @deprecated This method does not support multiple connected networks
1400 * of the same type. Use {@link #getAllNetworks},
1401 * {@link #getNetworkInfo(android.net.Network)}, and
1402 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001403 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001404 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001405 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001406 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001407 public LinkProperties getLinkProperties(int networkType) {
1408 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001409 return mService.getLinkPropertiesForType(networkType);
1410 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001411 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001412 }
1413 }
1414
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001415 /**
1416 * Get the {@link LinkProperties} for the given {@link Network}. This
1417 * will return {@code null} if the network is unknown.
1418 *
1419 * @param network The {@link Network} object identifying the network in question.
1420 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001421 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001422 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001423 @Nullable
1424 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001425 try {
1426 return mService.getLinkProperties(network);
1427 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001428 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001429 }
1430 }
1431
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001432 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001433 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001434 * will return {@code null} if the network is unknown.
1435 *
1436 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001437 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001438 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001439 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001440 @Nullable
1441 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001442 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001443 return mService.getNetworkCapabilities(
1444 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001445 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001446 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001447 }
1448 }
1449
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001450 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001451 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001452 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1453 * portal is present.
1454 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1455 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1456 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001457 * The system network validation may be using different strategies to detect captive portals,
1458 * so this method does not necessarily return a URL used by the system. It only returns a URL
1459 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001460 *
Udam Sainicd645462016-01-04 12:16:14 -08001461 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001462 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1463 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001464 */
paulhu8e96a752019-08-12 16:25:11 +08001465 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001466 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001467 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001468 public String getCaptivePortalServerUrl() {
1469 try {
1470 return mService.getCaptivePortalServerUrl();
1471 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001472 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001473 }
1474 }
1475
1476 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001477 * Tells the underlying networking system that the caller wants to
1478 * begin using the named feature. The interpretation of {@code feature}
1479 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001480 *
1481 * <p>This method requires the caller to hold either the
1482 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1483 * or the ability to modify system settings as determined by
1484 * {@link android.provider.Settings.System#canWrite}.</p>
1485 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001486 * @param networkType specifies which network the request pertains to
1487 * @param feature the name of the feature to be used
1488 * @return an integer value representing the outcome of the request.
1489 * The interpretation of this value is specific to each networking
1490 * implementation+feature combination, except that the value {@code -1}
1491 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001492 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001493 * @deprecated Deprecated in favor of the cleaner
1494 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001495 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001496 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001497 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001498 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001499 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001500 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001501 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001502 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1503 if (netCap == null) {
1504 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1505 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001506 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001507 }
1508
1509 NetworkRequest request = null;
1510 synchronized (sLegacyRequests) {
1511 LegacyRequest l = sLegacyRequests.get(netCap);
1512 if (l != null) {
1513 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1514 renewRequestLocked(l);
1515 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001516 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001517 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001518 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001519 }
1520 }
1521
1522 request = requestNetworkForFeatureLocked(netCap);
1523 }
1524 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001525 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001526 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001527 } else {
1528 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001529 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001530 }
1531 }
1532
1533 /**
1534 * Tells the underlying networking system that the caller is finished
1535 * using the named feature. The interpretation of {@code feature}
1536 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001537 *
1538 * <p>This method requires the caller to hold either the
1539 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1540 * or the ability to modify system settings as determined by
1541 * {@link android.provider.Settings.System#canWrite}.</p>
1542 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001543 * @param networkType specifies which network the request pertains to
1544 * @param feature the name of the feature that is no longer needed
1545 * @return an integer value representing the outcome of the request.
1546 * The interpretation of this value is specific to each networking
1547 * implementation+feature combination, except that the value {@code -1}
1548 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001549 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001550 * @deprecated Deprecated in favor of the cleaner
1551 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001552 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001553 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001554 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001555 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001556 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001557 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001558 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001559 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1560 if (netCap == null) {
1561 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1562 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001563 return -1;
1564 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001565
Paul Jensen49f74a32014-12-17 10:39:34 -05001566 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001567 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001568 }
1569 return 1;
1570 }
1571
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001572 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001573 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1574 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001575 switch (feature) {
1576 case "enableCBS":
1577 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1578 case "enableDUN":
1579 case "enableDUNAlways":
1580 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1581 case "enableFOTA":
1582 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1583 case "enableHIPRI":
1584 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1585 case "enableIMS":
1586 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1587 case "enableMMS":
1588 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1589 case "enableSUPL":
1590 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1591 default:
1592 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001593 }
Erik Klinece55eb12017-01-26 18:08:28 +09001594 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1595 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001596 }
1597 return null;
1598 }
1599
Robert Greenwalt802c1102014-06-02 15:32:02 -07001600 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001601 if (netCap == null) return TYPE_NONE;
1602 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1603 return TYPE_MOBILE_CBS;
1604 }
1605 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1606 return TYPE_MOBILE_IMS;
1607 }
1608 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1609 return TYPE_MOBILE_FOTA;
1610 }
1611 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1612 return TYPE_MOBILE_DUN;
1613 }
1614 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1615 return TYPE_MOBILE_SUPL;
1616 }
1617 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1618 return TYPE_MOBILE_MMS;
1619 }
1620 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1621 return TYPE_MOBILE_HIPRI;
1622 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001623 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1624 return TYPE_WIFI_P2P;
1625 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001626 return TYPE_NONE;
1627 }
1628
1629 private static class LegacyRequest {
1630 NetworkCapabilities networkCapabilities;
1631 NetworkRequest networkRequest;
1632 int expireSequenceNumber;
1633 Network currentNetwork;
1634 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001635
1636 private void clearDnsBinding() {
1637 if (currentNetwork != null) {
1638 currentNetwork = null;
1639 setProcessDefaultNetworkForHostResolution(null);
1640 }
1641 }
1642
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001643 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001644 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001645 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001646 currentNetwork = network;
1647 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001648 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001649 }
1650 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001651 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001652 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001653 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1654 }
1655 };
1656 }
1657
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001658 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001659 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1660 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001661
1662 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1663 synchronized (sLegacyRequests) {
1664 LegacyRequest l = sLegacyRequests.get(netCap);
1665 if (l != null) return l.networkRequest;
1666 }
1667 return null;
1668 }
1669
1670 private void renewRequestLocked(LegacyRequest l) {
1671 l.expireSequenceNumber++;
1672 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1673 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1674 }
1675
1676 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1677 int ourSeqNum = -1;
1678 synchronized (sLegacyRequests) {
1679 LegacyRequest l = sLegacyRequests.get(netCap);
1680 if (l == null) return;
1681 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001682 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001683 }
1684 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1685 }
1686
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001687 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001688 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1689 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001690 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001691 try {
1692 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001693 } catch (RemoteException e) {
1694 throw e.rethrowFromSystemServer();
1695 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001696 LegacyRequest l = new LegacyRequest();
1697 l.networkCapabilities = netCap;
1698 l.delay = delay;
1699 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001700 l.networkRequest = sendRequestForNetwork(
1701 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001702 if (l.networkRequest == null) return null;
1703 sLegacyRequests.put(netCap, l);
1704 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1705 return l.networkRequest;
1706 }
1707
1708 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1709 if (delay >= 0) {
1710 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001711 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001712 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1713 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001714 }
1715 }
1716
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001717 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001718 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1719 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001720 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001721 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001722 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001723 if (l == null) return false;
1724 unregisterNetworkCallback(l.networkCallback);
1725 l.clearDnsBinding();
1726 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001727 }
1728
Erik Klinece55eb12017-01-26 18:08:28 +09001729 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1730 static {
1731 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1732 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1733 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1734 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1735 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1736 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1737 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1738 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1739 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1740 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1741 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1742 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1743 }
1744
1745 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1746 static {
1747 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1748 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1749 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1750 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1751 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1752 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1753 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1754 }
1755
1756 /**
1757 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1758 * instance suitable for registering a request or callback. Throws an
1759 * IllegalArgumentException if no mapping from the legacy type to
1760 * NetworkCapabilities is known.
1761 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001762 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1763 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001764 * @hide
1765 */
1766 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1767 final NetworkCapabilities nc = new NetworkCapabilities();
1768
1769 // Map from type to transports.
1770 final int NOT_FOUND = -1;
1771 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichibc1104b2017-05-09 15:19:01 +09001772 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001773 nc.addTransportType(transport);
1774
1775 // Map from type to capabilities.
1776 nc.addCapability(sLegacyTypeToCapability.get(
1777 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1778 nc.maybeMarkCapabilitiesRestricted();
1779 return nc;
1780 }
1781
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001782 /** @hide */
1783 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001784 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001785 public PacketKeepaliveCallback() {
1786 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001787 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001788 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001789 public void onStarted() {}
1790 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001791 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001792 public void onStopped() {}
1793 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001794 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001795 public void onError(int error) {}
1796 }
1797
1798 /**
1799 * Allows applications to request that the system periodically send specific packets on their
1800 * behalf, using hardware offload to save battery power.
1801 *
1802 * To request that the system send keepalives, call one of the methods that return a
1803 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1804 * passing in a non-null callback. If the callback is successfully started, the callback's
1805 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1806 * specifying one of the {@code ERROR_*} constants in this class.
1807 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001808 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1809 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1810 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001811 *
junyulai4c95b082018-12-27 17:25:29 +08001812 * @deprecated Use {@link SocketKeepalive} instead.
1813 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001814 * @hide
1815 */
1816 public class PacketKeepalive {
1817
1818 private static final String TAG = "PacketKeepalive";
1819
1820 /** @hide */
1821 public static final int SUCCESS = 0;
1822
1823 /** @hide */
1824 public static final int NO_KEEPALIVE = -1;
1825
1826 /** @hide */
1827 public static final int BINDER_DIED = -10;
1828
1829 /** The specified {@code Network} is not connected. */
1830 public static final int ERROR_INVALID_NETWORK = -20;
1831 /** The specified IP addresses are invalid. For example, the specified source IP address is
1832 * not configured on the specified {@code Network}. */
1833 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1834 /** The requested port is invalid. */
1835 public static final int ERROR_INVALID_PORT = -22;
1836 /** The packet length is invalid (e.g., too long). */
1837 public static final int ERROR_INVALID_LENGTH = -23;
1838 /** The packet transmission interval is invalid (e.g., too short). */
1839 public static final int ERROR_INVALID_INTERVAL = -24;
1840
1841 /** The hardware does not support this request. */
1842 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001843 /** The hardware returned an error. */
1844 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001845
Nathan Harold0990bc82018-02-14 13:09:45 -08001846 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001847 public static final int NATT_PORT = 4500;
1848
Nathan Harold0990bc82018-02-14 13:09:45 -08001849 /** The minimum interval in seconds between keepalive packet transmissions */
1850 public static final int MIN_INTERVAL = 10;
1851
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001852 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001853 private final ISocketKeepaliveCallback mCallback;
1854 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001855
1856 private volatile Integer mSlot;
1857
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001858 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001859 public void stop() {
1860 try {
junyulai070f9ff2019-01-16 20:23:34 +08001861 mExecutor.execute(() -> {
1862 try {
1863 if (mSlot != null) {
1864 mService.stopKeepalive(mNetwork, mSlot);
1865 }
1866 } catch (RemoteException e) {
1867 Log.e(TAG, "Error stopping packet keepalive: ", e);
1868 throw e.rethrowFromSystemServer();
1869 }
1870 });
1871 } catch (RejectedExecutionException e) {
1872 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001873 }
1874 }
1875
1876 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09001877 Preconditions.checkNotNull(network, "network cannot be null");
1878 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001879 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001880 mExecutor = Executors.newSingleThreadExecutor();
1881 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001882 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001883 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001884 final long token = Binder.clearCallingIdentity();
1885 try {
1886 mExecutor.execute(() -> {
1887 mSlot = slot;
1888 callback.onStarted();
1889 });
1890 } finally {
1891 Binder.restoreCallingIdentity(token);
1892 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001893 }
junyulai070f9ff2019-01-16 20:23:34 +08001894
1895 @Override
1896 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001897 final long token = Binder.clearCallingIdentity();
1898 try {
1899 mExecutor.execute(() -> {
1900 mSlot = null;
1901 callback.onStopped();
1902 });
1903 } finally {
1904 Binder.restoreCallingIdentity(token);
1905 }
junyulai070f9ff2019-01-16 20:23:34 +08001906 mExecutor.shutdown();
1907 }
1908
1909 @Override
1910 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001911 final long token = Binder.clearCallingIdentity();
1912 try {
1913 mExecutor.execute(() -> {
1914 mSlot = null;
1915 callback.onError(error);
1916 });
1917 } finally {
1918 Binder.restoreCallingIdentity(token);
1919 }
junyulai070f9ff2019-01-16 20:23:34 +08001920 mExecutor.shutdown();
1921 }
1922
1923 @Override
1924 public void onDataReceived() {
1925 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1926 // this callback when data is received.
1927 }
1928 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001929 }
1930 }
1931
1932 /**
1933 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1934 *
junyulai4c95b082018-12-27 17:25:29 +08001935 * @deprecated Use {@link #createSocketKeepalive} instead.
1936 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001937 * @hide
1938 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001939 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001940 public PacketKeepalive startNattKeepalive(
1941 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1942 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1943 final PacketKeepalive k = new PacketKeepalive(network, callback);
1944 try {
junyulai070f9ff2019-01-16 20:23:34 +08001945 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001946 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1947 } catch (RemoteException e) {
1948 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001949 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001950 }
1951 return k;
1952 }
1953
Chiachang Wang619319a2021-01-15 11:06:21 +08001954 // Construct an invalid fd.
1955 private ParcelFileDescriptor createInvalidFd() {
1956 final int invalidFd = -1;
1957 return ParcelFileDescriptor.adoptFd(invalidFd);
1958 }
1959
The Android Open Source Project28527d22009-03-03 19:31:44 -08001960 /**
junyulai4c95b082018-12-27 17:25:29 +08001961 * Request that keepalives be started on a IPsec NAT-T socket.
1962 *
1963 * @param network The {@link Network} the socket is on.
1964 * @param socket The socket that needs to be kept alive.
1965 * @param source The source address of the {@link UdpEncapsulationSocket}.
1966 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1967 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1968 * must run callback sequentially, otherwise the order of callbacks cannot be
1969 * guaranteed.
1970 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1971 * changes. Must be extended by applications that use this API.
1972 *
junyulai0835a1e2019-01-08 20:04:33 +08001973 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1974 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001975 **/
junyulai7e06ad42019-03-04 22:45:36 +08001976 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001977 @NonNull UdpEncapsulationSocket socket,
1978 @NonNull InetAddress source,
1979 @NonNull InetAddress destination,
1980 @NonNull @CallbackExecutor Executor executor,
1981 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001982 ParcelFileDescriptor dup;
1983 try {
junyulai828dad12019-03-27 11:00:37 +08001984 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1985 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001986 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1987 } catch (IOException ignored) {
1988 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1989 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001990 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001991 }
1992 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1993 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08001994 }
1995
1996 /**
1997 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1998 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1999 *
2000 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002001 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2002 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2003 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002004 * @param source The source address of the {@link UdpEncapsulationSocket}.
2005 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2006 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2007 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2008 * must run callback sequentially, otherwise the order of callbacks cannot be
2009 * guaranteed.
2010 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2011 * changes. Must be extended by applications that use this API.
2012 *
junyulai0835a1e2019-01-08 20:04:33 +08002013 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2014 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002015 * @hide
2016 */
2017 @SystemApi
2018 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002019 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2020 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002021 @NonNull InetAddress source,
2022 @NonNull InetAddress destination,
2023 @NonNull @CallbackExecutor Executor executor,
2024 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002025 ParcelFileDescriptor dup;
2026 try {
junyulai828dad12019-03-27 11:00:37 +08002027 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002028 dup = pfd.dup();
2029 } catch (IOException ignored) {
2030 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2031 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002032 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002033 }
2034 return new NattSocketKeepalive(mService, network, dup,
2035 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002036 }
2037
2038 /**
junyulai0835a1e2019-01-08 20:04:33 +08002039 * Request that keepalives be started on a TCP socket.
2040 * The socket must be established.
2041 *
2042 * @param network The {@link Network} the socket is on.
2043 * @param socket The socket that needs to be kept alive.
2044 * @param executor The executor on which callback will be invoked. This implementation assumes
2045 * the provided {@link Executor} runs the callbacks in sequence with no
2046 * concurrency. Failing this, no guarantee of correctness can be made. It is
2047 * the responsibility of the caller to ensure the executor provides this
2048 * guarantee. A simple way of creating such an executor is with the standard
2049 * tool {@code Executors.newSingleThreadExecutor}.
2050 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2051 * changes. Must be extended by applications that use this API.
2052 *
2053 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2054 * given socket.
2055 * @hide
2056 */
2057 @SystemApi
2058 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002059 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002060 @NonNull Socket socket,
2061 @NonNull Executor executor,
2062 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002063 ParcelFileDescriptor dup;
2064 try {
2065 dup = ParcelFileDescriptor.fromSocket(socket);
2066 } catch (UncheckedIOException ignored) {
2067 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2068 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002069 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002070 }
2071 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002072 }
2073
2074 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002075 * Ensure that a network route exists to deliver traffic to the specified
2076 * host via the specified network interface. An attempt to add a route that
2077 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002078 *
2079 * <p>This method requires the caller to hold either the
2080 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2081 * or the ability to modify system settings as determined by
2082 * {@link android.provider.Settings.System#canWrite}.</p>
2083 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002084 * @param networkType the type of the network over which traffic to the specified
2085 * host is to be routed
2086 * @param hostAddress the IP address of the host to which the route is desired
2087 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002088 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002089 * @deprecated Deprecated in favor of the
2090 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2091 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002092 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002093 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002094 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002095 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002096 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002097 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002098 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002099 }
2100
2101 /**
2102 * Ensure that a network route exists to deliver traffic to the specified
2103 * host via the specified network interface. An attempt to add a route that
2104 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002105 *
2106 * <p>This method requires the caller to hold either the
2107 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2108 * or the ability to modify system settings as determined by
2109 * {@link android.provider.Settings.System#canWrite}.</p>
2110 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002111 * @param networkType the type of the network over which traffic to the specified
2112 * host is to be routed
2113 * @param hostAddress the IP address of the host to which the route is desired
2114 * @return {@code true} on success, {@code false} on failure
2115 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002116 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002117 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002118 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002119 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002120 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002121 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002122 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002123 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002124 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2125 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002126 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002127 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002128 }
2129 }
2130
2131 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002132 * @return the context's attribution tag
2133 */
2134 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2135 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002136 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002137 }
2138
2139 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002140 * Returns the value of the setting for background data usage. If false,
2141 * applications should not use the network if the application is not in the
2142 * foreground. Developers should respect this setting, and check the value
2143 * of this before performing any background data operations.
2144 * <p>
2145 * All applications that have background services that use the network
2146 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002147 * <p>
Scott Main50589142011-10-06 18:32:43 -07002148 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002149 * background data depends on several combined factors, and this method will
2150 * always return {@code true}. Instead, when background data is unavailable,
2151 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002152 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002153 * @return Whether background data usage is allowed.
2154 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002155 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002156 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002157 // assume that background data is allowed; final authority is
2158 // NetworkInfo which may be blocked.
2159 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002160 }
2161
2162 /**
2163 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002164 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002165 * @param allowBackgroundData Whether an application should use data while
2166 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002167 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002168 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2169 * @see #getBackgroundDataSetting()
2170 * @hide
2171 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002172 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002173 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002175 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002176 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002177
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002178 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002179 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002180 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002181 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002182 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002183 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002184 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002185 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2186 if (tm != null) {
2187 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2188 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2189 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2190 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2191 + " retVal=" + retVal);
2192 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002193 }
Wink Saville689f7042014-12-05 11:10:30 -08002194 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002195 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002196 }
2197
The Android Open Source Project28527d22009-03-03 19:31:44 -08002198 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002199 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002200 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002201 */
2202 public interface OnNetworkActiveListener {
2203 /**
2204 * Called on the main thread of the process to report that the current data network
2205 * has become active, and it is now a good time to perform any pending network
2206 * operations. Note that this listener only tells you when the network becomes
2207 * active; if at any other time you want to know whether it is active (and thus okay
2208 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002209 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002210 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002211 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002212 }
2213
2214 private INetworkManagementService getNetworkManagementService() {
2215 synchronized (this) {
2216 if (mNMService != null) {
2217 return mNMService;
2218 }
2219 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2220 mNMService = INetworkManagementService.Stub.asInterface(b);
2221 return mNMService;
2222 }
2223 }
2224
2225 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002226 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002227
2228 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002229 * Start listening to reports when the system's default data network is active, meaning it is
2230 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2231 * to determine the current state of the system's default network after registering the
2232 * listener.
2233 * <p>
2234 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002235 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002236 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002237 *
2238 * @param l The listener to be told when the network is active.
2239 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002240 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002241 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2242 @Override
2243 public void onNetworkActive() throws RemoteException {
2244 l.onNetworkActive();
2245 }
2246 };
2247
2248 try {
2249 getNetworkManagementService().registerNetworkActivityListener(rl);
2250 mNetworkActivityListeners.put(l, rl);
2251 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002252 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002253 }
2254 }
2255
2256 /**
2257 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002258 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002259 *
2260 * @param l Previously registered listener.
2261 */
Chalard Jean158702d2019-01-07 19:26:34 +09002262 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002263 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichibc1104b2017-05-09 15:19:01 +09002264 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002265 try {
2266 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2267 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002268 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002269 }
2270 }
2271
2272 /**
2273 * Return whether the data network is currently active. An active network means that
2274 * it is currently in a high power state for performing data transmission. On some
2275 * types of networks, it may be expensive to move and stay in such a state, so it is
2276 * more power efficient to batch network traffic together when the radio is already in
2277 * this state. This method tells you whether right now is currently a good time to
2278 * initiate network traffic, as the network is already active.
2279 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002280 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002281 try {
2282 return getNetworkManagementService().isNetworkActive();
2283 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002284 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002285 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002286 }
2287
2288 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002289 * {@hide}
2290 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002291 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002292 mContext = Preconditions.checkNotNull(context, "missing context");
2293 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002294 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002295 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002296 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002297
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002298 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002299 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002300 public static ConnectivityManager from(Context context) {
2301 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2302 }
2303
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002304 /** @hide */
2305 public NetworkRequest getDefaultRequest() {
2306 try {
2307 // This is not racy as the default request is final in ConnectivityService.
2308 return mService.getDefaultRequest();
2309 } catch (RemoteException e) {
2310 throw e.rethrowFromSystemServer();
2311 }
2312 }
2313
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09002314 /* TODO: These permissions checks don't belong in client-side code. Move them to
2315 * services.jar, possibly in com.android.server.net. */
2316
2317 /** {@hide} */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002318 public static final void enforceChangePermission(Context context,
2319 String callingPkg, String callingAttributionTag) {
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002320 int uid = Binder.getCallingUid();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002321 checkAndNoteChangeNetworkStateOperation(context, uid, callingPkg,
2322 callingAttributionTag, true /* throwException */);
2323 }
2324
2325 /**
2326 * Check if the package is a allowed to change the network state. This also accounts that such
2327 * an access happened.
2328 *
2329 * @return {@code true} iff the package is allowed to change the network state.
2330 */
2331 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2332 private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context,
2333 int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag,
2334 boolean throwException) {
2335 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, callingPackage,
2336 throwException);
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002337 }
2338
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002339 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002340 * Check if the package is a allowed to write settings. This also accounts that such an access
2341 * happened.
2342 *
2343 * @return {@code true} iff the package is allowed to write settings.
2344 */
2345 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2346 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2347 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2348 boolean throwException) {
2349 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2350 throwException);
2351 }
2352
2353 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002354 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2355 * situations where a Context pointer is unavailable.
2356 * @hide
2357 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002358 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002359 static ConnectivityManager getInstanceOrNull() {
2360 return sInstance;
2361 }
2362
2363 /**
2364 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2365 * situations where a Context pointer is unavailable.
2366 * @hide
2367 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002368 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002369 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002370 private static ConnectivityManager getInstance() {
2371 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002372 throw new IllegalStateException("No ConnectivityManager yet constructed");
2373 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002374 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002375 }
2376
2377 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002378 * Get the set of tetherable, available interfaces. This list is limited by
2379 * device configuration and current interface existence.
2380 *
2381 * @return an array of 0 or more Strings of tetherable interface names.
2382 *
markchien6ae63e52020-01-21 13:11:06 +08002383 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002384 * {@hide}
2385 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002386 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002387 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002388 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002389 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002390 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002391 }
2392
2393 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002394 * Get the set of tethered interfaces.
2395 *
2396 * @return an array of 0 or more String of currently tethered interface names.
2397 *
markchien6ae63e52020-01-21 13:11:06 +08002398 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002399 * {@hide}
2400 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002401 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002402 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002403 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002404 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002405 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002406 }
2407
2408 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002409 * Get the set of interface names which attempted to tether but
2410 * failed. Re-attempting to tether may cause them to reset to the Tethered
2411 * state. Alternatively, causing the interface to be destroyed and recreated
2412 * may cause them to reset to the available state.
2413 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2414 * information on the cause of the errors.
2415 *
2416 * @return an array of 0 or more String indicating the interface names
2417 * which failed to tether.
2418 *
markchien6ae63e52020-01-21 13:11:06 +08002419 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002420 * {@hide}
2421 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002422 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002423 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002424 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002425 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002426 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002427 }
2428
2429 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002430 * Get the set of tethered dhcp ranges.
2431 *
markchien2e6ba522020-02-14 11:55:48 +08002432 * @deprecated This method is not supported.
2433 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002434 * {@hide}
2435 */
paulhu8e96a752019-08-12 16:25:11 +08002436 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002437 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002438 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002439 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002440 }
2441
2442 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002443 * Attempt to tether the named interface. This will setup a dhcp server
2444 * on the interface, forward and NAT IP packets and forward DNS requests
2445 * to the best active upstream network interface. Note that if no upstream
2446 * IP network interface is available, dhcp will still run and traffic will be
2447 * allowed between the tethered devices and this device, though upstream net
2448 * access will of course fail until an upstream network interface becomes
2449 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002450 *
2451 * <p>This method requires the caller to hold either the
2452 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2453 * or the ability to modify system settings as determined by
2454 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002455 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002456 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2457 * and WifiStateMachine which need direct access. All other clients should use
2458 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2459 * logic.</p>
2460 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002461 * @param iface the interface name to tether.
2462 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002463 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002464 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002465 * {@hide}
2466 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002467 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002468 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002469 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002470 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002471 }
2472
2473 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002474 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002475 *
2476 * <p>This method requires the caller to hold either the
2477 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2478 * or the ability to modify system settings as determined by
2479 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002480 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002481 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2482 * and WifiStateMachine which need direct access. All other clients should use
2483 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2484 * logic.</p>
2485 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002486 * @param iface the interface name to untether.
2487 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2488 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002489 * {@hide}
2490 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002491 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002492 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002493 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002494 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002495 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002496
2497 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002498 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002499 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002500 * due to device configuration.
2501 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002502 * <p>If this app does not have permission to use this API, it will always
2503 * return false rather than throw an exception.</p>
2504 *
2505 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2506 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2507 *
2508 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2509 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2510 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002511 * @return a boolean - {@code true} indicating Tethering is supported.
2512 *
markchien6ae63e52020-01-21 13:11:06 +08002513 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002514 * {@hide}
2515 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002516 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002517 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2518 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002519 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002520 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002521 }
2522
2523 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002524 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002525 *
2526 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002527 * @hide
2528 */
2529 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002530 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002531 public static abstract class OnStartTetheringCallback {
2532 /**
2533 * Called when tethering has been successfully started.
2534 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002535 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002536
2537 /**
2538 * Called when starting tethering failed.
2539 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002540 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002541 }
2542
2543 /**
2544 * Convenient overload for
2545 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2546 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002547 *
2548 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002549 * @hide
2550 */
2551 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002552 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002553 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002554 public void startTethering(int type, boolean showProvisioningUi,
2555 final OnStartTetheringCallback callback) {
2556 startTethering(type, showProvisioningUi, callback, null);
2557 }
2558
2559 /**
2560 * Runs tether provisioning for the given type if needed and then starts tethering if
2561 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2562 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2563 * schedules tether provisioning re-checks if appropriate.
2564 *
2565 * @param type The type of tethering to start. Must be one of
2566 * {@link ConnectivityManager.TETHERING_WIFI},
2567 * {@link ConnectivityManager.TETHERING_USB}, or
2568 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2569 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2570 * is one. This should be true the first time this function is called and also any time
2571 * the user can see this UI. It gives users information from their carrier about the
2572 * check failing and how they can sign up for tethering if possible.
2573 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2574 * of the result of trying to tether.
2575 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002576 *
2577 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002578 * @hide
2579 */
2580 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002581 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002582 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002583 public void startTethering(int type, boolean showProvisioningUi,
2584 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002585 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002586
markchien91c78e52020-01-20 19:31:56 +08002587 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002588 @Override
markchien91c78e52020-01-20 19:31:56 +08002589 public void execute(Runnable command) {
2590 if (handler == null) {
2591 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002592 } else {
markchien91c78e52020-01-20 19:31:56 +08002593 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002594 }
2595 }
2596 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002597
markchien91c78e52020-01-20 19:31:56 +08002598 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2599 @Override
2600 public void onTetheringStarted() {
2601 callback.onTetheringStarted();
2602 }
2603
2604 @Override
markchienf47d8342020-03-19 13:37:43 +08002605 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002606 callback.onTetheringFailed();
2607 }
2608 };
2609
2610 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002611 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002612
Amos Bianchia9b415a2020-03-04 11:07:38 -08002613 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002614 }
2615
2616 /**
2617 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2618 * applicable.
2619 *
2620 * @param type The type of tethering to stop. Must be one of
2621 * {@link ConnectivityManager.TETHERING_WIFI},
2622 * {@link ConnectivityManager.TETHERING_USB}, or
2623 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002624 *
2625 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002626 * @hide
2627 */
2628 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002629 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002630 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002631 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002632 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002633 }
2634
2635 /**
markchien4ef53e82019-02-27 14:56:11 +08002636 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2637 * upstream status.
2638 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002639 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002640 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002641 */
2642 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002643 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002644 public abstract static class OnTetheringEventCallback {
2645
2646 /**
2647 * Called when tethering upstream changed. This can be called multiple times and can be
2648 * called any time.
2649 *
2650 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2651 * have any upstream.
2652 */
2653 public void onUpstreamChanged(@Nullable Network network) {}
2654 }
2655
markchien6ae63e52020-01-21 13:11:06 +08002656 @GuardedBy("mTetheringEventCallbacks")
2657 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2658 mTetheringEventCallbacks = new ArrayMap<>();
2659
markchien4ef53e82019-02-27 14:56:11 +08002660 /**
2661 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002662 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002663 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2664 * with a null argument. The same callback object cannot be registered twice.
2665 *
2666 * @param executor the executor on which callback will be invoked.
2667 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002668 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002669 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002670 * @hide
2671 */
2672 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002673 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002674 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2675 public void registerTetheringEventCallback(
2676 @NonNull @CallbackExecutor Executor executor,
2677 @NonNull final OnTetheringEventCallback callback) {
2678 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2679
markchien6ae63e52020-01-21 13:11:06 +08002680 final TetheringEventCallback tetherCallback =
2681 new TetheringEventCallback() {
2682 @Override
2683 public void onUpstreamChanged(@Nullable Network network) {
2684 callback.onUpstreamChanged(network);
2685 }
2686 };
2687
2688 synchronized (mTetheringEventCallbacks) {
2689 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002690 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002691 }
markchien4ef53e82019-02-27 14:56:11 +08002692 }
2693
2694 /**
2695 * Remove tethering event callback previously registered with
2696 * {@link #registerTetheringEventCallback}.
2697 *
2698 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002699 *
2700 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002701 * @hide
2702 */
2703 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002704 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002705 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2706 public void unregisterTetheringEventCallback(
2707 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002708 Objects.requireNonNull(callback, "The callback must be non-null");
2709 synchronized (mTetheringEventCallbacks) {
2710 final TetheringEventCallback tetherCallback =
2711 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002712 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002713 }
markchien4ef53e82019-02-27 14:56:11 +08002714 }
2715
2716
2717 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002718 * Get the list of regular expressions that define any tetherable
2719 * USB network interfaces. If USB tethering is not supported by the
2720 * device, this list should be empty.
2721 *
2722 * @return an array of 0 or more regular expression Strings defining
2723 * what interfaces are considered tetherable usb interfaces.
2724 *
markchien6ae63e52020-01-21 13:11:06 +08002725 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002726 * {@hide}
2727 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002728 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002729 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002730 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002731 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002732 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002733 }
2734
2735 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002736 * Get the list of regular expressions that define any tetherable
2737 * Wifi network interfaces. If Wifi tethering is not supported by the
2738 * device, this list should be empty.
2739 *
2740 * @return an array of 0 or more regular expression Strings defining
2741 * what interfaces are considered tetherable wifi interfaces.
2742 *
markchien6ae63e52020-01-21 13:11:06 +08002743 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002744 * {@hide}
2745 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002746 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002747 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002748 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002749 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002750 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002751 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002752
Danica Chang96567052010-08-11 14:54:43 -07002753 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002754 * Get the list of regular expressions that define any tetherable
2755 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2756 * device, this list should be empty.
2757 *
2758 * @return an array of 0 or more regular expression Strings defining
2759 * what interfaces are considered tetherable bluetooth interfaces.
2760 *
markchien6ae63e52020-01-21 13:11:06 +08002761 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2762 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002763 * {@hide}
2764 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002765 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002766 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002767 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002768 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002769 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002770 }
2771
Mike Lockwooded4a1742011-07-19 13:04:47 -07002772 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002773 * Attempt to both alter the mode of USB and Tethering of USB. A
2774 * utility method to deal with some of the complexity of USB - will
2775 * attempt to switch to Rndis and subsequently tether the resulting
2776 * interface on {@code true} or turn off tethering and switch off
2777 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002778 *
2779 * <p>This method requires the caller to hold either the
2780 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2781 * or the ability to modify system settings as determined by
2782 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002783 *
2784 * @param enable a boolean - {@code true} to enable tethering
2785 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002786 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002787 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002788 * {@hide}
2789 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002790 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002791 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002792 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002793 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002794 }
2795
markchien6ae63e52020-01-21 13:11:06 +08002796 /**
2797 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2798 * {@hide}
2799 */
markchien0f45bb92019-01-16 17:44:13 +08002800 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002801 @Deprecated
2802 public static final int TETHER_ERROR_NO_ERROR = TetheringManager.TETHER_ERROR_NO_ERROR;
2803 /**
2804 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2805 * {@hide}
2806 */
2807 @Deprecated
2808 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2809 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2810 /**
2811 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2812 * {@hide}
2813 */
2814 @Deprecated
2815 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2816 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2817 /**
2818 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2819 * {@hide}
2820 */
2821 @Deprecated
2822 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2823 /**
2824 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2825 * {@hide}
2826 */
2827 @Deprecated
2828 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2829 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2830 /**
markchienf47d8342020-03-19 13:37:43 +08002831 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002832 * {@hide}
2833 */
2834 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002835 public static final int TETHER_ERROR_MASTER_ERROR =
2836 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002837 /**
2838 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2839 * {@hide}
2840 */
2841 @Deprecated
2842 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2843 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2844 /**
2845 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2846 * {@hide}
2847 */
2848 @Deprecated
2849 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2850 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2851 /**
markchienf47d8342020-03-19 13:37:43 +08002852 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002853 * {@hide}
2854 */
2855 @Deprecated
2856 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002857 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002858 /**
markchienf47d8342020-03-19 13:37:43 +08002859 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002860 * {@hide}
2861 */
2862 @Deprecated
2863 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002864 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002865 /**
2866 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2867 * {@hide}
2868 */
2869 @Deprecated
2870 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2871 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2872 /**
markchienf47d8342020-03-19 13:37:43 +08002873 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002874 * {@hide}
2875 */
markchien0f45bb92019-01-16 17:44:13 +08002876 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002877 @Deprecated
2878 public static final int TETHER_ERROR_PROVISION_FAILED =
markchienf47d8342020-03-19 13:37:43 +08002879 TetheringManager.TETHER_ERROR_PROVISIONING_FAILED;
markchien6ae63e52020-01-21 13:11:06 +08002880 /**
2881 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2882 * {@hide}
2883 */
2884 @Deprecated
2885 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2886 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2887 /**
2888 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2889 * {@hide}
2890 */
markchien0f45bb92019-01-16 17:44:13 +08002891 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002892 @Deprecated
2893 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN =
2894 TetheringManager.TETHER_ERROR_ENTITLEMENT_UNKNOWN;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002895
2896 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002897 * Get a more detailed error code after a Tethering or Untethering
2898 * request asynchronously failed.
2899 *
2900 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002901 * @return error The error code of the last error tethering or untethering the named
2902 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002903 *
markchien6ae63e52020-01-21 13:11:06 +08002904 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002905 * {@hide}
2906 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002907 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002908 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002909 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002910 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002911 int error = mTetheringManager.getLastTetherError(iface);
2912 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2913 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2914 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2915 // instead.
2916 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2917 }
2918 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002919 }
2920
markchienbf5ab012019-03-06 16:25:00 +08002921 /** @hide */
2922 @Retention(RetentionPolicy.SOURCE)
2923 @IntDef(value = {
2924 TETHER_ERROR_NO_ERROR,
2925 TETHER_ERROR_PROVISION_FAILED,
2926 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2927 })
2928 public @interface EntitlementResultCode {
2929 }
2930
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002931 /**
markchienbf5ab012019-03-06 16:25:00 +08002932 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002933 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002934 *
2935 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002936 * @hide
2937 */
2938 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002939 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002940 public interface OnTetheringEntitlementResultListener {
2941 /**
2942 * Called to notify entitlement result.
2943 *
2944 * @param resultCode an int value of entitlement result. It may be one of
2945 * {@link #TETHER_ERROR_NO_ERROR},
2946 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2947 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2948 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002949 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002950 }
2951
2952 /**
markchien0f45bb92019-01-16 17:44:13 +08002953 * Get the last value of the entitlement check on this downstream. If the cached value is
2954 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2955 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2956 * guaranteed that the UI-based entitlement check will complete in any specific time period
2957 * and may in fact never complete. Any successful entitlement check the platform performs for
2958 * any reason will update the cached value.
2959 *
2960 * @param type the downstream type of tethering. Must be one of
2961 * {@link #TETHERING_WIFI},
2962 * {@link #TETHERING_USB}, or
2963 * {@link #TETHERING_BLUETOOTH}.
2964 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002965 * @param executor the executor on which callback will be invoked.
2966 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2967 * notify the caller of the result of entitlement check. The listener may be called zero
2968 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002969 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002970 * {@hide}
2971 */
2972 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002973 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002974 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002975 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2976 @NonNull @CallbackExecutor Executor executor,
2977 @NonNull final OnTetheringEntitlementResultListener listener) {
2978 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2979 ResultReceiver wrappedListener = new ResultReceiver(null) {
2980 @Override
2981 protected void onReceiveResult(int resultCode, Bundle resultData) {
2982 Binder.withCleanCallingIdentity(() ->
2983 executor.execute(() -> {
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002984 listener.onTetheringEntitlementResult(resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002985 }));
2986 }
2987 };
2988
Amos Bianchia9b415a2020-03-04 11:07:38 -08002989 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002990 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002991 }
2992
2993 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002994 * Report network connectivity status. This is currently used only
2995 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002996 * <p>This method requires the caller to hold the permission
2997 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002998 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002999 * @param networkType The type of network you want to report on
3000 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003001 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003002 * {@hide}
3003 */
3004 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003005 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003006 try {
3007 mService.reportInetCondition(networkType, percentage);
3008 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003009 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003010 }
3011 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003012
3013 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003014 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003015 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003016 * the framework to re-evaluate network connectivity and/or switch to another
3017 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003018 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003019 * @param network The {@link Network} the application was attempting to use
3020 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003021 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3022 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003023 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003024 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003025 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003026 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003027 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003028 // One of these will be ignored because it matches system's current state.
3029 // The other will trigger the necessary reevaluation.
3030 mService.reportNetworkConnectivity(network, true);
3031 mService.reportNetworkConnectivity(network, false);
3032 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003033 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003034 }
3035 }
3036
3037 /**
3038 * Report to the framework whether a network has working connectivity.
3039 * This provides a hint to the system that a particular network is providing
3040 * working connectivity or not. In response the framework may re-evaluate
3041 * the network's connectivity and might take further action thereafter.
3042 *
3043 * @param network The {@link Network} the application was attempting to use
3044 * or {@code null} to indicate the current default network.
3045 * @param hasConnectivity {@code true} if the application was able to successfully access the
3046 * Internet using {@code network} or {@code false} if not.
3047 */
Chalard Jean158702d2019-01-07 19:26:34 +09003048 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003049 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003050 try {
3051 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003052 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003053 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003054 }
3055 }
3056
3057 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003058 * Set a network-independent global http proxy. This is not normally what you want
3059 * for typical HTTP proxies - they are general network dependent. However if you're
3060 * doing something unusual like general internal filtering this may be useful. On
3061 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003062 *
3063 * @param p A {@link ProxyInfo} object defining the new global
3064 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003065 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003066 */
paulhu8e96a752019-08-12 16:25:11 +08003067 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04003068 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003069 try {
3070 mService.setGlobalProxy(p);
3071 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003072 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003073 }
3074 }
3075
3076 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003077 * Retrieve any network-independent global HTTP proxy.
3078 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003079 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003080 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003081 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003082 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003083 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003084 try {
3085 return mService.getGlobalProxy();
3086 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003087 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003088 }
3089 }
3090
3091 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003092 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3093 * network-specific HTTP proxy. If {@code network} is null, the
3094 * network-specific proxy returned is the proxy of the default active
3095 * network.
3096 *
3097 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3098 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3099 * or when {@code network} is {@code null},
3100 * the {@code ProxyInfo} for the default active network. Returns
3101 * {@code null} when no proxy applies or the caller doesn't have
3102 * permission to use {@code network}.
3103 * @hide
3104 */
3105 public ProxyInfo getProxyForNetwork(Network network) {
3106 try {
3107 return mService.getProxyForNetwork(network);
3108 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003109 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003110 }
3111 }
3112
3113 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003114 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3115 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003116 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003117 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003118 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003119 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003120 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003121 */
Chalard Jean158702d2019-01-07 19:26:34 +09003122 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003123 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003124 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003125 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003126
3127 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003128 * Returns true if the hardware supports the given network type
3129 * else it returns false. This doesn't indicate we have coverage
3130 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003131 * hardware supports it. For example a GSM phone without a SIM
3132 * should still return {@code true} for mobile data, but a wifi only
3133 * tablet would return {@code false}.
3134 *
3135 * @param networkType The network type we'd like to check
3136 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003137 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003138 * @hide
3139 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003140 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003141 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003142 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003143 public boolean isNetworkSupported(int networkType) {
3144 try {
3145 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003146 } catch (RemoteException e) {
3147 throw e.rethrowFromSystemServer();
3148 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003149 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003150
3151 /**
3152 * Returns if the currently active data network is metered. A network is
3153 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003154 * that connection due to monetary costs, data limitations or
3155 * battery/performance issues. You should check this before doing large
3156 * data transfers, and warn the user or delay the operation until another
3157 * network is available.
3158 *
3159 * @return {@code true} if large transfers should be avoided, otherwise
3160 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003161 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003162 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003163 public boolean isActiveNetworkMetered() {
3164 try {
3165 return mService.isActiveNetworkMetered();
3166 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003167 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003168 }
3169 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003170
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003171 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09003172 * Calls VpnManager#updateLockdownVpn.
3173 * @deprecated TODO: remove when callers have migrated to VpnManager.
3174 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003175 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09003176 @Deprecated
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003177 public boolean updateLockdownVpn() {
Lorenzo Colitticd675292021-02-04 17:32:07 +09003178 return getVpnManager().updateLockdownVpn();
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003179 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07003180
3181 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003182 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003183 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003184 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003185 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003186 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003187 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003188 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003189 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003190 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003191 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003192 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003193 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003194 }
3195 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003196
3197 /**
3198 * Set the value for enabling/disabling airplane mode
3199 *
3200 * @param enable whether to enable airplane mode or not
3201 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003202 * @hide
3203 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003204 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003205 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003206 android.Manifest.permission.NETWORK_SETTINGS,
3207 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3208 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003209 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003210 public void setAirplaneMode(boolean enable) {
3211 try {
3212 mService.setAirplaneMode(enable);
3213 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003214 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003215 }
3216 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003217
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003218 /**
3219 * Registers the specified {@link NetworkProvider}.
3220 * Each listener must only be registered once. The listener can be unregistered with
3221 * {@link #unregisterNetworkProvider}.
3222 *
3223 * @param provider the provider to register
3224 * @return the ID of the provider. This ID must be used by the provider when registering
3225 * {@link android.net.NetworkAgent}s.
3226 * @hide
3227 */
3228 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003229 @RequiresPermission(anyOf = {
3230 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3231 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003232 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3233 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003234 throw new IllegalStateException("NetworkProviders can only be registered once");
3235 }
3236
3237 try {
3238 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3239 provider.getName());
3240 provider.setProviderId(providerId);
3241 } catch (RemoteException e) {
3242 throw e.rethrowFromSystemServer();
3243 }
3244 return provider.getProviderId();
3245 }
3246
3247 /**
3248 * Unregisters the specified NetworkProvider.
3249 *
3250 * @param provider the provider to unregister
3251 * @hide
3252 */
3253 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003254 @RequiresPermission(anyOf = {
3255 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3256 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003257 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3258 try {
3259 mService.unregisterNetworkProvider(provider.getMessenger());
3260 } catch (RemoteException e) {
3261 throw e.rethrowFromSystemServer();
3262 }
3263 provider.setProviderId(NetworkProvider.ID_NONE);
3264 }
3265
3266
3267 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003268 @RequiresPermission(anyOf = {
3269 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3270 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003271 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3272 try {
3273 mService.declareNetworkRequestUnfulfillable(request);
3274 } catch (RemoteException e) {
3275 throw e.rethrowFromSystemServer();
3276 }
3277 }
3278
Chalard Jean29d06db2018-05-02 21:14:54 +09003279 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3280 // of dependent changes that would conflict throughout the automerger graph. Having this
3281 // temporarily helps with the process of going through with all these dependent changes across
3282 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003283 /**
3284 * @hide
3285 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003286 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003287 */
paulhub6ba8e82020-03-04 09:43:41 +08003288 @RequiresPermission(anyOf = {
3289 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3290 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003291 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003292 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003293 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003294 }
3295
3296 /**
3297 * @hide
3298 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003299 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003300 */
paulhub6ba8e82020-03-04 09:43:41 +08003301 @RequiresPermission(anyOf = {
3302 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3303 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003304 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003305 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003306 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003307 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003308 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003309 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003310 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003311 }
3312
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003313 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003314 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3315 * changes. Should be extended by applications wanting notifications.
3316 *
3317 * A {@code NetworkCallback} is registered by calling
3318 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3319 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003320 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003321 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3322 * A {@code NetworkCallback} should be registered at most once at any time.
3323 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003324 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003325 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003326 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003327 * Called when the framework connects to a new network to evaluate whether it satisfies this
3328 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3329 * callback. There is no guarantee that this new network will satisfy any requests, or that
3330 * the network will stay connected for longer than the time necessary to evaluate it.
3331 * <p>
3332 * Most applications <b>should not</b> act on this callback, and should instead use
3333 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3334 * the framework in properly evaluating the network &mdash; for example, an application that
3335 * can automatically log in to a captive portal without user intervention.
3336 *
3337 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003338 *
3339 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003340 */
paulhu1a407652019-03-22 16:35:06 +08003341 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003342
3343 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003344 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003345 * This callback may be called more than once if the {@link Network} that is
3346 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003347 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003348 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003349 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3350 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003351 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003352 * @hide
3353 */
paulhu1a407652019-03-22 16:35:06 +08003354 public void onAvailable(@NonNull Network network,
3355 @NonNull NetworkCapabilities networkCapabilities,
3356 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003357 // Internally only this method is called when a new network is available, and
3358 // it calls the callback in the same way and order that older versions used
3359 // to call so as not to change the behavior.
3360 onAvailable(network);
3361 if (!networkCapabilities.hasCapability(
3362 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3363 onNetworkSuspended(network);
3364 }
3365 onCapabilitiesChanged(network, networkCapabilities);
3366 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003367 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003368 }
3369
3370 /**
3371 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003372 *
3373 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3374 * be available at the same time, and onAvailable will be called for each of these as they
3375 * appear.
3376 *
3377 * <p>For callbacks registered with {@link #requestNetwork} and
3378 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3379 * is the new best network for this request and is now tracked by this callback ; this
3380 * callback will no longer receive method calls about other networks that may have been
3381 * passed to this method previously. The previously-best network may have disconnected, or
3382 * it may still be around and the newly-best network may simply be better.
3383 *
3384 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3385 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3386 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3387 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3388 *
3389 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3390 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3391 * this callback as this is prone to race conditions (there is no guarantee the objects
3392 * returned by these methods will be current). Instead, wait for a call to
3393 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3394 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3395 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003396 *
3397 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003398 */
paulhu1a407652019-03-22 16:35:06 +08003399 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003400
3401 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003402 * Called when the network is about to be lost, typically because there are no outstanding
3403 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3404 * with the new replacement network for graceful handover. This method is not guaranteed
3405 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3406 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003407 *
Chalard Jean01378b62019-08-30 16:27:28 +09003408 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3409 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3410 * this callback as this is prone to race conditions ; calling these methods while in a
3411 * callback may return an outdated or even a null object.
3412 *
3413 * @param network The {@link Network} that is about to be lost.
3414 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3415 * connected for graceful handover; note that the network may still
3416 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003417 */
paulhu1a407652019-03-22 16:35:06 +08003418 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003419
3420 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003421 * Called when a network disconnects or otherwise no longer satisfies this request or
3422 * callback.
3423 *
3424 * <p>If the callback was registered with requestNetwork() or
3425 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3426 * returned by onAvailable() when that network is lost and no other network satisfies
3427 * the criteria of the request.
3428 *
3429 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3430 * each network which no longer satisfies the criteria of the callback.
3431 *
3432 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3433 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3434 * this callback as this is prone to race conditions ; calling these methods while in a
3435 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003436 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003437 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003438 */
paulhu1a407652019-03-22 16:35:06 +08003439 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003440
3441 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003442 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003443 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3444 * requested network request cannot be fulfilled (whether or not a timeout was
3445 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003446 * {@link NetworkRequest} will have already been removed and released, as if
3447 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003448 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003449 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003450
3451 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003452 * Called when the network corresponding to this request changes capabilities but still
3453 * satisfies the requested criteria.
3454 *
3455 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3456 * to be called immediately after {@link #onAvailable}.
3457 *
3458 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3459 * ConnectivityManager methods in this callback as this is prone to race conditions :
3460 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003461 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003462 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003463 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3464 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003465 */
paulhu1a407652019-03-22 16:35:06 +08003466 public void onCapabilitiesChanged(@NonNull Network network,
3467 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003468
3469 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003470 * Called when the network corresponding to this request changes {@link LinkProperties}.
3471 *
3472 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3473 * to be called immediately after {@link #onAvailable}.
3474 *
3475 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3476 * ConnectivityManager methods in this callback as this is prone to race conditions :
3477 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003478 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003479 * @param network The {@link Network} whose link properties have changed.
3480 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003481 */
paulhu1a407652019-03-22 16:35:06 +08003482 public void onLinkPropertiesChanged(@NonNull Network network,
3483 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003484
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003485 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003486 * Called when the network the framework connected to for this request suspends data
3487 * transmission temporarily.
3488 *
3489 * <p>This generally means that while the TCP connections are still live temporarily
3490 * network data fails to transfer. To give a specific example, this is used on cellular
3491 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3492 * means read operations on sockets on this network will block once the buffers are
3493 * drained, and write operations will block once the buffers are full.
3494 *
3495 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3496 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3497 * this callback as this is prone to race conditions (there is no guarantee the objects
3498 * returned by these methods will be current).
3499 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003500 * @hide
3501 */
paulhu1a407652019-03-22 16:35:06 +08003502 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003503
3504 /**
3505 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003506 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3507 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003508
3509 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3510 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3511 * this callback as this is prone to race conditions : calling these methods while in a
3512 * callback may return an outdated or even a null object.
3513 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003514 * @hide
3515 */
paulhu1a407652019-03-22 16:35:06 +08003516 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003517
junyulaif2c67e42018-08-07 19:50:45 +08003518 /**
3519 * Called when access to the specified network is blocked or unblocked.
3520 *
Chalard Jean01378b62019-08-30 16:27:28 +09003521 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3522 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3523 * this callback as this is prone to race conditions : calling these methods while in a
3524 * callback may return an outdated or even a null object.
3525 *
junyulaif2c67e42018-08-07 19:50:45 +08003526 * @param network The {@link Network} whose blocked status has changed.
3527 * @param blocked The blocked status of this {@link Network}.
3528 */
junyulai7e06ad42019-03-04 22:45:36 +08003529 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003530
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003531 private NetworkRequest networkRequest;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003532 }
3533
Hugo Benichia590ab82017-05-11 13:16:17 +09003534 /**
3535 * Constant error codes used by ConnectivityService to communicate about failures and errors
3536 * across a Binder boundary.
3537 * @hide
3538 */
3539 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003540 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003541 }
3542
3543 /** @hide */
3544 public static class TooManyRequestsException extends RuntimeException {}
3545
3546 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3547 switch (e.errorCode) {
3548 case Errors.TOO_MANY_REQUESTS:
3549 return new TooManyRequestsException();
3550 default:
3551 Log.w(TAG, "Unknown service error code " + e.errorCode);
3552 return new RuntimeException(e);
3553 }
3554 }
3555
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003556 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003557 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003558 public static final int CALLBACK_PRECHECK = BASE + 1;
3559 /** @hide */
3560 public static final int CALLBACK_AVAILABLE = BASE + 2;
3561 /** @hide arg1 = TTL */
3562 public static final int CALLBACK_LOSING = BASE + 3;
3563 /** @hide */
3564 public static final int CALLBACK_LOST = BASE + 4;
3565 /** @hide */
3566 public static final int CALLBACK_UNAVAIL = BASE + 5;
3567 /** @hide */
3568 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3569 /** @hide */
3570 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003571 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003572 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003573 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003574 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003575 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003576 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003577 /** @hide */
3578 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003579
Erik Kline155a59a2015-11-25 12:49:38 +09003580 /** @hide */
3581 public static String getCallbackName(int whichCallback) {
3582 switch (whichCallback) {
3583 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3584 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3585 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3586 case CALLBACK_LOST: return "CALLBACK_LOST";
3587 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3588 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3589 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003590 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3591 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3592 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003593 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003594 default:
3595 return Integer.toString(whichCallback);
3596 }
3597 }
3598
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003599 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003600 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003601 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003602
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003603 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003604 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003605 }
3606
Hugo Benichifd44e912017-02-02 17:02:36 +09003607 CallbackHandler(Handler handler) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003608 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003609 }
3610
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003611 @Override
3612 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003613 if (message.what == EXPIRE_LEGACY_REQUEST) {
3614 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3615 return;
3616 }
3617
3618 final NetworkRequest request = getObject(message, NetworkRequest.class);
3619 final Network network = getObject(message, Network.class);
3620 final NetworkCallback callback;
3621 synchronized (sCallbacks) {
3622 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003623 if (callback == null) {
3624 Log.w(TAG,
3625 "callback not found for " + getCallbackName(message.what) + " message");
3626 return;
3627 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003628 if (message.what == CALLBACK_UNAVAIL) {
3629 sCallbacks.remove(request);
3630 callback.networkRequest = ALREADY_UNREGISTERED;
3631 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003632 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003633 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003634 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003635 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003636
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003637 switch (message.what) {
3638 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003639 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003640 break;
3641 }
3642 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003643 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3644 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003645 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003646 break;
3647 }
3648 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003649 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003650 break;
3651 }
3652 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003653 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003654 break;
3655 }
3656 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003657 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003658 break;
3659 }
3660 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003661 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3662 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003663 break;
3664 }
3665 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003666 LinkProperties lp = getObject(message, LinkProperties.class);
3667 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003668 break;
3669 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003670 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003671 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003672 break;
3673 }
3674 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003675 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003676 break;
3677 }
junyulaif2c67e42018-08-07 19:50:45 +08003678 case CALLBACK_BLK_CHANGED: {
3679 boolean blocked = message.arg1 != 0;
3680 callback.onBlockedStatusChanged(network, blocked);
3681 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003682 }
3683 }
3684
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003685 private <T> T getObject(Message msg, Class<T> c) {
3686 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003687 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003688 }
3689
Hugo Benichifd44e912017-02-02 17:02:36 +09003690 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003691 synchronized (sCallbacks) {
3692 if (sCallbackHandler == null) {
3693 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003694 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003695 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003696 }
3697 }
3698
Hugo Benichibc4ac972017-02-03 14:18:44 +09003699 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3700 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003701
Hugo Benichibc4ac972017-02-03 14:18:44 +09003702 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003703 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003704 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003705 checkCallbackNotNull(callback);
junyulaiad010792021-01-11 16:53:38 +08003706 Preconditions.checkArgument(
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09003707 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3708 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003709 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003710 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003711 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003712 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003713 if (callback.networkRequest != null
3714 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003715 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3716 // and requests (http://b/20701525).
3717 Log.e(TAG, "NetworkCallback was already registered");
3718 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003719 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003720 Binder binder = new Binder();
junyulaiad010792021-01-11 16:53:38 +08003721 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003722 request = mService.listenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003723 need, messenger, binder, callingPackageName,
3724 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003725 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003726 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003727 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3728 callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003729 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003730 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003731 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003732 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003733 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003734 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003735 } catch (RemoteException e) {
3736 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003737 } catch (ServiceSpecificException e) {
3738 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003739 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003740 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003741 }
3742
3743 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003744 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003745 *
markchienfac84a22020-03-18 21:16:15 +08003746 * This API is only for use in internal system code that requests networks with legacy type and
3747 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003748 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003749 *
markchiend6eeffd2020-01-14 00:55:21 +08003750 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003751 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3752 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3753 * be a positive value (i.e. >0).
3754 * @param legacyType to specify the network type(#TYPE_*).
3755 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003756 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3757 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003758 *
3759 * @hide
3760 */
markchiend6eeffd2020-01-14 00:55:21 +08003761 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003762 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003763 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003764 int timeoutMs, int legacyType, @NonNull Handler handler,
3765 @NonNull NetworkCallback networkCallback) {
3766 if (legacyType == TYPE_NONE) {
3767 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3768 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003769 CallbackHandler cbHandler = new CallbackHandler(handler);
3770 NetworkCapabilities nc = request.networkCapabilities;
3771 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003772 }
3773
3774 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003775 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003776 *
Chalard Jean01378b62019-08-30 16:27:28 +09003777 * <p>This method will attempt to find the best network that matches the passed
3778 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3779 * criteria. The platform will evaluate which network is the best at its own discretion.
3780 * Throughput, latency, cost per byte, policy, user preference and other considerations
3781 * may be factored in the decision of what is considered the best network.
3782 *
3783 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3784 * matching this request, while always attempting to match the request to a better network if
3785 * possible. If a better match is found, the platform will switch this request to the now-best
3786 * network and inform the app of the newly best network by invoking
3787 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3788 * will not try to maintain any other network than the best one currently matching the request:
3789 * a network not matching any network request may be disconnected at any time.
3790 *
3791 * <p>For example, an application could use this method to obtain a connected cellular network
3792 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3793 * radio to consume additional power. Or, an application could inform the system that it wants
3794 * a network supporting sending MMSes and have the system let it know about the currently best
3795 * MMS-supporting network through the provided {@link NetworkCallback}.
3796 *
3797 * <p>The status of the request can be followed by listening to the various callbacks described
3798 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3799 * used to direct traffic to the network (although accessing some networks may be subject to
3800 * holding specific permissions). Callers will learn about the specific characteristics of the
3801 * network through
3802 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3803 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3804 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3805 * matching the request at any given time; therefore when a better network matching the request
3806 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3807 * with the new network after which no further updates are given about the previously-best
3808 * network, unless it becomes the best again at some later time. All callbacks are invoked
3809 * in order on the same thread, which by default is a thread created by the framework running
3810 * in the app.
3811 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3812 * callbacks are invoked.
3813 *
3814 * <p>This{@link NetworkRequest} will live until released via
3815 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3816 * which point the system may let go of the network at any time.
3817 *
3818 * <p>A version of this method which takes a timeout is
3819 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3820 * wait for a limited amount of time for the network to become unavailable.
3821 *
Paul Jensenee52d232015-06-16 15:11:58 -04003822 * <p>It is presently unsupported to request a network with mutable
3823 * {@link NetworkCapabilities} such as
3824 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3825 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3826 * as these {@code NetworkCapabilities} represent states that a particular
3827 * network may never attain, and whether a network will attain these states
3828 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003829 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003830 *
3831 * <p>This method requires the caller to hold either the
3832 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3833 * or the ability to modify system settings as determined by
3834 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003835 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003836 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3837 * number of outstanding requests to 100 per app (identified by their UID), shared with
3838 * all variants of this method, of {@link #registerNetworkCallback} as well as
3839 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3840 * Requesting a network with this method will count toward this limit. If this limit is
3841 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3842 * make sure to unregister the callbacks with
3843 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3844 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003845 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003846 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3847 * the callback must not be shared - it uniquely specifies this request.
3848 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003849 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3850 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003851 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003852 */
Chalard Jean158702d2019-01-07 19:26:34 +09003853 public void requestNetwork(@NonNull NetworkRequest request,
3854 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003855 requestNetwork(request, networkCallback, getDefaultHandler());
3856 }
3857
3858 /**
3859 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3860 *
Chalard Jean01378b62019-08-30 16:27:28 +09003861 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3862 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003863 *
Chalard Jean01378b62019-08-30 16:27:28 +09003864 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003865 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3866 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003867 *
3868 * @param request {@link NetworkRequest} describing this request.
3869 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3870 * the callback must not be shared - it uniquely specifies this request.
3871 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003872 */
Chalard Jean158702d2019-01-07 19:26:34 +09003873 public void requestNetwork(@NonNull NetworkRequest request,
3874 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003875 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003876 NetworkCapabilities nc = request.networkCapabilities;
3877 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003878 }
3879
3880 /**
Etan Cohenf67bde92017-03-01 12:47:28 -08003881 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3882 * by a timeout.
3883 *
3884 * This function behaves identically to the non-timed-out version
3885 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3886 * is not found within the given time (in milliseconds) the
3887 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3888 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3889 * not have to be released if timed-out (it is automatically released). Unregistering a
3890 * request that timed out is not an error.
3891 *
3892 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3893 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3894 * for that purpose. Calling this method will attempt to bring up the requested network.
3895 *
Chalard Jean01378b62019-08-30 16:27:28 +09003896 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003897 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3898 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003899 *
3900 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003901 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3902 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003903 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3904 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3905 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003906 */
Chalard Jean158702d2019-01-07 19:26:34 +09003907 public void requestNetwork(@NonNull NetworkRequest request,
3908 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003909 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003910 NetworkCapabilities nc = request.networkCapabilities;
3911 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3912 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003913 }
3914
Hugo Benichifd44e912017-02-02 17:02:36 +09003915 /**
3916 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3917 * by a timeout.
3918 *
Chalard Jean01378b62019-08-30 16:27:28 +09003919 * This method behaves identically to
3920 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3921 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003922 *
Chalard Jean01378b62019-08-30 16:27:28 +09003923 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003924 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3925 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003926 *
3927 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003928 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3929 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003930 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003931 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3932 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003933 */
Chalard Jean158702d2019-01-07 19:26:34 +09003934 public void requestNetwork(@NonNull NetworkRequest request,
3935 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003936 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003937 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003938 NetworkCapabilities nc = request.networkCapabilities;
3939 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003940 }
3941
3942 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003943 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003944 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003945 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003946 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003947 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3948 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003949 */
Erik Kline8a826212014-11-19 12:12:24 +09003950 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003951
3952 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003953 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003954 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003955 * {@link android.content.Intent#getParcelableExtra(String)}.
3956 */
Erik Kline8a826212014-11-19 12:12:24 +09003957 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003958
3959
3960 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003961 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003962 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003963 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003964 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003965 * the request may outlive the calling application and get called back when a suitable
3966 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003967 * <p>
3968 * The operation is an Intent broadcast that goes to a broadcast receiver that
3969 * you registered with {@link Context#registerReceiver} or through the
3970 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3971 * <p>
3972 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003973 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3974 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003975 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003976 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003977 * Intent to reserve the network or it will be released shortly after the Intent
3978 * is processed.
3979 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003980 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003981 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003982 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003983 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003984 * The request may be released normally by calling
3985 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003986 * <p>It is presently unsupported to request a network with either
3987 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3988 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3989 * as these {@code NetworkCapabilities} represent states that a particular
3990 * network may never attain, and whether a network will attain these states
3991 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003992 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003993 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003994 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3995 * number of outstanding requests to 100 per app (identified by their UID), shared with
3996 * all variants of this method, of {@link #registerNetworkCallback} as well as
3997 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3998 * Requesting a network with this method will count toward this limit. If this limit is
3999 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4000 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4001 * or {@link #releaseNetworkRequest(PendingIntent)}.
4002 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004003 * <p>This method requires the caller to hold either the
4004 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4005 * or the ability to modify system settings as determined by
4006 * {@link android.provider.Settings.System#canWrite}.</p>
4007 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004008 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004009 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004010 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004011 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004012 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4013 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004014 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004015 */
Chalard Jean158702d2019-01-07 19:26:34 +09004016 public void requestNetwork(@NonNull NetworkRequest request,
4017 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004018 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004019 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004020 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004021 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004022 request.networkCapabilities, operation, mContext.getOpPackageName(),
4023 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004024 } catch (RemoteException e) {
4025 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004026 } catch (ServiceSpecificException e) {
4027 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004028 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004029 }
4030
4031 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004032 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4033 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004034 * This method has the same behavior as
4035 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004036 * releasing network resources and disconnecting.
4037 *
4038 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4039 * PendingIntent passed to
4040 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4041 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4042 */
Chalard Jean158702d2019-01-07 19:26:34 +09004043 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004044 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004045 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004046 try {
4047 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004048 } catch (RemoteException e) {
4049 throw e.rethrowFromSystemServer();
4050 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004051 }
4052
Hugo Benichibc1104b2017-05-09 15:19:01 +09004053 private static void checkPendingIntentNotNull(PendingIntent intent) {
4054 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4055 }
4056
4057 private static void checkCallbackNotNull(NetworkCallback callback) {
4058 Preconditions.checkNotNull(callback, "null NetworkCallback");
4059 }
4060
4061 private static void checkTimeout(int timeoutMs) {
4062 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004063 }
4064
4065 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004066 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004067 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004068 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4069 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004070 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004071 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4072 * number of outstanding requests to 100 per app (identified by their UID), shared with
4073 * all variants of this method, of {@link #requestNetwork} as well as
4074 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4075 * Requesting a network with this method will count toward this limit. If this limit is
4076 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4077 * make sure to unregister the callbacks with
4078 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4079 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004080 * @param request {@link NetworkRequest} describing this request.
4081 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4082 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004083 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004084 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004085 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004086 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004087 public void registerNetworkCallback(@NonNull NetworkRequest request,
4088 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004089 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4090 }
4091
4092 /**
4093 * Registers to receive notifications about all networks which satisfy the given
4094 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004095 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4096 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004097 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004098 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4099 * number of outstanding requests to 100 per app (identified by their UID), shared with
4100 * all variants of this method, of {@link #requestNetwork} as well as
4101 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4102 * Requesting a network with this method will count toward this limit. If this limit is
4103 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4104 * make sure to unregister the callbacks with
4105 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4106 *
4107 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004108 * @param request {@link NetworkRequest} describing this request.
4109 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4110 * networks change state.
4111 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004112 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004113 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004114 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004115 public void registerNetworkCallback(@NonNull NetworkRequest request,
4116 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004117 CallbackHandler cbHandler = new CallbackHandler(handler);
4118 NetworkCapabilities nc = request.networkCapabilities;
4119 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004120 }
4121
4122 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004123 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4124 * {@link NetworkRequest}.
4125 *
4126 * This function behaves identically to the version that takes a NetworkCallback, but instead
4127 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4128 * the request may outlive the calling application and get called back when a suitable
4129 * network is found.
4130 * <p>
4131 * The operation is an Intent broadcast that goes to a broadcast receiver that
4132 * you registered with {@link Context#registerReceiver} or through the
4133 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4134 * <p>
4135 * The operation Intent is delivered with two extras, a {@link Network} typed
4136 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4137 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4138 * the original requests parameters.
4139 * <p>
4140 * If there is already a request for this Intent registered (with the equality of
4141 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4142 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4143 * <p>
4144 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004145 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004146 *
4147 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4148 * number of outstanding requests to 100 per app (identified by their UID), shared with
4149 * all variants of this method, of {@link #requestNetwork} as well as
4150 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4151 * Requesting a network with this method will count toward this limit. If this limit is
4152 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4153 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4154 * or {@link #releaseNetworkRequest(PendingIntent)}.
4155 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004156 * @param request {@link NetworkRequest} describing this request.
4157 * @param operation Action to perform when the network is available (corresponds
4158 * to the {@link NetworkCallback#onAvailable} call. Typically
4159 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004160 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004161 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004162 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004163 public void registerNetworkCallback(@NonNull NetworkRequest request,
4164 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004165 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004166 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004167 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004168 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004169 request.networkCapabilities, operation, mContext.getOpPackageName(),
4170 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004171 } catch (RemoteException e) {
4172 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004173 } catch (ServiceSpecificException e) {
4174 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004175 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004176 }
4177
4178 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004179 * Registers to receive notifications about changes in the application's default network. This
4180 * may be a physical network or a virtual network, such as a VPN that applies to the
4181 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004182 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004183 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004184 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4185 * number of outstanding requests to 100 per app (identified by their UID), shared with
4186 * all variants of this method, of {@link #requestNetwork} as well as
4187 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4188 * Requesting a network with this method will count toward this limit. If this limit is
4189 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4190 * make sure to unregister the callbacks with
4191 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4192 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004193 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004194 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004195 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004196 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004197 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004198 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004199 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004200 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4201 }
4202
4203 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004204 * Registers to receive notifications about changes in the application's default network. This
4205 * may be a physical network or a virtual network, such as a VPN that applies to the
4206 * application. The callbacks will continue to be called until either the application exits or
4207 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4208 *
4209 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4210 * number of outstanding requests to 100 per app (identified by their UID), shared with
4211 * all variants of this method, of {@link #requestNetwork} as well as
4212 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4213 * Requesting a network with this method will count toward this limit. If this limit is
4214 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4215 * make sure to unregister the callbacks with
4216 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4217 *
4218 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4219 * application's default network changes.
4220 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4221 * @throws RuntimeException if the app already has too many callbacks registered.
4222 */
4223 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4224 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4225 @NonNull Handler handler) {
4226 CallbackHandler cbHandler = new CallbackHandler(handler);
4227 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4228 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4229 }
4230
4231 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004232 * Registers to receive notifications about changes in the system default network. The callbacks
4233 * will continue to be called until either the application exits or
4234 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004235 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004236 * This method should not be used to determine networking state seen by applications, because in
4237 * many cases, most or even all application traffic may not use the default network directly,
4238 * and traffic from different applications may go on different networks by default. As an
4239 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4240 * and not onto the system default network. Applications or system components desiring to do
4241 * determine network state as seen by applications should use other methods such as
4242 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4243 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004244 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4245 * number of outstanding requests to 100 per app (identified by their UID), shared with
4246 * all variants of this method, of {@link #requestNetwork} as well as
4247 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4248 * Requesting a network with this method will count toward this limit. If this limit is
4249 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4250 * make sure to unregister the callbacks with
4251 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4252 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004253 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4254 * system default network changes.
4255 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004256 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004257 *
4258 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004259 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004260 @SystemApi(client = MODULE_LIBRARIES)
4261 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4262 @RequiresPermission(anyOf = {
4263 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4264 android.Manifest.permission.NETWORK_SETTINGS})
4265 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004266 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004267 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004268 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004269 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004270 }
4271
4272 /**
fenglub00f4882015-04-21 17:12:05 -07004273 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4274 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4275 * network connection for updated bandwidth information. The caller will be notified via
4276 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004277 * method assumes that the caller has previously called
4278 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4279 * changes.
fenglu3f357402015-03-20 11:29:56 -07004280 *
fengluea2d9282015-04-27 14:28:04 -07004281 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004282 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004283 */
Chalard Jean158702d2019-01-07 19:26:34 +09004284 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004285 try {
fenglub00f4882015-04-21 17:12:05 -07004286 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004287 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004288 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004289 }
4290 }
4291
4292 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004293 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004294 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4295 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4296 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004297 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4298 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004299 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004300 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4301 * triggering it as soon as this call returns.
4302 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004303 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004304 */
Chalard Jean158702d2019-01-07 19:26:34 +09004305 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004306 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004307 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004308 final List<NetworkRequest> reqs = new ArrayList<>();
4309 // Find all requests associated to this callback and stop callback triggers immediately.
4310 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4311 synchronized (sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09004312 Preconditions.checkArgument(networkCallback.networkRequest != null,
4313 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004314 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4315 Log.d(TAG, "NetworkCallback was already unregistered");
4316 return;
4317 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004318 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4319 if (e.getValue() == networkCallback) {
4320 reqs.add(e.getKey());
4321 }
4322 }
4323 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4324 for (NetworkRequest r : reqs) {
4325 try {
4326 mService.releaseNetworkRequest(r);
4327 } catch (RemoteException e) {
4328 throw e.rethrowFromSystemServer();
4329 }
4330 // Only remove mapping if rpc was successful.
4331 sCallbacks.remove(r);
4332 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004333 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004334 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004335 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004336
4337 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004338 * Unregisters a callback previously registered via
4339 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4340 *
4341 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4342 * PendingIntent passed to
4343 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4344 * Cannot be null.
4345 */
Chalard Jean158702d2019-01-07 19:26:34 +09004346 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004347 releaseNetworkRequest(operation);
4348 }
4349
4350 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004351 * Informs the system whether it should switch to {@code network} regardless of whether it is
4352 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4353 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4354 * the system default network regardless of any other network that's currently connected. If
4355 * {@code always} is true, then the choice is remembered, so that the next time the user
4356 * connects to this network, the system will switch to it.
4357 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004358 * @param network The network to accept.
4359 * @param accept Whether to accept the network even if unvalidated.
4360 * @param always Whether to remember this choice in the future.
4361 *
4362 * @hide
4363 */
lucaslin2240ef62019-03-12 13:08:03 +08004364 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004365 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4366 try {
4367 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004368 } catch (RemoteException e) {
4369 throw e.rethrowFromSystemServer();
4370 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004371 }
4372
4373 /**
lucaslin2240ef62019-03-12 13:08:03 +08004374 * Informs the system whether it should consider the network as validated even if it only has
4375 * partial connectivity. If {@code accept} is true, then the network will be considered as
4376 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4377 * is remembered, so that the next time the user connects to this network, the system will
4378 * switch to it.
4379 *
4380 * @param network The network to accept.
4381 * @param accept Whether to consider the network as validated even if it has partial
4382 * connectivity.
4383 * @param always Whether to remember this choice in the future.
4384 *
4385 * @hide
4386 */
4387 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4388 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4389 try {
4390 mService.setAcceptPartialConnectivity(network, accept, always);
4391 } catch (RemoteException e) {
4392 throw e.rethrowFromSystemServer();
4393 }
4394 }
4395
4396 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004397 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4398 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4399 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4400 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4401 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004402 * @param network The network to accept.
4403 *
4404 * @hide
4405 */
lucaslin2240ef62019-03-12 13:08:03 +08004406 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004407 public void setAvoidUnvalidated(Network network) {
4408 try {
4409 mService.setAvoidUnvalidated(network);
4410 } catch (RemoteException e) {
4411 throw e.rethrowFromSystemServer();
4412 }
4413 }
4414
4415 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004416 * Requests that the system open the captive portal app on the specified network.
4417 *
4418 * @param network The network to log into.
4419 *
4420 * @hide
4421 */
paulhu8e96a752019-08-12 16:25:11 +08004422 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004423 public void startCaptivePortalApp(Network network) {
4424 try {
4425 mService.startCaptivePortalApp(network);
4426 } catch (RemoteException e) {
4427 throw e.rethrowFromSystemServer();
4428 }
4429 }
4430
4431 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004432 * Requests that the system open the captive portal app with the specified extras.
4433 *
4434 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4435 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004436 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004437 * @param appExtras Extras to include in the app start intent.
4438 * @hide
4439 */
4440 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004441 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004442 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004443 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004444 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004445 } catch (RemoteException e) {
4446 throw e.rethrowFromSystemServer();
4447 }
4448 }
4449
4450 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004451 * Determine whether the device is configured to avoid bad wifi.
4452 * @hide
4453 */
4454 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004455 @RequiresPermission(anyOf = {
4456 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4457 android.Manifest.permission.NETWORK_STACK})
4458 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004459 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004460 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004461 } catch (RemoteException e) {
4462 throw e.rethrowFromSystemServer();
4463 }
4464 }
4465
4466 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004467 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4468 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004469 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4470 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004471 *
4472 * An example of such an operation might be a time-sensitive foreground activity, such as a
4473 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4474 */
4475 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4476
4477 /**
4478 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4479 * a backup channel for traffic that is primarily going over another network.
4480 *
4481 * An example might be maintaining backup connections to peers or servers for the purpose of
4482 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4483 * on backup paths should be negligible compared to the traffic on the main path.
4484 */
4485 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4486
4487 /**
4488 * It is acceptable to use metered data to improve network latency and performance.
4489 */
4490 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4491
4492 /**
4493 * Return value to use for unmetered networks. On such networks we currently set all the flags
4494 * to true.
4495 * @hide
4496 */
4497 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4498 MULTIPATH_PREFERENCE_HANDOVER |
4499 MULTIPATH_PREFERENCE_RELIABILITY |
4500 MULTIPATH_PREFERENCE_PERFORMANCE;
4501
4502 /** @hide */
4503 @Retention(RetentionPolicy.SOURCE)
4504 @IntDef(flag = true, value = {
4505 MULTIPATH_PREFERENCE_HANDOVER,
4506 MULTIPATH_PREFERENCE_RELIABILITY,
4507 MULTIPATH_PREFERENCE_PERFORMANCE,
4508 })
4509 public @interface MultipathPreference {
4510 }
4511
4512 /**
4513 * Provides a hint to the calling application on whether it is desirable to use the
4514 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4515 * for multipath data transfer on this network when it is not the system default network.
4516 * Applications desiring to use multipath network protocols should call this method before
4517 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004518 *
4519 * @param network The network on which the application desires to use multipath data.
4520 * If {@code null}, this method will return the a preference that will generally
4521 * apply to metered networks.
4522 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4523 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004524 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004525 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004526 try {
4527 return mService.getMultipathPreference(network);
4528 } catch (RemoteException e) {
4529 throw e.rethrowFromSystemServer();
4530 }
4531 }
4532
4533 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004534 * Resets all connectivity manager settings back to factory defaults.
4535 * @hide
4536 */
paulhu8e96a752019-08-12 16:25:11 +08004537 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004538 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004539 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004540 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004541 mTetheringManager.stopAllTethering();
Lorenzo Colitticd675292021-02-04 17:32:07 +09004542 // TODO: Migrate callers to VpnManager#factoryReset.
4543 getVpnManager().factoryReset();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004544 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004545 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004546 }
4547 }
4548
4549 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004550 * Binds the current process to {@code network}. All Sockets created in the future
4551 * (and not explicitly bound via a bound SocketFactory from
4552 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4553 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4554 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4555 * work and all host name resolutions will fail. This is by design so an application doesn't
4556 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4557 * To clear binding pass {@code null} for {@code network}. Using individually bound
4558 * Sockets created by Network.getSocketFactory().createSocket() and
4559 * performing network-specific host name resolutions via
4560 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004561 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004562 *
4563 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4564 * the current binding.
4565 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4566 */
Chalard Jean158702d2019-01-07 19:26:34 +09004567 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004568 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004569 // instantiated.
4570 return setProcessDefaultNetwork(network);
4571 }
4572
4573 /**
4574 * Binds the current process to {@code network}. All Sockets created in the future
4575 * (and not explicitly bound via a bound SocketFactory from
4576 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4577 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4578 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4579 * work and all host name resolutions will fail. This is by design so an application doesn't
4580 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4581 * To clear binding pass {@code null} for {@code network}. Using individually bound
4582 * Sockets created by Network.getSocketFactory().createSocket() and
4583 * performing network-specific host name resolutions via
4584 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4585 * {@code setProcessDefaultNetwork}.
4586 *
4587 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4588 * the current binding.
4589 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4590 * @deprecated This function can throw {@link IllegalStateException}. Use
4591 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4592 * is a direct replacement.
4593 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004594 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004595 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004596 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004597 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4598
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004599 if (netId != NETID_UNSET) {
4600 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004601 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004602
4603 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4604 return false;
4605 }
4606
4607 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004608 // Set HTTP proxy system properties to match network.
4609 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004610 try {
4611 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4612 } catch (SecurityException e) {
4613 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4614 Log.e(TAG, "Can't set proxy properties", e);
4615 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004616 // Must flush DNS cache as new network may have different DNS resolutions.
4617 InetAddress.clearDnsCache();
4618 // Must flush socket pool as idle sockets will be bound to previous network and may
4619 // cause subsequent fetches to be performed on old network.
4620 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004621 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004622
4623 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004624 }
4625
4626 /**
4627 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004628 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004629 *
4630 * @return {@code Network} to which this process is bound, or {@code null}.
4631 */
Chalard Jean158702d2019-01-07 19:26:34 +09004632 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004633 public Network getBoundNetworkForProcess() {
4634 // Forcing callers to call thru non-static function ensures ConnectivityManager
4635 // instantiated.
4636 return getProcessDefaultNetwork();
4637 }
4638
4639 /**
4640 * Returns the {@link Network} currently bound to this process via
4641 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4642 *
4643 * @return {@code Network} to which this process is bound, or {@code null}.
4644 * @deprecated Using this function can lead to other functions throwing
4645 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4646 * {@code getBoundNetworkForProcess} is a direct replacement.
4647 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004648 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004649 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004650 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004651 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004652 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004653 return new Network(netId);
4654 }
4655
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004656 private void unsupportedStartingFrom(int version) {
4657 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004658 // The getApplicationInfo() call we make below is not supported in system context. Let
4659 // the call through here, and rely on the fact that ConnectivityService will refuse to
4660 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004661 return;
4662 }
4663
4664 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4665 throw new UnsupportedOperationException(
4666 "This method is not supported in target SDK version " + version + " and above");
4667 }
4668 }
4669
4670 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4671 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004672 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004673 // remove these exemptions. Note that this check is not secure, and apps can still access these
4674 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4675 // so is unsupported and may break in the future. http://b/22728205
4676 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004677 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004678 }
4679
Paul Jensen8cdda642014-05-29 10:12:39 -04004680 /**
4681 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004682 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004683 *
4684 * @param network The {@link Network} to bind host resolutions from the current process to, or
4685 * {@code null} to clear the current binding.
4686 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4687 * @hide
4688 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4689 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004690 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004691 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004692 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004693 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004694 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004695 }
Felipe Leme30511352016-01-22 09:44:57 -08004696
4697 /**
4698 * Device is not restricting metered network activity while application is running on
4699 * background.
4700 */
4701 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4702
4703 /**
4704 * Device is restricting metered network activity while application is running on background,
4705 * but application is allowed to bypass it.
4706 * <p>
4707 * In this state, application should take action to mitigate metered network access.
4708 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4709 */
4710 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4711
4712 /**
4713 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004714 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004715 * In this state, application should not try to use the network while running on background,
4716 * because it would be denied.
4717 */
4718 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4719
Felipe Lemed34c9af2016-01-27 14:46:39 -08004720 /**
4721 * A change in the background metered network activity restriction has occurred.
4722 * <p>
4723 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4724 * applies to them.
4725 * <p>
4726 * This is only sent to registered receivers, not manifest receivers.
4727 */
4728 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4729 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4730 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4731
Felipe Leme7e4c1852016-01-25 11:48:04 -08004732 /** @hide */
4733 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004734 @IntDef(flag = false, value = {
4735 RESTRICT_BACKGROUND_STATUS_DISABLED,
4736 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4737 RESTRICT_BACKGROUND_STATUS_ENABLED,
4738 })
Felipe Leme30511352016-01-22 09:44:57 -08004739 public @interface RestrictBackgroundStatus {
4740 }
4741
4742 private INetworkPolicyManager getNetworkPolicyManager() {
4743 synchronized (this) {
4744 if (mNPManager != null) {
4745 return mNPManager;
4746 }
4747 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4748 .getService(Context.NETWORK_POLICY_SERVICE));
4749 return mNPManager;
4750 }
4751 }
4752
4753 /**
4754 * Determines if the calling application is subject to metered network restrictions while
4755 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004756 *
4757 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4758 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4759 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004760 */
4761 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4762 try {
4763 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4764 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004765 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004766 }
4767 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004768
4769 /**
4770 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004771 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4772 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004773 *
4774 * @return Hash of network watchlist config file. Null if config does not exist.
4775 */
Chalard Jean158702d2019-01-07 19:26:34 +09004776 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004777 public byte[] getNetworkWatchlistConfigHash() {
4778 try {
4779 return mService.getNetworkWatchlistConfigHash();
4780 } catch (RemoteException e) {
4781 Log.e(TAG, "Unable to get watchlist config hash");
4782 throw e.rethrowFromSystemServer();
4783 }
4784 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004785
4786 /**
4787 * Returns the {@code uid} of the owner of a network connection.
4788 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004789 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4790 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004791 * @param local The local {@link InetSocketAddress} of a connection.
4792 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004793 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004794 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4795 * android.os.Process#INVALID_UID} if the connection is not found.
4796 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4797 * user.
4798 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004799 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004800 public int getConnectionOwnerUid(
4801 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004802 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4803 try {
4804 return mService.getConnectionOwnerUid(connectionInfo);
4805 } catch (RemoteException e) {
4806 throw e.rethrowFromSystemServer();
4807 }
4808 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004809
4810 private void printStackTrace() {
4811 if (DEBUG) {
4812 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4813 final StringBuffer sb = new StringBuffer();
4814 for (int i = 3; i < callStack.length; i++) {
4815 final String stackTrace = callStack[i].toString();
4816 if (stackTrace == null || stackTrace.contains("android.os")) {
4817 break;
4818 }
4819 sb.append(" [").append(stackTrace).append("]");
4820 }
4821 Log.d(TAG, "StackLog:" + sb.toString());
4822 }
4823 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004824
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004825 /** @hide */
4826 public TestNetworkManager startOrGetTestNetworkManager() {
4827 final IBinder tnBinder;
4828 try {
4829 tnBinder = mService.startOrGetTestNetworkService();
4830 } catch (RemoteException e) {
4831 throw e.rethrowFromSystemServer();
4832 }
4833
4834 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4835 }
4836
Lorenzo Colitticd675292021-02-04 17:32:07 +09004837 /**
4838 * Temporary hack to shim calls from ConnectivityManager to VpnManager. We cannot store a
4839 * private final mVpnManager because ConnectivityManager is initialized before VpnManager.
4840 * @hide TODO: remove.
4841 */
4842 public VpnManager getVpnManager() {
4843 return mContext.getSystemService(VpnManager.class);
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004844 }
4845
4846 /** @hide */
4847 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4848 return new ConnectivityDiagnosticsManager(mContext, mService);
4849 }
4850
Cody Kestingf53a0752020-04-15 12:33:28 -07004851 /**
4852 * Simulates a Data Stall for the specified Network.
4853 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004854 * <p>This method should only be used for tests.
4855 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004856 * <p>The caller must be the owner of the specified Network.
4857 *
4858 * @param detectionMethod The detection method used to identify the Data Stall.
4859 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4860 * @param network The Network for which a Data Stall is being simluated.
4861 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4862 * @throws SecurityException if the caller is not the owner of the given network.
4863 * @hide
4864 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004865 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004866 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4867 android.Manifest.permission.NETWORK_STACK})
4868 public void simulateDataStall(int detectionMethod, long timestampMillis,
4869 @NonNull Network network, @NonNull PersistableBundle extras) {
4870 try {
4871 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4872 } catch (RemoteException e) {
4873 e.rethrowFromSystemServer();
4874 }
4875 }
James Mattis356a8792020-10-28 21:48:54 -07004876
James Mattis47db0582021-01-01 14:13:35 -08004877 private void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
4878 try {
4879 mService.setOemNetworkPreference(preference);
4880 } catch (RemoteException e) {
4881 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
4882 throw e.rethrowFromSystemServer();
4883 }
James Mattis356a8792020-10-28 21:48:54 -07004884 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004885
4886 @NonNull
4887 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4888
4889 /**
4890 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4891 * receive available QoS events related to the {@link Network} and local ip + port
4892 * specified within socketInfo.
4893 * <p/>
4894 * The same {@link QosCallback} must be unregistered before being registered a second time,
4895 * otherwise {@link QosCallbackRegistrationException} is thrown.
4896 * <p/>
4897 * This API does not, in itself, require any permission if called with a network that is not
4898 * restricted. However, the underlying implementation currently only supports the IMS network,
4899 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4900 * useful, because they'd never be called back on networks that they would have access to.
4901 *
4902 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4903 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4904 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4905 * @throws RuntimeException if the app already has too many callbacks registered.
4906 *
4907 * Exceptions after the time of registration is passed through
4908 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4909 *
4910 * @param socketInfo the socket information used to match QoS events
4911 * @param callback receives qos events that satisfy socketInfo
4912 * @param executor The executor on which the callback will be invoked. The provided
4913 * {@link Executor} must run callback sequentially, otherwise the order of
4914 * callbacks cannot be guaranteed.
4915 *
4916 * @hide
4917 */
4918 @SystemApi
4919 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4920 @NonNull final QosCallback callback,
4921 @CallbackExecutor @NonNull final Executor executor) {
4922 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4923 Objects.requireNonNull(callback, "callback must be non-null");
4924 Objects.requireNonNull(executor, "executor must be non-null");
4925
4926 try {
4927 synchronized (mQosCallbackConnections) {
4928 if (getQosCallbackConnection(callback) == null) {
4929 final QosCallbackConnection connection =
4930 new QosCallbackConnection(this, callback, executor);
4931 mQosCallbackConnections.add(connection);
4932 mService.registerQosSocketCallback(socketInfo, connection);
4933 } else {
4934 Log.e(TAG, "registerQosCallback: Callback already registered");
4935 throw new QosCallbackRegistrationException();
4936 }
4937 }
4938 } catch (final RemoteException e) {
4939 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4940
4941 // The same unregister method method is called for consistency even though nothing
4942 // will be sent to the ConnectivityService since the callback was never successfully
4943 // registered.
4944 unregisterQosCallback(callback);
4945 e.rethrowFromSystemServer();
4946 } catch (final ServiceSpecificException e) {
4947 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4948 unregisterQosCallback(callback);
4949 throw convertServiceException(e);
4950 }
4951 }
4952
4953 /**
4954 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4955 * events once unregistered and can be registered a second time.
4956 * <p/>
4957 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4958 *
4959 * @param callback the callback being unregistered
4960 *
4961 * @hide
4962 */
4963 @SystemApi
4964 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4965 Objects.requireNonNull(callback, "The callback must be non-null");
4966 try {
4967 synchronized (mQosCallbackConnections) {
4968 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4969 if (connection != null) {
4970 connection.stopReceivingMessages();
4971 mService.unregisterQosCallback(connection);
4972 mQosCallbackConnections.remove(connection);
4973 } else {
4974 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4975 }
4976 }
4977 } catch (final RemoteException e) {
4978 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4979 e.rethrowFromSystemServer();
4980 }
4981 }
4982
4983 /**
4984 * Gets the connection related to the callback.
4985 *
4986 * @param callback the callback to look up
4987 * @return the related connection
4988 */
4989 @Nullable
4990 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4991 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4992 // Checking by reference here is intentional
4993 if (connection.getCallback() == callback) {
4994 return connection;
4995 }
4996 }
4997 return null;
4998 }
Junyu Laia62493f2021-01-19 11:10:56 +00004999
5000 /**
5001 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
5002 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5003 * be used to request that the system provide a network without causing the network to be
5004 * in the foreground.
5005 *
5006 * <p>This method will attempt to find the best network that matches the passed
5007 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5008 * criteria. The platform will evaluate which network is the best at its own discretion.
5009 * Throughput, latency, cost per byte, policy, user preference and other considerations
5010 * may be factored in the decision of what is considered the best network.
5011 *
5012 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5013 * matching this request, while always attempting to match the request to a better network if
5014 * possible. If a better match is found, the platform will switch this request to the now-best
5015 * network and inform the app of the newly best network by invoking
5016 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5017 * will not try to maintain any other network than the best one currently matching the request:
5018 * a network not matching any network request may be disconnected at any time.
5019 *
5020 * <p>For example, an application could use this method to obtain a connected cellular network
5021 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5022 * radio to consume additional power. Or, an application could inform the system that it wants
5023 * a network supporting sending MMSes and have the system let it know about the currently best
5024 * MMS-supporting network through the provided {@link NetworkCallback}.
5025 *
5026 * <p>The status of the request can be followed by listening to the various callbacks described
5027 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5028 * used to direct traffic to the network (although accessing some networks may be subject to
5029 * holding specific permissions). Callers will learn about the specific characteristics of the
5030 * network through
5031 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5032 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5033 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5034 * matching the request at any given time; therefore when a better network matching the request
5035 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5036 * with the new network after which no further updates are given about the previously-best
5037 * network, unless it becomes the best again at some later time. All callbacks are invoked
5038 * in order on the same thread, which by default is a thread created by the framework running
5039 * in the app.
5040 *
5041 * <p>This{@link NetworkRequest} will live until released via
5042 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5043 * which point the system may let go of the network at any time.
5044 *
5045 * <p>It is presently unsupported to request a network with mutable
5046 * {@link NetworkCapabilities} such as
5047 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5048 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5049 * as these {@code NetworkCapabilities} represent states that a particular
5050 * network may never attain, and whether a network will attain these states
5051 * is unknown prior to bringing up the network so the framework does not
5052 * know how to go about satisfying a request with these capabilities.
5053 *
5054 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5055 * number of outstanding requests to 100 per app (identified by their UID), shared with
5056 * all variants of this method, of {@link #registerNetworkCallback} as well as
5057 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5058 * Requesting a network with this method will count toward this limit. If this limit is
5059 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5060 * make sure to unregister the callbacks with
5061 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5062 *
5063 * @param request {@link NetworkRequest} describing this request.
5064 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5065 * If null, the callback is invoked on the default internal Handler.
5066 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5067 * the callback must not be shared - it uniquely specifies this request.
5068 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5069 * @throws SecurityException if missing the appropriate permissions.
5070 * @throws RuntimeException if the app already has too many callbacks registered.
5071 *
5072 * @hide
5073 */
5074 @SystemApi(client = MODULE_LIBRARIES)
5075 @SuppressLint("ExecutorRegistration")
5076 @RequiresPermission(anyOf = {
5077 android.Manifest.permission.NETWORK_SETTINGS,
5078 android.Manifest.permission.NETWORK_STACK,
5079 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5080 })
5081 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
5082 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
5083 final NetworkCapabilities nc = request.networkCapabilities;
5084 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
5085 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
5086 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005087}