blob: 8437798b7bbb36675e26b40d09c94d804d979f66 [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;
Paul Jensenc0618a62014-12-10 15:12:18 -0500827 /**
828 * A kludge to facilitate static access where a Context pointer isn't available, like in the
829 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
830 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
831 * methods that take a Context argument.
832 */
833 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800834
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900835 private final Context mContext;
836
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800837 private INetworkManagementService mNMService;
Felipe Leme30511352016-01-22 09:44:57 -0800838 private INetworkPolicyManager mNPManager;
Amos Bianchia9b415a2020-03-04 11:07:38 -0800839 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800840
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800841 /**
842 * Tests if a given integer represents a valid network type.
843 * @param networkType the type to be tested
844 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400845 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
846 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800847 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700848 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700849 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900850 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800851 }
852
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800853 /**
854 * Returns a non-localized string representing a given network type.
855 * ONLY used for debugging output.
856 * @param type the type needing naming
857 * @return a String for the given type, or a string version of the type ("87")
858 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900859 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800860 * {@hide}
861 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900862 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000863 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700864 public static String getNetworkTypeName(int type) {
865 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900866 case TYPE_NONE:
867 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700868 case TYPE_MOBILE:
869 return "MOBILE";
870 case TYPE_WIFI:
871 return "WIFI";
872 case TYPE_MOBILE_MMS:
873 return "MOBILE_MMS";
874 case TYPE_MOBILE_SUPL:
875 return "MOBILE_SUPL";
876 case TYPE_MOBILE_DUN:
877 return "MOBILE_DUN";
878 case TYPE_MOBILE_HIPRI:
879 return "MOBILE_HIPRI";
880 case TYPE_WIMAX:
881 return "WIMAX";
882 case TYPE_BLUETOOTH:
883 return "BLUETOOTH";
884 case TYPE_DUMMY:
885 return "DUMMY";
886 case TYPE_ETHERNET:
887 return "ETHERNET";
888 case TYPE_MOBILE_FOTA:
889 return "MOBILE_FOTA";
890 case TYPE_MOBILE_IMS:
891 return "MOBILE_IMS";
892 case TYPE_MOBILE_CBS:
893 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700894 case TYPE_WIFI_P2P:
895 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700896 case TYPE_MOBILE_IA:
897 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700898 case TYPE_MOBILE_EMERGENCY:
899 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500900 case TYPE_PROXY:
901 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900902 case TYPE_VPN:
903 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700904 default:
905 return Integer.toString(type);
906 }
907 }
908
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800909 /**
Aaron Huang96011892020-06-27 07:18:23 +0800910 * @hide
911 * TODO: Expose for SystemServer when becomes a module.
912 */
913 public void systemReady() {
914 try {
915 mService.systemReady();
916 } catch (RemoteException e) {
917 throw e.rethrowFromSystemServer();
918 }
919 }
920
921 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800922 * Checks if a given type uses the cellular data connection.
923 * This should be replaced in the future by a network property.
924 * @param networkType the type to check
925 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900926 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800927 * {@hide}
928 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900929 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900930 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700931 public static boolean isNetworkTypeMobile(int networkType) {
932 switch (networkType) {
933 case TYPE_MOBILE:
934 case TYPE_MOBILE_MMS:
935 case TYPE_MOBILE_SUPL:
936 case TYPE_MOBILE_DUN:
937 case TYPE_MOBILE_HIPRI:
938 case TYPE_MOBILE_FOTA:
939 case TYPE_MOBILE_IMS:
940 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -0700941 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -0700942 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700943 return true;
944 default:
945 return false;
946 }
947 }
948
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800949 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700950 * Checks if the given network type is backed by a Wi-Fi radio.
951 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900952 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700953 * @hide
954 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900955 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700956 public static boolean isNetworkTypeWifi(int networkType) {
957 switch (networkType) {
958 case TYPE_WIFI:
959 case TYPE_WIFI_P2P:
960 return true;
961 default:
962 return false;
963 }
964 }
965
966 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800967 * Specifies the preferred network type. When the device has more
968 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800969 *
970 * @param preference the network type to prefer over all others. It is
971 * unspecified what happens to the old preferred network in the
972 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700973 * @deprecated Functionality has been removed as it no longer makes sense,
974 * with many more than two networks - we'd need an array to express
975 * preference. Instead we use dynamic network properties of
976 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800977 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700978 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800979 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800980 }
981
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800982 /**
983 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800984 *
985 * @return an integer representing the preferred network type
986 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700987 * @deprecated Functionality has been removed as it no longer makes sense,
988 * with many more than two networks - we'd need an array to express
989 * preference. Instead we use dynamic network properties of
990 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800991 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700992 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -0600993 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -0800994 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700995 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800996 }
997
Scott Mainf58b7d82011-10-06 19:02:28 -0700998 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800999 * Returns details about the currently active default data network. When
1000 * connected, this network is the default route for outgoing connections.
1001 * You should always check {@link NetworkInfo#isConnected()} before initiating
1002 * network traffic. This may return {@code null} when there is no default
1003 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001004 * Note that if the default network is a VPN, this method will return the
1005 * NetworkInfo for one of its underlying networks instead, or null if the
1006 * VPN agent did not specify any. Apps interested in learning about VPNs
1007 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001008 *
1009 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001010 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001011 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001012 */
junyulai9826e7f2018-12-13 12:47:51 +08001013 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001014 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001015 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001016 public NetworkInfo getActiveNetworkInfo() {
1017 try {
1018 return mService.getActiveNetworkInfo();
1019 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001020 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001021 }
1022 }
1023
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001024 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001025 * Returns a {@link Network} object corresponding to the currently active
1026 * default data network. In the event that the current active default data
1027 * network disconnects, the returned {@code Network} object will no longer
1028 * be usable. This will return {@code null} when there is no default
1029 * network.
1030 *
1031 * @return a {@link Network} object for the current default network or
1032 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001033 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001034 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001035 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001036 public Network getActiveNetwork() {
1037 try {
1038 return mService.getActiveNetwork();
1039 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001040 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001041 }
1042 }
1043
1044 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001045 * Returns a {@link Network} object corresponding to the currently active
1046 * default data network for a specific UID. In the event that the default data
1047 * network disconnects, the returned {@code Network} object will no longer
1048 * be usable. This will return {@code null} when there is no default
1049 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001050 *
1051 * @return a {@link Network} object for the current default network for the
1052 * given UID or {@code null} if no default network is currently active
1053 *
1054 * @hide
1055 */
paulhu8e96a752019-08-12 16:25:11 +08001056 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001057 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001058 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001059 return getActiveNetworkForUid(uid, false);
1060 }
1061
1062 /** {@hide} */
1063 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001064 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001065 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001066 } catch (RemoteException e) {
1067 throw e.rethrowFromSystemServer();
1068 }
1069 }
1070
1071 /**
Charles He9369e612017-05-15 17:07:18 +01001072 * Checks if a VPN app supports always-on mode.
1073 *
1074 * In order to support the always-on feature, an app has to
1075 * <ul>
1076 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hed6813632017-08-15 15:30:22 +01001077 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
1078 * meta-data field.
Charles He9369e612017-05-15 17:07:18 +01001079 * </ul>
1080 *
1081 * @param userId The identifier of the user for whom the VPN app is installed.
1082 * @param vpnPackage The canonical package name of the VPN app.
1083 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
1084 * @hide
1085 */
1086 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1087 try {
1088 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1089 } catch (RemoteException e) {
1090 throw e.rethrowFromSystemServer();
1091 }
1092 }
1093
1094 /**
Robin Leee5d5ed52016-01-05 18:03:46 +00001095 * Configures an always-on VPN connection through a specific application.
1096 * This connection is automatically granted and persisted after a reboot.
1097 *
1098 * <p>The designated package should declare a {@link VpnService} in its
1099 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1100 * otherwise the call will fail.
1101 *
1102 * @param userId The identifier of the user to set an always-on VPN for.
1103 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1104 * to remove an existing always-on VPN configuration.
Robin Lee94e69be2016-05-03 13:23:03 +01001105 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1106 * {@code false} otherwise.
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001107 * @param lockdownAllowlist The list of packages that are allowed to access network directly
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001108 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001109 * this method must be called when a package that should be allowed is installed or
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001110 * uninstalled.
Robin Leee5d5ed52016-01-05 18:03:46 +00001111 * @return {@code true} if the package is set as always-on VPN controller;
1112 * {@code false} otherwise.
1113 * @hide
1114 */
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001115 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee94e69be2016-05-03 13:23:03 +01001116 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001117 boolean lockdownEnabled, @Nullable List<String> lockdownAllowlist) {
Robin Leee5d5ed52016-01-05 18:03:46 +00001118 try {
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001119 return mService.setAlwaysOnVpnPackage(
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001120 userId, vpnPackage, lockdownEnabled, lockdownAllowlist);
Robin Leee5d5ed52016-01-05 18:03:46 +00001121 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001122 throw e.rethrowFromSystemServer();
Robin Leee5d5ed52016-01-05 18:03:46 +00001123 }
1124 }
1125
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001126 /**
Robin Leee5d5ed52016-01-05 18:03:46 +00001127 * Returns the package name of the currently set always-on VPN application.
1128 * If there is no always-on VPN set, or the VPN is provided by the system instead
1129 * of by an app, {@code null} will be returned.
1130 *
1131 * @return Package name of VPN controller responsible for always-on VPN,
1132 * or {@code null} if none is set.
1133 * @hide
1134 */
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001135 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leee5d5ed52016-01-05 18:03:46 +00001136 public String getAlwaysOnVpnPackageForUser(int userId) {
1137 try {
1138 return mService.getAlwaysOnVpnPackage(userId);
1139 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001140 throw e.rethrowFromSystemServer();
Robin Leee5d5ed52016-01-05 18:03:46 +00001141 }
1142 }
1143
1144 /**
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001145 * @return whether always-on VPN is in lockdown mode.
1146 *
1147 * @hide
1148 **/
1149 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1150 public boolean isVpnLockdownEnabled(int userId) {
1151 try {
1152 return mService.isVpnLockdownEnabled(userId);
1153 } catch (RemoteException e) {
1154 throw e.rethrowFromSystemServer();
1155 }
1156
1157 }
1158
1159 /**
1160 * @return the list of packages that are allowed to access network when always-on VPN is in
1161 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1162 *
1163 * @hide
1164 **/
1165 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1166 public List<String> getVpnLockdownWhitelist(int userId) {
1167 try {
1168 return mService.getVpnLockdownWhitelist(userId);
1169 } catch (RemoteException e) {
1170 throw e.rethrowFromSystemServer();
1171 }
1172 }
1173
1174 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001175 * Adds or removes a requirement for given UID ranges to use the VPN.
1176 *
1177 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1178 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1179 * otherwise have permission to bypass the VPN (e.g., because they have the
1180 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1181 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1182 * set to {@code false}, a previously-added restriction is removed.
1183 * <p>
1184 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1185 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1186 * remove a previously-added range, the exact range must be removed as is.
1187 * <p>
1188 * The changes are applied asynchronously and may not have been applied by the time the method
1189 * returns. Apps will be notified about any changes that apply to them via
1190 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1191 * effect.
1192 * <p>
1193 * This method should be called only by the VPN code.
1194 *
1195 * @param ranges the UID ranges to restrict
1196 * @param requireVpn whether the specified UID ranges must use a VPN
1197 *
1198 * TODO: expose as @SystemApi.
1199 * @hide
1200 */
1201 @RequiresPermission(anyOf = {
1202 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1203 android.Manifest.permission.NETWORK_STACK})
1204 public void setRequireVpnForUids(boolean requireVpn,
1205 @NonNull Collection<Range<Integer>> ranges) {
1206 Objects.requireNonNull(ranges);
1207 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1208 // This method is not necessarily expected to be used outside the system server, so
1209 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1210 // stack process, or by tests.
1211 UidRange[] rangesArray = new UidRange[ranges.size()];
1212 int index = 0;
1213 for (Range<Integer> range : ranges) {
1214 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1215 }
1216 try {
1217 mService.setRequireVpnForUids(requireVpn, rangesArray);
1218 } catch (RemoteException e) {
1219 throw e.rethrowFromSystemServer();
1220 }
1221 }
1222
1223 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001224 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1225 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1226 * but is still supported for backwards compatibility.
1227 * <p>
1228 * This type of VPN is assumed always to use the system default network, and must always declare
1229 * exactly one underlying network, which is the network that was the default when the VPN
1230 * connected.
1231 * <p>
1232 * Calling this method with {@code true} enables legacy behaviour, specifically:
1233 * <ul>
1234 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1235 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1236 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1237 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1238 * underlying the VPN.</li>
1239 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1240 * similarly replaced by the VPN network state.</li>
1241 * <li>Information on current network interfaces passed to NetworkStatsService will not
1242 * include any VPN interfaces.</li>
1243 * </ul>
1244 *
1245 * @param enabled whether legacy lockdown VPN is enabled or disabled
1246 *
1247 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1248 *
1249 * @hide
1250 */
1251 @RequiresPermission(anyOf = {
1252 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1253 android.Manifest.permission.NETWORK_SETTINGS})
1254 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1255 try {
1256 mService.setLegacyLockdownVpnEnabled(enabled);
1257 } catch (RemoteException e) {
1258 throw e.rethrowFromSystemServer();
1259 }
1260 }
1261
1262 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001263 * Returns details about the currently active default data network
1264 * for a given uid. This is for internal use only to avoid spying
1265 * other apps.
1266 *
1267 * @return a {@link NetworkInfo} object for the current default network
1268 * for the given uid or {@code null} if no default network is
1269 * available for the specified uid.
1270 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001271 * {@hide}
1272 */
paulhu8e96a752019-08-12 16:25:11 +08001273 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001274 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001275 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001276 return getActiveNetworkInfoForUid(uid, false);
1277 }
1278
1279 /** {@hide} */
1280 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001281 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001282 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001283 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001284 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001285 }
1286 }
1287
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001288 /**
1289 * Returns connection status information about a particular
1290 * network type.
1291 *
1292 * @param networkType integer specifying which networkType in
1293 * which you're interested.
1294 * @return a {@link NetworkInfo} object for the requested
1295 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001296 * supported by the device. If {@code networkType} is
1297 * TYPE_VPN and a VPN is active for the calling app,
1298 * then this method will try to return one of the
1299 * underlying networks for the VPN or null if the
1300 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001301 *
Paul Jensendda8e592015-03-18 12:23:02 -04001302 * @deprecated This method does not support multiple connected networks
1303 * of the same type. Use {@link #getAllNetworks} and
1304 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001305 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001306 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001307 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001308 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001309 public NetworkInfo getNetworkInfo(int networkType) {
1310 try {
1311 return mService.getNetworkInfo(networkType);
1312 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001313 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001314 }
1315 }
1316
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001317 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001318 * Returns connection status information about a particular
1319 * Network.
1320 *
1321 * @param network {@link Network} specifying which network
1322 * in which you're interested.
1323 * @return a {@link NetworkInfo} object for the requested
1324 * network or {@code null} if the {@code Network}
1325 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001326 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001327 */
junyulai9826e7f2018-12-13 12:47:51 +08001328 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001329 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001330 @Nullable
1331 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001332 return getNetworkInfoForUid(network, Process.myUid(), false);
1333 }
1334
1335 /** {@hide} */
1336 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001337 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001338 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001339 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001340 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001341 }
1342 }
1343
1344 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001345 * Returns connection status information about all network
1346 * types supported by the device.
1347 *
1348 * @return an array of {@link NetworkInfo} objects. Check each
1349 * {@link NetworkInfo#getType} for which type each applies.
1350 *
Paul Jensendda8e592015-03-18 12:23:02 -04001351 * @deprecated This method does not support multiple connected networks
1352 * of the same type. Use {@link #getAllNetworks} and
1353 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001354 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001355 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001356 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001357 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001358 public NetworkInfo[] getAllNetworkInfo() {
1359 try {
1360 return mService.getAllNetworkInfo();
1361 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001362 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001363 }
1364 }
1365
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001366 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001367 * Returns the {@link Network} object currently serving a given type, or
1368 * null if the given type is not connected.
1369 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001370 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001371 * @deprecated This method does not support multiple connected networks
1372 * of the same type. Use {@link #getAllNetworks} and
1373 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001374 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001375 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001376 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001377 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001378 public Network getNetworkForType(int networkType) {
1379 try {
1380 return mService.getNetworkForType(networkType);
1381 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001382 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001383 }
1384 }
1385
1386 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001387 * Returns an array of all {@link Network} currently tracked by the
1388 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001389 *
1390 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001391 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001392 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001393 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001394 public Network[] getAllNetworks() {
1395 try {
1396 return mService.getAllNetworks();
1397 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001398 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001399 }
1400 }
1401
1402 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001403 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001404 * the Networks that applications run by the given user will use by default.
1405 * @hide
1406 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001407 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001408 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1409 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001410 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001411 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001412 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001413 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001414 }
1415 }
1416
1417 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001418 * Returns the IP information for the current default network.
1419 *
1420 * @return a {@link LinkProperties} object describing the IP info
1421 * for the current default network, or {@code null} if there
1422 * is no current default network.
1423 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001424 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001425 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1426 * value of {@link #getActiveNetwork()} instead. In particular,
1427 * this method will return non-null LinkProperties even if the
1428 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001429 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001430 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001431 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001432 public LinkProperties getActiveLinkProperties() {
1433 try {
1434 return mService.getActiveLinkProperties();
1435 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001436 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001437 }
1438 }
1439
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001440 /**
1441 * Returns the IP information for a given network type.
1442 *
1443 * @param networkType the network type of interest.
1444 * @return a {@link LinkProperties} object describing the IP info
1445 * for the given networkType, or {@code null} if there is
1446 * no current default network.
1447 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001448 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001449 * @deprecated This method does not support multiple connected networks
1450 * of the same type. Use {@link #getAllNetworks},
1451 * {@link #getNetworkInfo(android.net.Network)}, and
1452 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001453 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001454 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001455 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001456 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001457 public LinkProperties getLinkProperties(int networkType) {
1458 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001459 return mService.getLinkPropertiesForType(networkType);
1460 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001461 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001462 }
1463 }
1464
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001465 /**
1466 * Get the {@link LinkProperties} for the given {@link Network}. This
1467 * will return {@code null} if the network is unknown.
1468 *
1469 * @param network The {@link Network} object identifying the network in question.
1470 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001471 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001472 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001473 @Nullable
1474 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001475 try {
1476 return mService.getLinkProperties(network);
1477 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001478 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001479 }
1480 }
1481
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001482 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001483 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001484 * will return {@code null} if the network is unknown.
1485 *
1486 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001487 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001488 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001489 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001490 @Nullable
1491 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001492 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001493 return mService.getNetworkCapabilities(
1494 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001495 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001496 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001497 }
1498 }
1499
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001500 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001501 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001502 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1503 * portal is present.
1504 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1505 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1506 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001507 * The system network validation may be using different strategies to detect captive portals,
1508 * so this method does not necessarily return a URL used by the system. It only returns a URL
1509 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001510 *
Udam Sainicd645462016-01-04 12:16:14 -08001511 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001512 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1513 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001514 */
paulhu8e96a752019-08-12 16:25:11 +08001515 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001516 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001517 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001518 public String getCaptivePortalServerUrl() {
1519 try {
1520 return mService.getCaptivePortalServerUrl();
1521 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001522 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001523 }
1524 }
1525
1526 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001527 * Tells the underlying networking system that the caller wants to
1528 * begin using the named feature. The interpretation of {@code feature}
1529 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001530 *
1531 * <p>This method requires the caller to hold either the
1532 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1533 * or the ability to modify system settings as determined by
1534 * {@link android.provider.Settings.System#canWrite}.</p>
1535 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001536 * @param networkType specifies which network the request pertains to
1537 * @param feature the name of the feature to be used
1538 * @return an integer value representing the outcome of the request.
1539 * The interpretation of this value is specific to each networking
1540 * implementation+feature combination, except that the value {@code -1}
1541 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001542 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001543 * @deprecated Deprecated in favor of the cleaner
1544 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001545 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001546 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001547 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001548 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001549 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001550 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001551 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001552 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1553 if (netCap == null) {
1554 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1555 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001556 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001557 }
1558
1559 NetworkRequest request = null;
1560 synchronized (sLegacyRequests) {
1561 LegacyRequest l = sLegacyRequests.get(netCap);
1562 if (l != null) {
1563 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1564 renewRequestLocked(l);
1565 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001566 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001567 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001568 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001569 }
1570 }
1571
1572 request = requestNetworkForFeatureLocked(netCap);
1573 }
1574 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001575 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001576 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001577 } else {
1578 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001579 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001580 }
1581 }
1582
1583 /**
1584 * Tells the underlying networking system that the caller is finished
1585 * using the named feature. The interpretation of {@code feature}
1586 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001587 *
1588 * <p>This method requires the caller to hold either the
1589 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1590 * or the ability to modify system settings as determined by
1591 * {@link android.provider.Settings.System#canWrite}.</p>
1592 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001593 * @param networkType specifies which network the request pertains to
1594 * @param feature the name of the feature that is no longer needed
1595 * @return an integer value representing the outcome of the request.
1596 * The interpretation of this value is specific to each networking
1597 * implementation+feature combination, except that the value {@code -1}
1598 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001599 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001600 * @deprecated Deprecated in favor of the cleaner
1601 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001602 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001603 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001604 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001605 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001606 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001607 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001608 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001609 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1610 if (netCap == null) {
1611 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1612 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001613 return -1;
1614 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001615
Paul Jensen49f74a32014-12-17 10:39:34 -05001616 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001617 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001618 }
1619 return 1;
1620 }
1621
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001622 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001623 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1624 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001625 switch (feature) {
1626 case "enableCBS":
1627 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1628 case "enableDUN":
1629 case "enableDUNAlways":
1630 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1631 case "enableFOTA":
1632 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1633 case "enableHIPRI":
1634 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1635 case "enableIMS":
1636 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1637 case "enableMMS":
1638 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1639 case "enableSUPL":
1640 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1641 default:
1642 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001643 }
Erik Klinece55eb12017-01-26 18:08:28 +09001644 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1645 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001646 }
1647 return null;
1648 }
1649
Robert Greenwalt802c1102014-06-02 15:32:02 -07001650 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001651 if (netCap == null) return TYPE_NONE;
1652 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1653 return TYPE_MOBILE_CBS;
1654 }
1655 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1656 return TYPE_MOBILE_IMS;
1657 }
1658 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1659 return TYPE_MOBILE_FOTA;
1660 }
1661 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1662 return TYPE_MOBILE_DUN;
1663 }
1664 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1665 return TYPE_MOBILE_SUPL;
1666 }
1667 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1668 return TYPE_MOBILE_MMS;
1669 }
1670 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1671 return TYPE_MOBILE_HIPRI;
1672 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001673 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1674 return TYPE_WIFI_P2P;
1675 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001676 return TYPE_NONE;
1677 }
1678
1679 private static class LegacyRequest {
1680 NetworkCapabilities networkCapabilities;
1681 NetworkRequest networkRequest;
1682 int expireSequenceNumber;
1683 Network currentNetwork;
1684 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001685
1686 private void clearDnsBinding() {
1687 if (currentNetwork != null) {
1688 currentNetwork = null;
1689 setProcessDefaultNetworkForHostResolution(null);
1690 }
1691 }
1692
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001693 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001694 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001695 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001696 currentNetwork = network;
1697 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001698 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001699 }
1700 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001701 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001702 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001703 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1704 }
1705 };
1706 }
1707
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001708 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001709 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1710 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001711
1712 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1713 synchronized (sLegacyRequests) {
1714 LegacyRequest l = sLegacyRequests.get(netCap);
1715 if (l != null) return l.networkRequest;
1716 }
1717 return null;
1718 }
1719
1720 private void renewRequestLocked(LegacyRequest l) {
1721 l.expireSequenceNumber++;
1722 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1723 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1724 }
1725
1726 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1727 int ourSeqNum = -1;
1728 synchronized (sLegacyRequests) {
1729 LegacyRequest l = sLegacyRequests.get(netCap);
1730 if (l == null) return;
1731 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001732 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001733 }
1734 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1735 }
1736
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001737 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001738 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1739 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001740 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001741 try {
1742 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001743 } catch (RemoteException e) {
1744 throw e.rethrowFromSystemServer();
1745 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001746 LegacyRequest l = new LegacyRequest();
1747 l.networkCapabilities = netCap;
1748 l.delay = delay;
1749 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001750 l.networkRequest = sendRequestForNetwork(
1751 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001752 if (l.networkRequest == null) return null;
1753 sLegacyRequests.put(netCap, l);
1754 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1755 return l.networkRequest;
1756 }
1757
1758 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1759 if (delay >= 0) {
1760 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001761 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001762 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1763 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001764 }
1765 }
1766
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001767 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001768 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1769 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001770 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001771 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001772 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001773 if (l == null) return false;
1774 unregisterNetworkCallback(l.networkCallback);
1775 l.clearDnsBinding();
1776 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001777 }
1778
Erik Klinece55eb12017-01-26 18:08:28 +09001779 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1780 static {
1781 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1782 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1783 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1784 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1785 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1786 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1787 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1788 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1789 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1790 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1791 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1792 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1793 }
1794
1795 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1796 static {
1797 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1798 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1799 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1800 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1801 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1802 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1803 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1804 }
1805
1806 /**
1807 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1808 * instance suitable for registering a request or callback. Throws an
1809 * IllegalArgumentException if no mapping from the legacy type to
1810 * NetworkCapabilities is known.
1811 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001812 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1813 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001814 * @hide
1815 */
1816 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1817 final NetworkCapabilities nc = new NetworkCapabilities();
1818
1819 // Map from type to transports.
1820 final int NOT_FOUND = -1;
1821 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichibc1104b2017-05-09 15:19:01 +09001822 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001823 nc.addTransportType(transport);
1824
1825 // Map from type to capabilities.
1826 nc.addCapability(sLegacyTypeToCapability.get(
1827 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1828 nc.maybeMarkCapabilitiesRestricted();
1829 return nc;
1830 }
1831
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001832 /** @hide */
1833 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001834 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001835 public PacketKeepaliveCallback() {
1836 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001837 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001838 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001839 public void onStarted() {}
1840 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001841 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001842 public void onStopped() {}
1843 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001844 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001845 public void onError(int error) {}
1846 }
1847
1848 /**
1849 * Allows applications to request that the system periodically send specific packets on their
1850 * behalf, using hardware offload to save battery power.
1851 *
1852 * To request that the system send keepalives, call one of the methods that return a
1853 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1854 * passing in a non-null callback. If the callback is successfully started, the callback's
1855 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1856 * specifying one of the {@code ERROR_*} constants in this class.
1857 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001858 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1859 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1860 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001861 *
junyulai4c95b082018-12-27 17:25:29 +08001862 * @deprecated Use {@link SocketKeepalive} instead.
1863 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001864 * @hide
1865 */
1866 public class PacketKeepalive {
1867
1868 private static final String TAG = "PacketKeepalive";
1869
1870 /** @hide */
1871 public static final int SUCCESS = 0;
1872
1873 /** @hide */
1874 public static final int NO_KEEPALIVE = -1;
1875
1876 /** @hide */
1877 public static final int BINDER_DIED = -10;
1878
1879 /** The specified {@code Network} is not connected. */
1880 public static final int ERROR_INVALID_NETWORK = -20;
1881 /** The specified IP addresses are invalid. For example, the specified source IP address is
1882 * not configured on the specified {@code Network}. */
1883 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1884 /** The requested port is invalid. */
1885 public static final int ERROR_INVALID_PORT = -22;
1886 /** The packet length is invalid (e.g., too long). */
1887 public static final int ERROR_INVALID_LENGTH = -23;
1888 /** The packet transmission interval is invalid (e.g., too short). */
1889 public static final int ERROR_INVALID_INTERVAL = -24;
1890
1891 /** The hardware does not support this request. */
1892 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001893 /** The hardware returned an error. */
1894 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001895
Nathan Harold0990bc82018-02-14 13:09:45 -08001896 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001897 public static final int NATT_PORT = 4500;
1898
Nathan Harold0990bc82018-02-14 13:09:45 -08001899 /** The minimum interval in seconds between keepalive packet transmissions */
1900 public static final int MIN_INTERVAL = 10;
1901
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001902 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001903 private final ISocketKeepaliveCallback mCallback;
1904 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001905
1906 private volatile Integer mSlot;
1907
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001908 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001909 public void stop() {
1910 try {
junyulai070f9ff2019-01-16 20:23:34 +08001911 mExecutor.execute(() -> {
1912 try {
1913 if (mSlot != null) {
1914 mService.stopKeepalive(mNetwork, mSlot);
1915 }
1916 } catch (RemoteException e) {
1917 Log.e(TAG, "Error stopping packet keepalive: ", e);
1918 throw e.rethrowFromSystemServer();
1919 }
1920 });
1921 } catch (RejectedExecutionException e) {
1922 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001923 }
1924 }
1925
1926 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09001927 Preconditions.checkNotNull(network, "network cannot be null");
1928 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001929 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001930 mExecutor = Executors.newSingleThreadExecutor();
1931 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001932 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001933 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001934 final long token = Binder.clearCallingIdentity();
1935 try {
1936 mExecutor.execute(() -> {
1937 mSlot = slot;
1938 callback.onStarted();
1939 });
1940 } finally {
1941 Binder.restoreCallingIdentity(token);
1942 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001943 }
junyulai070f9ff2019-01-16 20:23:34 +08001944
1945 @Override
1946 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001947 final long token = Binder.clearCallingIdentity();
1948 try {
1949 mExecutor.execute(() -> {
1950 mSlot = null;
1951 callback.onStopped();
1952 });
1953 } finally {
1954 Binder.restoreCallingIdentity(token);
1955 }
junyulai070f9ff2019-01-16 20:23:34 +08001956 mExecutor.shutdown();
1957 }
1958
1959 @Override
1960 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001961 final long token = Binder.clearCallingIdentity();
1962 try {
1963 mExecutor.execute(() -> {
1964 mSlot = null;
1965 callback.onError(error);
1966 });
1967 } finally {
1968 Binder.restoreCallingIdentity(token);
1969 }
junyulai070f9ff2019-01-16 20:23:34 +08001970 mExecutor.shutdown();
1971 }
1972
1973 @Override
1974 public void onDataReceived() {
1975 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1976 // this callback when data is received.
1977 }
1978 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001979 }
1980 }
1981
1982 /**
1983 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1984 *
junyulai4c95b082018-12-27 17:25:29 +08001985 * @deprecated Use {@link #createSocketKeepalive} instead.
1986 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001987 * @hide
1988 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001989 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001990 public PacketKeepalive startNattKeepalive(
1991 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1992 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1993 final PacketKeepalive k = new PacketKeepalive(network, callback);
1994 try {
junyulai070f9ff2019-01-16 20:23:34 +08001995 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001996 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1997 } catch (RemoteException e) {
1998 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001999 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002000 }
2001 return k;
2002 }
2003
Chiachang Wang619319a2021-01-15 11:06:21 +08002004 // Construct an invalid fd.
2005 private ParcelFileDescriptor createInvalidFd() {
2006 final int invalidFd = -1;
2007 return ParcelFileDescriptor.adoptFd(invalidFd);
2008 }
2009
The Android Open Source Project28527d22009-03-03 19:31:44 -08002010 /**
junyulai4c95b082018-12-27 17:25:29 +08002011 * Request that keepalives be started on a IPsec NAT-T socket.
2012 *
2013 * @param network The {@link Network} the socket is on.
2014 * @param socket The socket that needs to be kept alive.
2015 * @param source The source address of the {@link UdpEncapsulationSocket}.
2016 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2017 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2018 * must run callback sequentially, otherwise the order of callbacks cannot be
2019 * guaranteed.
2020 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2021 * changes. Must be extended by applications that use this API.
2022 *
junyulai0835a1e2019-01-08 20:04:33 +08002023 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2024 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08002025 **/
junyulai7e06ad42019-03-04 22:45:36 +08002026 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08002027 @NonNull UdpEncapsulationSocket socket,
2028 @NonNull InetAddress source,
2029 @NonNull InetAddress destination,
2030 @NonNull @CallbackExecutor Executor executor,
2031 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002032 ParcelFileDescriptor dup;
2033 try {
junyulai828dad12019-03-27 11:00:37 +08002034 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2035 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08002036 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2037 } catch (IOException ignored) {
2038 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2039 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002040 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002041 }
2042 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2043 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002044 }
2045
2046 /**
2047 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2048 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2049 *
2050 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002051 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2052 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2053 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002054 * @param source The source address of the {@link UdpEncapsulationSocket}.
2055 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2056 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2057 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2058 * must run callback sequentially, otherwise the order of callbacks cannot be
2059 * guaranteed.
2060 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2061 * changes. Must be extended by applications that use this API.
2062 *
junyulai0835a1e2019-01-08 20:04:33 +08002063 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2064 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002065 * @hide
2066 */
2067 @SystemApi
2068 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002069 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2070 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002071 @NonNull InetAddress source,
2072 @NonNull InetAddress destination,
2073 @NonNull @CallbackExecutor Executor executor,
2074 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002075 ParcelFileDescriptor dup;
2076 try {
junyulai828dad12019-03-27 11:00:37 +08002077 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002078 dup = pfd.dup();
2079 } catch (IOException ignored) {
2080 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2081 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002082 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002083 }
2084 return new NattSocketKeepalive(mService, network, dup,
2085 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002086 }
2087
2088 /**
junyulai0835a1e2019-01-08 20:04:33 +08002089 * Request that keepalives be started on a TCP socket.
2090 * The socket must be established.
2091 *
2092 * @param network The {@link Network} the socket is on.
2093 * @param socket The socket that needs to be kept alive.
2094 * @param executor The executor on which callback will be invoked. This implementation assumes
2095 * the provided {@link Executor} runs the callbacks in sequence with no
2096 * concurrency. Failing this, no guarantee of correctness can be made. It is
2097 * the responsibility of the caller to ensure the executor provides this
2098 * guarantee. A simple way of creating such an executor is with the standard
2099 * tool {@code Executors.newSingleThreadExecutor}.
2100 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2101 * changes. Must be extended by applications that use this API.
2102 *
2103 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2104 * given socket.
2105 * @hide
2106 */
2107 @SystemApi
2108 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002109 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002110 @NonNull Socket socket,
2111 @NonNull Executor executor,
2112 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002113 ParcelFileDescriptor dup;
2114 try {
2115 dup = ParcelFileDescriptor.fromSocket(socket);
2116 } catch (UncheckedIOException ignored) {
2117 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2118 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002119 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002120 }
2121 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002122 }
2123
2124 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002125 * Ensure that a network route exists to deliver traffic to the specified
2126 * host via the specified network interface. An attempt to add a route that
2127 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002128 *
2129 * <p>This method requires the caller to hold either the
2130 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2131 * or the ability to modify system settings as determined by
2132 * {@link android.provider.Settings.System#canWrite}.</p>
2133 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134 * @param networkType the type of the network over which traffic to the specified
2135 * host is to be routed
2136 * @param hostAddress the IP address of the host to which the route is desired
2137 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002138 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002139 * @deprecated Deprecated in favor of the
2140 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2141 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002142 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002143 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002144 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002145 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002146 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002147 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002148 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002149 }
2150
2151 /**
2152 * Ensure that a network route exists to deliver traffic to the specified
2153 * host via the specified network interface. An attempt to add a route that
2154 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002155 *
2156 * <p>This method requires the caller to hold either the
2157 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2158 * or the ability to modify system settings as determined by
2159 * {@link android.provider.Settings.System#canWrite}.</p>
2160 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002161 * @param networkType the type of the network over which traffic to the specified
2162 * host is to be routed
2163 * @param hostAddress the IP address of the host to which the route is desired
2164 * @return {@code true} on success, {@code false} on failure
2165 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002166 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002167 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002168 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002169 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002170 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002171 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002172 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002173 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002174 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2175 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002176 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002177 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002178 }
2179 }
2180
2181 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002182 * @return the context's attribution tag
2183 */
2184 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2185 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002186 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002187 }
2188
2189 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002190 * Returns the value of the setting for background data usage. If false,
2191 * applications should not use the network if the application is not in the
2192 * foreground. Developers should respect this setting, and check the value
2193 * of this before performing any background data operations.
2194 * <p>
2195 * All applications that have background services that use the network
2196 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002197 * <p>
Scott Main50589142011-10-06 18:32:43 -07002198 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002199 * background data depends on several combined factors, and this method will
2200 * always return {@code true}. Instead, when background data is unavailable,
2201 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002202 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002203 * @return Whether background data usage is allowed.
2204 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002205 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002206 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002207 // assume that background data is allowed; final authority is
2208 // NetworkInfo which may be blocked.
2209 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002210 }
2211
2212 /**
2213 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002214 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002215 * @param allowBackgroundData Whether an application should use data while
2216 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002217 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002218 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2219 * @see #getBackgroundDataSetting()
2220 * @hide
2221 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002222 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002223 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002224 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002225 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002226 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002227
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002228 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002229 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002230 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002231 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002232 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002233 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002234 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002235 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2236 if (tm != null) {
2237 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2238 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2239 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2240 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2241 + " retVal=" + retVal);
2242 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002243 }
Wink Saville689f7042014-12-05 11:10:30 -08002244 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002245 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002246 }
2247
The Android Open Source Project28527d22009-03-03 19:31:44 -08002248 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002249 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002250 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002251 */
2252 public interface OnNetworkActiveListener {
2253 /**
2254 * Called on the main thread of the process to report that the current data network
2255 * has become active, and it is now a good time to perform any pending network
2256 * operations. Note that this listener only tells you when the network becomes
2257 * active; if at any other time you want to know whether it is active (and thus okay
2258 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002259 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002260 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002261 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002262 }
2263
2264 private INetworkManagementService getNetworkManagementService() {
2265 synchronized (this) {
2266 if (mNMService != null) {
2267 return mNMService;
2268 }
2269 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2270 mNMService = INetworkManagementService.Stub.asInterface(b);
2271 return mNMService;
2272 }
2273 }
2274
2275 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002276 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002277
2278 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002279 * Start listening to reports when the system's default data network is active, meaning it is
2280 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2281 * to determine the current state of the system's default network after registering the
2282 * listener.
2283 * <p>
2284 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002285 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002286 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002287 *
2288 * @param l The listener to be told when the network is active.
2289 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002290 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002291 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2292 @Override
2293 public void onNetworkActive() throws RemoteException {
2294 l.onNetworkActive();
2295 }
2296 };
2297
2298 try {
2299 getNetworkManagementService().registerNetworkActivityListener(rl);
2300 mNetworkActivityListeners.put(l, rl);
2301 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002302 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002303 }
2304 }
2305
2306 /**
2307 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002308 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002309 *
2310 * @param l Previously registered listener.
2311 */
Chalard Jean158702d2019-01-07 19:26:34 +09002312 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002313 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichibc1104b2017-05-09 15:19:01 +09002314 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002315 try {
2316 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2317 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002318 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002319 }
2320 }
2321
2322 /**
2323 * Return whether the data network is currently active. An active network means that
2324 * it is currently in a high power state for performing data transmission. On some
2325 * types of networks, it may be expensive to move and stay in such a state, so it is
2326 * more power efficient to batch network traffic together when the radio is already in
2327 * this state. This method tells you whether right now is currently a good time to
2328 * initiate network traffic, as the network is already active.
2329 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002330 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002331 try {
2332 return getNetworkManagementService().isNetworkActive();
2333 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002334 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002335 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002336 }
2337
2338 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002339 * {@hide}
2340 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002341 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002342 mContext = Preconditions.checkNotNull(context, "missing context");
2343 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002344 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002345 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002346 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002347
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002348 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002349 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002350 public static ConnectivityManager from(Context context) {
2351 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2352 }
2353
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002354 /** @hide */
2355 public NetworkRequest getDefaultRequest() {
2356 try {
2357 // This is not racy as the default request is final in ConnectivityService.
2358 return mService.getDefaultRequest();
2359 } catch (RemoteException e) {
2360 throw e.rethrowFromSystemServer();
2361 }
2362 }
2363
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09002364 /* TODO: These permissions checks don't belong in client-side code. Move them to
2365 * services.jar, possibly in com.android.server.net. */
2366
2367 /** {@hide} */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002368 public static final void enforceChangePermission(Context context,
2369 String callingPkg, String callingAttributionTag) {
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002370 int uid = Binder.getCallingUid();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002371 checkAndNoteChangeNetworkStateOperation(context, uid, callingPkg,
2372 callingAttributionTag, true /* throwException */);
2373 }
2374
2375 /**
2376 * Check if the package is a allowed to change the network state. This also accounts that such
2377 * an access happened.
2378 *
2379 * @return {@code true} iff the package is allowed to change the network state.
2380 */
2381 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2382 private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context,
2383 int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag,
2384 boolean throwException) {
2385 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, callingPackage,
2386 throwException);
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002387 }
2388
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002389 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002390 * Check if the package is a allowed to write settings. This also accounts that such an access
2391 * happened.
2392 *
2393 * @return {@code true} iff the package is allowed to write settings.
2394 */
2395 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2396 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2397 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2398 boolean throwException) {
2399 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2400 throwException);
2401 }
2402
2403 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002404 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2405 * situations where a Context pointer is unavailable.
2406 * @hide
2407 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002408 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002409 static ConnectivityManager getInstanceOrNull() {
2410 return sInstance;
2411 }
2412
2413 /**
2414 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2415 * situations where a Context pointer is unavailable.
2416 * @hide
2417 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002418 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002419 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002420 private static ConnectivityManager getInstance() {
2421 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002422 throw new IllegalStateException("No ConnectivityManager yet constructed");
2423 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002424 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002425 }
2426
2427 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002428 * Get the set of tetherable, available interfaces. This list is limited by
2429 * device configuration and current interface existence.
2430 *
2431 * @return an array of 0 or more Strings of tetherable interface names.
2432 *
markchien6ae63e52020-01-21 13:11:06 +08002433 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002434 * {@hide}
2435 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002436 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002437 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002438 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002439 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002440 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002441 }
2442
2443 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002444 * Get the set of tethered interfaces.
2445 *
2446 * @return an array of 0 or more String of currently tethered interface names.
2447 *
markchien6ae63e52020-01-21 13:11:06 +08002448 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002449 * {@hide}
2450 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002451 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002452 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002453 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002454 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002455 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002456 }
2457
2458 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002459 * Get the set of interface names which attempted to tether but
2460 * failed. Re-attempting to tether may cause them to reset to the Tethered
2461 * state. Alternatively, causing the interface to be destroyed and recreated
2462 * may cause them to reset to the available state.
2463 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2464 * information on the cause of the errors.
2465 *
2466 * @return an array of 0 or more String indicating the interface names
2467 * which failed to tether.
2468 *
markchien6ae63e52020-01-21 13:11:06 +08002469 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002470 * {@hide}
2471 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002472 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002473 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002474 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002475 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002476 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002477 }
2478
2479 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002480 * Get the set of tethered dhcp ranges.
2481 *
markchien2e6ba522020-02-14 11:55:48 +08002482 * @deprecated This method is not supported.
2483 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002484 * {@hide}
2485 */
paulhu8e96a752019-08-12 16:25:11 +08002486 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002487 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002488 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002489 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002490 }
2491
2492 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002493 * Attempt to tether the named interface. This will setup a dhcp server
2494 * on the interface, forward and NAT IP packets and forward DNS requests
2495 * to the best active upstream network interface. Note that if no upstream
2496 * IP network interface is available, dhcp will still run and traffic will be
2497 * allowed between the tethered devices and this device, though upstream net
2498 * access will of course fail until an upstream network interface becomes
2499 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002500 *
2501 * <p>This method requires the caller to hold either the
2502 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2503 * or the ability to modify system settings as determined by
2504 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002505 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002506 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2507 * and WifiStateMachine which need direct access. All other clients should use
2508 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2509 * logic.</p>
2510 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002511 * @param iface the interface name to tether.
2512 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002513 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002514 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002515 * {@hide}
2516 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002517 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002518 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002519 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002520 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002521 }
2522
2523 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002524 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002525 *
2526 * <p>This method requires the caller to hold either the
2527 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2528 * or the ability to modify system settings as determined by
2529 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002530 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002531 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2532 * and WifiStateMachine which need direct access. All other clients should use
2533 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2534 * logic.</p>
2535 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002536 * @param iface the interface name to untether.
2537 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2538 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002539 * {@hide}
2540 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002541 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002542 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002543 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002544 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002545 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002546
2547 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002548 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002549 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002550 * due to device configuration.
2551 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002552 * <p>If this app does not have permission to use this API, it will always
2553 * return false rather than throw an exception.</p>
2554 *
2555 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2556 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2557 *
2558 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2559 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2560 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002561 * @return a boolean - {@code true} indicating Tethering is supported.
2562 *
markchien6ae63e52020-01-21 13:11:06 +08002563 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002564 * {@hide}
2565 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002566 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002567 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2568 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002569 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002570 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002571 }
2572
2573 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002574 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002575 *
2576 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002577 * @hide
2578 */
2579 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002580 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002581 public static abstract class OnStartTetheringCallback {
2582 /**
2583 * Called when tethering has been successfully started.
2584 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002585 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002586
2587 /**
2588 * Called when starting tethering failed.
2589 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002590 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002591 }
2592
2593 /**
2594 * Convenient overload for
2595 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2596 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002597 *
2598 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002599 * @hide
2600 */
2601 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002602 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002603 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002604 public void startTethering(int type, boolean showProvisioningUi,
2605 final OnStartTetheringCallback callback) {
2606 startTethering(type, showProvisioningUi, callback, null);
2607 }
2608
2609 /**
2610 * Runs tether provisioning for the given type if needed and then starts tethering if
2611 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2612 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2613 * schedules tether provisioning re-checks if appropriate.
2614 *
2615 * @param type The type of tethering to start. Must be one of
2616 * {@link ConnectivityManager.TETHERING_WIFI},
2617 * {@link ConnectivityManager.TETHERING_USB}, or
2618 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2619 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2620 * is one. This should be true the first time this function is called and also any time
2621 * the user can see this UI. It gives users information from their carrier about the
2622 * check failing and how they can sign up for tethering if possible.
2623 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2624 * of the result of trying to tether.
2625 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002626 *
2627 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002628 * @hide
2629 */
2630 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002631 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002632 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002633 public void startTethering(int type, boolean showProvisioningUi,
2634 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002635 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002636
markchien91c78e52020-01-20 19:31:56 +08002637 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002638 @Override
markchien91c78e52020-01-20 19:31:56 +08002639 public void execute(Runnable command) {
2640 if (handler == null) {
2641 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002642 } else {
markchien91c78e52020-01-20 19:31:56 +08002643 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002644 }
2645 }
2646 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002647
markchien91c78e52020-01-20 19:31:56 +08002648 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2649 @Override
2650 public void onTetheringStarted() {
2651 callback.onTetheringStarted();
2652 }
2653
2654 @Override
markchienf47d8342020-03-19 13:37:43 +08002655 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002656 callback.onTetheringFailed();
2657 }
2658 };
2659
2660 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002661 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002662
Amos Bianchia9b415a2020-03-04 11:07:38 -08002663 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002664 }
2665
2666 /**
2667 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2668 * applicable.
2669 *
2670 * @param type The type of tethering to stop. Must be one of
2671 * {@link ConnectivityManager.TETHERING_WIFI},
2672 * {@link ConnectivityManager.TETHERING_USB}, or
2673 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002674 *
2675 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002676 * @hide
2677 */
2678 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002679 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002680 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002681 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002682 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002683 }
2684
2685 /**
markchien4ef53e82019-02-27 14:56:11 +08002686 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2687 * upstream status.
2688 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002689 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002690 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002691 */
2692 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002693 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002694 public abstract static class OnTetheringEventCallback {
2695
2696 /**
2697 * Called when tethering upstream changed. This can be called multiple times and can be
2698 * called any time.
2699 *
2700 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2701 * have any upstream.
2702 */
2703 public void onUpstreamChanged(@Nullable Network network) {}
2704 }
2705
markchien6ae63e52020-01-21 13:11:06 +08002706 @GuardedBy("mTetheringEventCallbacks")
2707 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2708 mTetheringEventCallbacks = new ArrayMap<>();
2709
markchien4ef53e82019-02-27 14:56:11 +08002710 /**
2711 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002712 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002713 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2714 * with a null argument. The same callback object cannot be registered twice.
2715 *
2716 * @param executor the executor on which callback will be invoked.
2717 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002718 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002719 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002720 * @hide
2721 */
2722 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002723 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002724 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2725 public void registerTetheringEventCallback(
2726 @NonNull @CallbackExecutor Executor executor,
2727 @NonNull final OnTetheringEventCallback callback) {
2728 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2729
markchien6ae63e52020-01-21 13:11:06 +08002730 final TetheringEventCallback tetherCallback =
2731 new TetheringEventCallback() {
2732 @Override
2733 public void onUpstreamChanged(@Nullable Network network) {
2734 callback.onUpstreamChanged(network);
2735 }
2736 };
2737
2738 synchronized (mTetheringEventCallbacks) {
2739 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002740 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002741 }
markchien4ef53e82019-02-27 14:56:11 +08002742 }
2743
2744 /**
2745 * Remove tethering event callback previously registered with
2746 * {@link #registerTetheringEventCallback}.
2747 *
2748 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002749 *
2750 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002751 * @hide
2752 */
2753 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002754 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002755 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2756 public void unregisterTetheringEventCallback(
2757 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002758 Objects.requireNonNull(callback, "The callback must be non-null");
2759 synchronized (mTetheringEventCallbacks) {
2760 final TetheringEventCallback tetherCallback =
2761 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002762 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002763 }
markchien4ef53e82019-02-27 14:56:11 +08002764 }
2765
2766
2767 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002768 * Get the list of regular expressions that define any tetherable
2769 * USB network interfaces. If USB tethering is not supported by the
2770 * device, this list should be empty.
2771 *
2772 * @return an array of 0 or more regular expression Strings defining
2773 * what interfaces are considered tetherable usb interfaces.
2774 *
markchien6ae63e52020-01-21 13:11:06 +08002775 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002776 * {@hide}
2777 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002778 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002779 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002780 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002781 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002782 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002783 }
2784
2785 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002786 * Get the list of regular expressions that define any tetherable
2787 * Wifi network interfaces. If Wifi tethering is not supported by the
2788 * device, this list should be empty.
2789 *
2790 * @return an array of 0 or more regular expression Strings defining
2791 * what interfaces are considered tetherable wifi interfaces.
2792 *
markchien6ae63e52020-01-21 13:11:06 +08002793 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002794 * {@hide}
2795 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002796 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002797 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002798 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002799 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002800 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002801 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002802
Danica Chang96567052010-08-11 14:54:43 -07002803 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002804 * Get the list of regular expressions that define any tetherable
2805 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2806 * device, this list should be empty.
2807 *
2808 * @return an array of 0 or more regular expression Strings defining
2809 * what interfaces are considered tetherable bluetooth interfaces.
2810 *
markchien6ae63e52020-01-21 13:11:06 +08002811 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2812 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002813 * {@hide}
2814 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002815 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002816 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002817 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002818 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002819 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002820 }
2821
Mike Lockwooded4a1742011-07-19 13:04:47 -07002822 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002823 * Attempt to both alter the mode of USB and Tethering of USB. A
2824 * utility method to deal with some of the complexity of USB - will
2825 * attempt to switch to Rndis and subsequently tether the resulting
2826 * interface on {@code true} or turn off tethering and switch off
2827 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002828 *
2829 * <p>This method requires the caller to hold either the
2830 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2831 * or the ability to modify system settings as determined by
2832 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002833 *
2834 * @param enable a boolean - {@code true} to enable tethering
2835 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002836 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002837 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002838 * {@hide}
2839 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002840 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002841 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002842 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002843 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002844 }
2845
markchien6ae63e52020-01-21 13:11:06 +08002846 /**
2847 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2848 * {@hide}
2849 */
markchien0f45bb92019-01-16 17:44:13 +08002850 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002851 @Deprecated
2852 public static final int TETHER_ERROR_NO_ERROR = TetheringManager.TETHER_ERROR_NO_ERROR;
2853 /**
2854 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2855 * {@hide}
2856 */
2857 @Deprecated
2858 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2859 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2860 /**
2861 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2862 * {@hide}
2863 */
2864 @Deprecated
2865 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2866 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2867 /**
2868 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2869 * {@hide}
2870 */
2871 @Deprecated
2872 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2873 /**
2874 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2875 * {@hide}
2876 */
2877 @Deprecated
2878 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2879 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2880 /**
markchienf47d8342020-03-19 13:37:43 +08002881 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002882 * {@hide}
2883 */
2884 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002885 public static final int TETHER_ERROR_MASTER_ERROR =
2886 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002887 /**
2888 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2889 * {@hide}
2890 */
2891 @Deprecated
2892 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2893 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2894 /**
2895 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2896 * {@hide}
2897 */
2898 @Deprecated
2899 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2900 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2901 /**
markchienf47d8342020-03-19 13:37:43 +08002902 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002903 * {@hide}
2904 */
2905 @Deprecated
2906 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002907 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002908 /**
markchienf47d8342020-03-19 13:37:43 +08002909 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002910 * {@hide}
2911 */
2912 @Deprecated
2913 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002914 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002915 /**
2916 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2917 * {@hide}
2918 */
2919 @Deprecated
2920 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2921 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2922 /**
markchienf47d8342020-03-19 13:37:43 +08002923 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002924 * {@hide}
2925 */
markchien0f45bb92019-01-16 17:44:13 +08002926 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002927 @Deprecated
2928 public static final int TETHER_ERROR_PROVISION_FAILED =
markchienf47d8342020-03-19 13:37:43 +08002929 TetheringManager.TETHER_ERROR_PROVISIONING_FAILED;
markchien6ae63e52020-01-21 13:11:06 +08002930 /**
2931 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2932 * {@hide}
2933 */
2934 @Deprecated
2935 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2936 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2937 /**
2938 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2939 * {@hide}
2940 */
markchien0f45bb92019-01-16 17:44:13 +08002941 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002942 @Deprecated
2943 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN =
2944 TetheringManager.TETHER_ERROR_ENTITLEMENT_UNKNOWN;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002945
2946 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002947 * Get a more detailed error code after a Tethering or Untethering
2948 * request asynchronously failed.
2949 *
2950 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002951 * @return error The error code of the last error tethering or untethering the named
2952 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002953 *
markchien6ae63e52020-01-21 13:11:06 +08002954 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002955 * {@hide}
2956 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002957 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002958 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002959 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002960 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002961 int error = mTetheringManager.getLastTetherError(iface);
2962 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2963 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2964 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2965 // instead.
2966 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2967 }
2968 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002969 }
2970
markchienbf5ab012019-03-06 16:25:00 +08002971 /** @hide */
2972 @Retention(RetentionPolicy.SOURCE)
2973 @IntDef(value = {
2974 TETHER_ERROR_NO_ERROR,
2975 TETHER_ERROR_PROVISION_FAILED,
2976 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2977 })
2978 public @interface EntitlementResultCode {
2979 }
2980
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002981 /**
markchienbf5ab012019-03-06 16:25:00 +08002982 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002983 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002984 *
2985 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002986 * @hide
2987 */
2988 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002989 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002990 public interface OnTetheringEntitlementResultListener {
2991 /**
2992 * Called to notify entitlement result.
2993 *
2994 * @param resultCode an int value of entitlement result. It may be one of
2995 * {@link #TETHER_ERROR_NO_ERROR},
2996 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2997 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2998 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002999 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08003000 }
3001
3002 /**
markchien0f45bb92019-01-16 17:44:13 +08003003 * Get the last value of the entitlement check on this downstream. If the cached value is
3004 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3005 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3006 * guaranteed that the UI-based entitlement check will complete in any specific time period
3007 * and may in fact never complete. Any successful entitlement check the platform performs for
3008 * any reason will update the cached value.
3009 *
3010 * @param type the downstream type of tethering. Must be one of
3011 * {@link #TETHERING_WIFI},
3012 * {@link #TETHERING_USB}, or
3013 * {@link #TETHERING_BLUETOOTH}.
3014 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08003015 * @param executor the executor on which callback will be invoked.
3016 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3017 * notify the caller of the result of entitlement check. The listener may be called zero
3018 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08003019 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08003020 * {@hide}
3021 */
3022 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08003023 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08003024 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08003025 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3026 @NonNull @CallbackExecutor Executor executor,
3027 @NonNull final OnTetheringEntitlementResultListener listener) {
3028 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
3029 ResultReceiver wrappedListener = new ResultReceiver(null) {
3030 @Override
3031 protected void onReceiveResult(int resultCode, Bundle resultData) {
3032 Binder.withCleanCallingIdentity(() ->
3033 executor.execute(() -> {
Jeremy Klein7e7c7422019-03-12 13:32:08 -07003034 listener.onTetheringEntitlementResult(resultCode);
markchienbf5ab012019-03-06 16:25:00 +08003035 }));
3036 }
3037 };
3038
Amos Bianchia9b415a2020-03-04 11:07:38 -08003039 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08003040 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08003041 }
3042
3043 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003044 * Report network connectivity status. This is currently used only
3045 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003046 * <p>This method requires the caller to hold the permission
3047 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003048 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003049 * @param networkType The type of network you want to report on
3050 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003051 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003052 * {@hide}
3053 */
3054 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003055 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003056 try {
3057 mService.reportInetCondition(networkType, percentage);
3058 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003059 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003060 }
3061 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003062
3063 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003064 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003065 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003066 * the framework to re-evaluate network connectivity and/or switch to another
3067 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003068 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003069 * @param network The {@link Network} the application was attempting to use
3070 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003071 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3072 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003073 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003074 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003075 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003076 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003077 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003078 // One of these will be ignored because it matches system's current state.
3079 // The other will trigger the necessary reevaluation.
3080 mService.reportNetworkConnectivity(network, true);
3081 mService.reportNetworkConnectivity(network, false);
3082 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003083 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003084 }
3085 }
3086
3087 /**
3088 * Report to the framework whether a network has working connectivity.
3089 * This provides a hint to the system that a particular network is providing
3090 * working connectivity or not. In response the framework may re-evaluate
3091 * the network's connectivity and might take further action thereafter.
3092 *
3093 * @param network The {@link Network} the application was attempting to use
3094 * or {@code null} to indicate the current default network.
3095 * @param hasConnectivity {@code true} if the application was able to successfully access the
3096 * Internet using {@code network} or {@code false} if not.
3097 */
Chalard Jean158702d2019-01-07 19:26:34 +09003098 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003099 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003100 try {
3101 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003102 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003103 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003104 }
3105 }
3106
3107 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003108 * Set a network-independent global http proxy. This is not normally what you want
3109 * for typical HTTP proxies - they are general network dependent. However if you're
3110 * doing something unusual like general internal filtering this may be useful. On
3111 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003112 *
3113 * @param p A {@link ProxyInfo} object defining the new global
3114 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003115 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003116 */
paulhu8e96a752019-08-12 16:25:11 +08003117 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04003118 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003119 try {
3120 mService.setGlobalProxy(p);
3121 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003122 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003123 }
3124 }
3125
3126 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003127 * Retrieve any network-independent global HTTP proxy.
3128 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003129 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003130 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003131 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003132 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003133 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003134 try {
3135 return mService.getGlobalProxy();
3136 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003137 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003138 }
3139 }
3140
3141 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003142 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3143 * network-specific HTTP proxy. If {@code network} is null, the
3144 * network-specific proxy returned is the proxy of the default active
3145 * network.
3146 *
3147 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3148 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3149 * or when {@code network} is {@code null},
3150 * the {@code ProxyInfo} for the default active network. Returns
3151 * {@code null} when no proxy applies or the caller doesn't have
3152 * permission to use {@code network}.
3153 * @hide
3154 */
3155 public ProxyInfo getProxyForNetwork(Network network) {
3156 try {
3157 return mService.getProxyForNetwork(network);
3158 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003159 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003160 }
3161 }
3162
3163 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003164 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3165 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003166 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003167 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003168 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003169 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003170 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003171 */
Chalard Jean158702d2019-01-07 19:26:34 +09003172 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003173 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003174 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003175 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003176
3177 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003178 * Returns true if the hardware supports the given network type
3179 * else it returns false. This doesn't indicate we have coverage
3180 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003181 * hardware supports it. For example a GSM phone without a SIM
3182 * should still return {@code true} for mobile data, but a wifi only
3183 * tablet would return {@code false}.
3184 *
3185 * @param networkType The network type we'd like to check
3186 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003187 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003188 * @hide
3189 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003190 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003191 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003192 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003193 public boolean isNetworkSupported(int networkType) {
3194 try {
3195 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003196 } catch (RemoteException e) {
3197 throw e.rethrowFromSystemServer();
3198 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003199 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003200
3201 /**
3202 * Returns if the currently active data network is metered. A network is
3203 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003204 * that connection due to monetary costs, data limitations or
3205 * battery/performance issues. You should check this before doing large
3206 * data transfers, and warn the user or delay the operation until another
3207 * network is available.
3208 *
3209 * @return {@code true} if large transfers should be avoided, otherwise
3210 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003211 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003212 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003213 public boolean isActiveNetworkMetered() {
3214 try {
3215 return mService.isActiveNetworkMetered();
3216 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003217 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003218 }
3219 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003220
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003221 /**
3222 * If the LockdownVpn mechanism is enabled, updates the vpn
3223 * with a reload of its profile.
3224 *
3225 * @return a boolean with {@code} indicating success
3226 *
3227 * <p>This method can only be called by the system UID
3228 * {@hide}
3229 */
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003230 public boolean updateLockdownVpn() {
3231 try {
3232 return mService.updateLockdownVpn();
3233 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003234 throw e.rethrowFromSystemServer();
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003235 }
3236 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07003237
3238 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003239 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003240 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003241 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003242 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003243 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003244 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003245 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003246 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003247 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003248 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003249 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003250 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003251 }
3252 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003253
3254 /**
3255 * Set the value for enabling/disabling airplane mode
3256 *
3257 * @param enable whether to enable airplane mode or not
3258 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003259 * @hide
3260 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003261 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003262 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003263 android.Manifest.permission.NETWORK_SETTINGS,
3264 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3265 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003266 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003267 public void setAirplaneMode(boolean enable) {
3268 try {
3269 mService.setAirplaneMode(enable);
3270 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003271 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003272 }
3273 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003274
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003275 /**
3276 * Registers the specified {@link NetworkProvider}.
3277 * Each listener must only be registered once. The listener can be unregistered with
3278 * {@link #unregisterNetworkProvider}.
3279 *
3280 * @param provider the provider to register
3281 * @return the ID of the provider. This ID must be used by the provider when registering
3282 * {@link android.net.NetworkAgent}s.
3283 * @hide
3284 */
3285 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003286 @RequiresPermission(anyOf = {
3287 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3288 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003289 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3290 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003291 throw new IllegalStateException("NetworkProviders can only be registered once");
3292 }
3293
3294 try {
3295 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3296 provider.getName());
3297 provider.setProviderId(providerId);
3298 } catch (RemoteException e) {
3299 throw e.rethrowFromSystemServer();
3300 }
3301 return provider.getProviderId();
3302 }
3303
3304 /**
3305 * Unregisters the specified NetworkProvider.
3306 *
3307 * @param provider the provider to unregister
3308 * @hide
3309 */
3310 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003311 @RequiresPermission(anyOf = {
3312 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3313 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003314 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3315 try {
3316 mService.unregisterNetworkProvider(provider.getMessenger());
3317 } catch (RemoteException e) {
3318 throw e.rethrowFromSystemServer();
3319 }
3320 provider.setProviderId(NetworkProvider.ID_NONE);
3321 }
3322
3323
3324 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003325 @RequiresPermission(anyOf = {
3326 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3327 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003328 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3329 try {
3330 mService.declareNetworkRequestUnfulfillable(request);
3331 } catch (RemoteException e) {
3332 throw e.rethrowFromSystemServer();
3333 }
3334 }
3335
Chalard Jean29d06db2018-05-02 21:14:54 +09003336 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3337 // of dependent changes that would conflict throughout the automerger graph. Having this
3338 // temporarily helps with the process of going through with all these dependent changes across
3339 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003340 /**
3341 * @hide
3342 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003343 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003344 */
paulhub6ba8e82020-03-04 09:43:41 +08003345 @RequiresPermission(anyOf = {
3346 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3347 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003348 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003349 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003350 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003351 }
3352
3353 /**
3354 * @hide
3355 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003356 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003357 */
paulhub6ba8e82020-03-04 09:43:41 +08003358 @RequiresPermission(anyOf = {
3359 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3360 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003361 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003362 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003363 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003364 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003365 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003366 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003367 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003368 }
3369
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003370 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003371 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3372 * changes. Should be extended by applications wanting notifications.
3373 *
3374 * A {@code NetworkCallback} is registered by calling
3375 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3376 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003377 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003378 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3379 * A {@code NetworkCallback} should be registered at most once at any time.
3380 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003381 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003382 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003383 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003384 * Called when the framework connects to a new network to evaluate whether it satisfies this
3385 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3386 * callback. There is no guarantee that this new network will satisfy any requests, or that
3387 * the network will stay connected for longer than the time necessary to evaluate it.
3388 * <p>
3389 * Most applications <b>should not</b> act on this callback, and should instead use
3390 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3391 * the framework in properly evaluating the network &mdash; for example, an application that
3392 * can automatically log in to a captive portal without user intervention.
3393 *
3394 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003395 *
3396 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003397 */
paulhu1a407652019-03-22 16:35:06 +08003398 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003399
3400 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003401 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003402 * This callback may be called more than once if the {@link Network} that is
3403 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003404 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003405 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003406 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3407 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003408 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003409 * @hide
3410 */
paulhu1a407652019-03-22 16:35:06 +08003411 public void onAvailable(@NonNull Network network,
3412 @NonNull NetworkCapabilities networkCapabilities,
3413 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003414 // Internally only this method is called when a new network is available, and
3415 // it calls the callback in the same way and order that older versions used
3416 // to call so as not to change the behavior.
3417 onAvailable(network);
3418 if (!networkCapabilities.hasCapability(
3419 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3420 onNetworkSuspended(network);
3421 }
3422 onCapabilitiesChanged(network, networkCapabilities);
3423 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003424 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003425 }
3426
3427 /**
3428 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003429 *
3430 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3431 * be available at the same time, and onAvailable will be called for each of these as they
3432 * appear.
3433 *
3434 * <p>For callbacks registered with {@link #requestNetwork} and
3435 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3436 * is the new best network for this request and is now tracked by this callback ; this
3437 * callback will no longer receive method calls about other networks that may have been
3438 * passed to this method previously. The previously-best network may have disconnected, or
3439 * it may still be around and the newly-best network may simply be better.
3440 *
3441 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3442 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3443 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3444 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3445 *
3446 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3447 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3448 * this callback as this is prone to race conditions (there is no guarantee the objects
3449 * returned by these methods will be current). Instead, wait for a call to
3450 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3451 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3452 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003453 *
3454 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003455 */
paulhu1a407652019-03-22 16:35:06 +08003456 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003457
3458 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003459 * Called when the network is about to be lost, typically because there are no outstanding
3460 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3461 * with the new replacement network for graceful handover. This method is not guaranteed
3462 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3463 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003464 *
Chalard Jean01378b62019-08-30 16:27:28 +09003465 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3466 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3467 * this callback as this is prone to race conditions ; calling these methods while in a
3468 * callback may return an outdated or even a null object.
3469 *
3470 * @param network The {@link Network} that is about to be lost.
3471 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3472 * connected for graceful handover; note that the network may still
3473 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003474 */
paulhu1a407652019-03-22 16:35:06 +08003475 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003476
3477 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003478 * Called when a network disconnects or otherwise no longer satisfies this request or
3479 * callback.
3480 *
3481 * <p>If the callback was registered with requestNetwork() or
3482 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3483 * returned by onAvailable() when that network is lost and no other network satisfies
3484 * the criteria of the request.
3485 *
3486 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3487 * each network which no longer satisfies the criteria of the callback.
3488 *
3489 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3490 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3491 * this callback as this is prone to race conditions ; calling these methods while in a
3492 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003493 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003494 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003495 */
paulhu1a407652019-03-22 16:35:06 +08003496 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003497
3498 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003499 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003500 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3501 * requested network request cannot be fulfilled (whether or not a timeout was
3502 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003503 * {@link NetworkRequest} will have already been removed and released, as if
3504 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003505 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003506 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003507
3508 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003509 * Called when the network corresponding to this request changes capabilities but still
3510 * satisfies the requested criteria.
3511 *
3512 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3513 * to be called immediately after {@link #onAvailable}.
3514 *
3515 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3516 * ConnectivityManager methods in this callback as this is prone to race conditions :
3517 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003518 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003519 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003520 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3521 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003522 */
paulhu1a407652019-03-22 16:35:06 +08003523 public void onCapabilitiesChanged(@NonNull Network network,
3524 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003525
3526 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003527 * Called when the network corresponding to this request changes {@link LinkProperties}.
3528 *
3529 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3530 * to be called immediately after {@link #onAvailable}.
3531 *
3532 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3533 * ConnectivityManager methods in this callback as this is prone to race conditions :
3534 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003535 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003536 * @param network The {@link Network} whose link properties have changed.
3537 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003538 */
paulhu1a407652019-03-22 16:35:06 +08003539 public void onLinkPropertiesChanged(@NonNull Network network,
3540 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003541
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003542 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003543 * Called when the network the framework connected to for this request suspends data
3544 * transmission temporarily.
3545 *
3546 * <p>This generally means that while the TCP connections are still live temporarily
3547 * network data fails to transfer. To give a specific example, this is used on cellular
3548 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3549 * means read operations on sockets on this network will block once the buffers are
3550 * drained, and write operations will block once the buffers are full.
3551 *
3552 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3553 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3554 * this callback as this is prone to race conditions (there is no guarantee the objects
3555 * returned by these methods will be current).
3556 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003557 * @hide
3558 */
paulhu1a407652019-03-22 16:35:06 +08003559 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003560
3561 /**
3562 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003563 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3564 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003565
3566 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3567 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3568 * this callback as this is prone to race conditions : calling these methods while in a
3569 * callback may return an outdated or even a null object.
3570 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003571 * @hide
3572 */
paulhu1a407652019-03-22 16:35:06 +08003573 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003574
junyulaif2c67e42018-08-07 19:50:45 +08003575 /**
3576 * Called when access to the specified network is blocked or unblocked.
3577 *
Chalard Jean01378b62019-08-30 16:27:28 +09003578 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3579 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3580 * this callback as this is prone to race conditions : calling these methods while in a
3581 * callback may return an outdated or even a null object.
3582 *
junyulaif2c67e42018-08-07 19:50:45 +08003583 * @param network The {@link Network} whose blocked status has changed.
3584 * @param blocked The blocked status of this {@link Network}.
3585 */
junyulai7e06ad42019-03-04 22:45:36 +08003586 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003587
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003588 private NetworkRequest networkRequest;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003589 }
3590
Hugo Benichia590ab82017-05-11 13:16:17 +09003591 /**
3592 * Constant error codes used by ConnectivityService to communicate about failures and errors
3593 * across a Binder boundary.
3594 * @hide
3595 */
3596 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003597 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003598 }
3599
3600 /** @hide */
3601 public static class TooManyRequestsException extends RuntimeException {}
3602
3603 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3604 switch (e.errorCode) {
3605 case Errors.TOO_MANY_REQUESTS:
3606 return new TooManyRequestsException();
3607 default:
3608 Log.w(TAG, "Unknown service error code " + e.errorCode);
3609 return new RuntimeException(e);
3610 }
3611 }
3612
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003613 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003614 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003615 public static final int CALLBACK_PRECHECK = BASE + 1;
3616 /** @hide */
3617 public static final int CALLBACK_AVAILABLE = BASE + 2;
3618 /** @hide arg1 = TTL */
3619 public static final int CALLBACK_LOSING = BASE + 3;
3620 /** @hide */
3621 public static final int CALLBACK_LOST = BASE + 4;
3622 /** @hide */
3623 public static final int CALLBACK_UNAVAIL = BASE + 5;
3624 /** @hide */
3625 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3626 /** @hide */
3627 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003628 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003629 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003630 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003631 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003632 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003633 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003634 /** @hide */
3635 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003636
Erik Kline155a59a2015-11-25 12:49:38 +09003637 /** @hide */
3638 public static String getCallbackName(int whichCallback) {
3639 switch (whichCallback) {
3640 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3641 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3642 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3643 case CALLBACK_LOST: return "CALLBACK_LOST";
3644 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3645 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3646 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003647 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3648 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3649 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003650 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003651 default:
3652 return Integer.toString(whichCallback);
3653 }
3654 }
3655
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003656 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003657 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003658 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003659
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003660 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003661 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003662 }
3663
Hugo Benichifd44e912017-02-02 17:02:36 +09003664 CallbackHandler(Handler handler) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003665 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003666 }
3667
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003668 @Override
3669 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003670 if (message.what == EXPIRE_LEGACY_REQUEST) {
3671 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3672 return;
3673 }
3674
3675 final NetworkRequest request = getObject(message, NetworkRequest.class);
3676 final Network network = getObject(message, Network.class);
3677 final NetworkCallback callback;
3678 synchronized (sCallbacks) {
3679 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003680 if (callback == null) {
3681 Log.w(TAG,
3682 "callback not found for " + getCallbackName(message.what) + " message");
3683 return;
3684 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003685 if (message.what == CALLBACK_UNAVAIL) {
3686 sCallbacks.remove(request);
3687 callback.networkRequest = ALREADY_UNREGISTERED;
3688 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003689 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003690 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003691 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003692 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003693
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003694 switch (message.what) {
3695 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003696 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003697 break;
3698 }
3699 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003700 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3701 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003702 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003703 break;
3704 }
3705 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003706 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003707 break;
3708 }
3709 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003710 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003711 break;
3712 }
3713 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003714 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003715 break;
3716 }
3717 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003718 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3719 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003720 break;
3721 }
3722 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003723 LinkProperties lp = getObject(message, LinkProperties.class);
3724 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003725 break;
3726 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003727 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003728 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003729 break;
3730 }
3731 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003732 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003733 break;
3734 }
junyulaif2c67e42018-08-07 19:50:45 +08003735 case CALLBACK_BLK_CHANGED: {
3736 boolean blocked = message.arg1 != 0;
3737 callback.onBlockedStatusChanged(network, blocked);
3738 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003739 }
3740 }
3741
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003742 private <T> T getObject(Message msg, Class<T> c) {
3743 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003744 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003745 }
3746
Hugo Benichifd44e912017-02-02 17:02:36 +09003747 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003748 synchronized (sCallbacks) {
3749 if (sCallbackHandler == null) {
3750 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003751 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003752 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003753 }
3754 }
3755
Hugo Benichibc4ac972017-02-03 14:18:44 +09003756 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3757 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003758
Hugo Benichibc4ac972017-02-03 14:18:44 +09003759 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003760 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003761 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003762 checkCallbackNotNull(callback);
junyulaiad010792021-01-11 16:53:38 +08003763 Preconditions.checkArgument(
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09003764 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3765 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003766 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003767 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003768 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003769 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003770 if (callback.networkRequest != null
3771 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003772 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3773 // and requests (http://b/20701525).
3774 Log.e(TAG, "NetworkCallback was already registered");
3775 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003776 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003777 Binder binder = new Binder();
junyulaiad010792021-01-11 16:53:38 +08003778 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003779 request = mService.listenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003780 need, messenger, binder, callingPackageName,
3781 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003782 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003783 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003784 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3785 callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003786 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003787 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003788 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003789 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003790 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003791 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003792 } catch (RemoteException e) {
3793 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003794 } catch (ServiceSpecificException e) {
3795 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003796 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003797 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003798 }
3799
3800 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003801 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003802 *
markchienfac84a22020-03-18 21:16:15 +08003803 * This API is only for use in internal system code that requests networks with legacy type and
3804 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003805 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003806 *
markchiend6eeffd2020-01-14 00:55:21 +08003807 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003808 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3809 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3810 * be a positive value (i.e. >0).
3811 * @param legacyType to specify the network type(#TYPE_*).
3812 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003813 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3814 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003815 *
3816 * @hide
3817 */
markchiend6eeffd2020-01-14 00:55:21 +08003818 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003819 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003820 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003821 int timeoutMs, int legacyType, @NonNull Handler handler,
3822 @NonNull NetworkCallback networkCallback) {
3823 if (legacyType == TYPE_NONE) {
3824 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3825 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003826 CallbackHandler cbHandler = new CallbackHandler(handler);
3827 NetworkCapabilities nc = request.networkCapabilities;
3828 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003829 }
3830
3831 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003832 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003833 *
Chalard Jean01378b62019-08-30 16:27:28 +09003834 * <p>This method will attempt to find the best network that matches the passed
3835 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3836 * criteria. The platform will evaluate which network is the best at its own discretion.
3837 * Throughput, latency, cost per byte, policy, user preference and other considerations
3838 * may be factored in the decision of what is considered the best network.
3839 *
3840 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3841 * matching this request, while always attempting to match the request to a better network if
3842 * possible. If a better match is found, the platform will switch this request to the now-best
3843 * network and inform the app of the newly best network by invoking
3844 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3845 * will not try to maintain any other network than the best one currently matching the request:
3846 * a network not matching any network request may be disconnected at any time.
3847 *
3848 * <p>For example, an application could use this method to obtain a connected cellular network
3849 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3850 * radio to consume additional power. Or, an application could inform the system that it wants
3851 * a network supporting sending MMSes and have the system let it know about the currently best
3852 * MMS-supporting network through the provided {@link NetworkCallback}.
3853 *
3854 * <p>The status of the request can be followed by listening to the various callbacks described
3855 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3856 * used to direct traffic to the network (although accessing some networks may be subject to
3857 * holding specific permissions). Callers will learn about the specific characteristics of the
3858 * network through
3859 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3860 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3861 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3862 * matching the request at any given time; therefore when a better network matching the request
3863 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3864 * with the new network after which no further updates are given about the previously-best
3865 * network, unless it becomes the best again at some later time. All callbacks are invoked
3866 * in order on the same thread, which by default is a thread created by the framework running
3867 * in the app.
3868 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3869 * callbacks are invoked.
3870 *
3871 * <p>This{@link NetworkRequest} will live until released via
3872 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3873 * which point the system may let go of the network at any time.
3874 *
3875 * <p>A version of this method which takes a timeout is
3876 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3877 * wait for a limited amount of time for the network to become unavailable.
3878 *
Paul Jensenee52d232015-06-16 15:11:58 -04003879 * <p>It is presently unsupported to request a network with mutable
3880 * {@link NetworkCapabilities} such as
3881 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3882 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3883 * as these {@code NetworkCapabilities} represent states that a particular
3884 * network may never attain, and whether a network will attain these states
3885 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003886 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003887 *
3888 * <p>This method requires the caller to hold either the
3889 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3890 * or the ability to modify system settings as determined by
3891 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003892 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003893 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3894 * number of outstanding requests to 100 per app (identified by their UID), shared with
3895 * all variants of this method, of {@link #registerNetworkCallback} as well as
3896 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3897 * Requesting a network with this method will count toward this limit. If this limit is
3898 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3899 * make sure to unregister the callbacks with
3900 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3901 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003902 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003903 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3904 * the callback must not be shared - it uniquely specifies this request.
3905 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003906 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3907 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003908 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003909 */
Chalard Jean158702d2019-01-07 19:26:34 +09003910 public void requestNetwork(@NonNull NetworkRequest request,
3911 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003912 requestNetwork(request, networkCallback, getDefaultHandler());
3913 }
3914
3915 /**
3916 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3917 *
Chalard Jean01378b62019-08-30 16:27:28 +09003918 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3919 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003920 *
Chalard Jean01378b62019-08-30 16:27:28 +09003921 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003922 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3923 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003924 *
3925 * @param request {@link NetworkRequest} describing this request.
3926 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3927 * the callback must not be shared - it uniquely specifies this request.
3928 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003929 */
Chalard Jean158702d2019-01-07 19:26:34 +09003930 public void requestNetwork(@NonNull NetworkRequest request,
3931 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003932 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003933 NetworkCapabilities nc = request.networkCapabilities;
3934 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003935 }
3936
3937 /**
Etan Cohenf67bde92017-03-01 12:47:28 -08003938 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3939 * by a timeout.
3940 *
3941 * This function behaves identically to the non-timed-out version
3942 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3943 * is not found within the given time (in milliseconds) the
3944 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3945 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3946 * not have to be released if timed-out (it is automatically released). Unregistering a
3947 * request that timed out is not an error.
3948 *
3949 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3950 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3951 * for that purpose. Calling this method will attempt to bring up the requested network.
3952 *
Chalard Jean01378b62019-08-30 16:27:28 +09003953 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003954 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3955 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003956 *
3957 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003958 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3959 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003960 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3961 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3962 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003963 */
Chalard Jean158702d2019-01-07 19:26:34 +09003964 public void requestNetwork(@NonNull NetworkRequest request,
3965 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003966 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003967 NetworkCapabilities nc = request.networkCapabilities;
3968 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3969 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003970 }
3971
Hugo Benichifd44e912017-02-02 17:02:36 +09003972 /**
3973 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3974 * by a timeout.
3975 *
Chalard Jean01378b62019-08-30 16:27:28 +09003976 * This method behaves identically to
3977 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3978 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003979 *
Chalard Jean01378b62019-08-30 16:27:28 +09003980 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003981 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3982 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003983 *
3984 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003985 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3986 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003987 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003988 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3989 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003990 */
Chalard Jean158702d2019-01-07 19:26:34 +09003991 public void requestNetwork(@NonNull NetworkRequest request,
3992 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003993 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003994 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003995 NetworkCapabilities nc = request.networkCapabilities;
3996 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003997 }
3998
3999 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004000 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004001 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004002 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08004003 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04004004 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4005 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004006 */
Erik Kline8a826212014-11-19 12:12:24 +09004007 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004008
4009 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004010 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004011 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004012 * {@link android.content.Intent#getParcelableExtra(String)}.
4013 */
Erik Kline8a826212014-11-19 12:12:24 +09004014 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004015
4016
4017 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09004018 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004019 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004020 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004021 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004022 * the request may outlive the calling application and get called back when a suitable
4023 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004024 * <p>
4025 * The operation is an Intent broadcast that goes to a broadcast receiver that
4026 * you registered with {@link Context#registerReceiver} or through the
4027 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4028 * <p>
4029 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09004030 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4031 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004032 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004033 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004034 * Intent to reserve the network or it will be released shortly after the Intent
4035 * is processed.
4036 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04004037 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004038 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004039 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004040 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004041 * The request may be released normally by calling
4042 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04004043 * <p>It is presently unsupported to request a network with either
4044 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4045 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4046 * as these {@code NetworkCapabilities} represent states that a particular
4047 * network may never attain, and whether a network will attain these states
4048 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09004049 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004050 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004051 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4052 * number of outstanding requests to 100 per app (identified by their UID), shared with
4053 * all variants of this method, of {@link #registerNetworkCallback} as well as
4054 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4055 * Requesting a network with this method will count toward this limit. If this limit is
4056 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4057 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4058 * or {@link #releaseNetworkRequest(PendingIntent)}.
4059 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004060 * <p>This method requires the caller to hold either the
4061 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4062 * or the ability to modify system settings as determined by
4063 * {@link android.provider.Settings.System#canWrite}.</p>
4064 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004065 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004066 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004067 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004068 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004069 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4070 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004071 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004072 */
Chalard Jean158702d2019-01-07 19:26:34 +09004073 public void requestNetwork(@NonNull NetworkRequest request,
4074 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004075 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004076 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004077 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004078 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004079 request.networkCapabilities, operation, mContext.getOpPackageName(),
4080 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004081 } catch (RemoteException e) {
4082 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004083 } catch (ServiceSpecificException e) {
4084 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004085 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004086 }
4087
4088 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004089 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4090 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004091 * This method has the same behavior as
4092 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004093 * releasing network resources and disconnecting.
4094 *
4095 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4096 * PendingIntent passed to
4097 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4098 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4099 */
Chalard Jean158702d2019-01-07 19:26:34 +09004100 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004101 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004102 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004103 try {
4104 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004105 } catch (RemoteException e) {
4106 throw e.rethrowFromSystemServer();
4107 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004108 }
4109
Hugo Benichibc1104b2017-05-09 15:19:01 +09004110 private static void checkPendingIntentNotNull(PendingIntent intent) {
4111 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4112 }
4113
4114 private static void checkCallbackNotNull(NetworkCallback callback) {
4115 Preconditions.checkNotNull(callback, "null NetworkCallback");
4116 }
4117
4118 private static void checkTimeout(int timeoutMs) {
4119 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004120 }
4121
4122 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004123 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004124 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004125 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4126 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004127 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004128 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4129 * number of outstanding requests to 100 per app (identified by their UID), shared with
4130 * all variants of this method, of {@link #requestNetwork} as well as
4131 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4132 * Requesting a network with this method will count toward this limit. If this limit is
4133 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4134 * make sure to unregister the callbacks with
4135 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4136 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004137 * @param request {@link NetworkRequest} describing this request.
4138 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4139 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004140 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004141 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004142 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004143 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004144 public void registerNetworkCallback(@NonNull NetworkRequest request,
4145 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004146 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4147 }
4148
4149 /**
4150 * Registers to receive notifications about all networks which satisfy the given
4151 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004152 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4153 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004154 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004155 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4156 * number of outstanding requests to 100 per app (identified by their UID), shared with
4157 * all variants of this method, of {@link #requestNetwork} as well as
4158 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4159 * Requesting a network with this method will count toward this limit. If this limit is
4160 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4161 * make sure to unregister the callbacks with
4162 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4163 *
4164 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004165 * @param request {@link NetworkRequest} describing this request.
4166 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4167 * networks change state.
4168 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004169 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004170 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004171 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004172 public void registerNetworkCallback(@NonNull NetworkRequest request,
4173 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004174 CallbackHandler cbHandler = new CallbackHandler(handler);
4175 NetworkCapabilities nc = request.networkCapabilities;
4176 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004177 }
4178
4179 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004180 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4181 * {@link NetworkRequest}.
4182 *
4183 * This function behaves identically to the version that takes a NetworkCallback, but instead
4184 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4185 * the request may outlive the calling application and get called back when a suitable
4186 * network is found.
4187 * <p>
4188 * The operation is an Intent broadcast that goes to a broadcast receiver that
4189 * you registered with {@link Context#registerReceiver} or through the
4190 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4191 * <p>
4192 * The operation Intent is delivered with two extras, a {@link Network} typed
4193 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4194 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4195 * the original requests parameters.
4196 * <p>
4197 * If there is already a request for this Intent registered (with the equality of
4198 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4199 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4200 * <p>
4201 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004202 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004203 *
4204 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4205 * number of outstanding requests to 100 per app (identified by their UID), shared with
4206 * all variants of this method, of {@link #requestNetwork} as well as
4207 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4208 * Requesting a network with this method will count toward this limit. If this limit is
4209 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4210 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4211 * or {@link #releaseNetworkRequest(PendingIntent)}.
4212 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004213 * @param request {@link NetworkRequest} describing this request.
4214 * @param operation Action to perform when the network is available (corresponds
4215 * to the {@link NetworkCallback#onAvailable} call. Typically
4216 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004217 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004218 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004219 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004220 public void registerNetworkCallback(@NonNull NetworkRequest request,
4221 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004222 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004223 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004224 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004225 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004226 request.networkCapabilities, operation, mContext.getOpPackageName(),
4227 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004228 } catch (RemoteException e) {
4229 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004230 } catch (ServiceSpecificException e) {
4231 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004232 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004233 }
4234
4235 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004236 * Registers to receive notifications about changes in the application's default network. This
4237 * may be a physical network or a virtual network, such as a VPN that applies to the
4238 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004239 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004240 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004241 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4242 * number of outstanding requests to 100 per app (identified by their UID), shared with
4243 * all variants of this method, of {@link #requestNetwork} as well as
4244 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4245 * Requesting a network with this method will count toward this limit. If this limit is
4246 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4247 * make sure to unregister the callbacks with
4248 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4249 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004250 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004251 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004252 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004253 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004254 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004255 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004256 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004257 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4258 }
4259
4260 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004261 * Registers to receive notifications about changes in the application's default network. This
4262 * may be a physical network or a virtual network, such as a VPN that applies to the
4263 * application. The callbacks will continue to be called until either the application exits or
4264 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4265 *
4266 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4267 * number of outstanding requests to 100 per app (identified by their UID), shared with
4268 * all variants of this method, of {@link #requestNetwork} as well as
4269 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4270 * Requesting a network with this method will count toward this limit. If this limit is
4271 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4272 * make sure to unregister the callbacks with
4273 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4274 *
4275 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4276 * application's default network changes.
4277 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4278 * @throws RuntimeException if the app already has too many callbacks registered.
4279 */
4280 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4281 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4282 @NonNull Handler handler) {
4283 CallbackHandler cbHandler = new CallbackHandler(handler);
4284 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4285 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4286 }
4287
4288 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004289 * Registers to receive notifications about changes in the system default network. The callbacks
4290 * will continue to be called until either the application exits or
4291 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004292 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004293 * This method should not be used to determine networking state seen by applications, because in
4294 * many cases, most or even all application traffic may not use the default network directly,
4295 * and traffic from different applications may go on different networks by default. As an
4296 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4297 * and not onto the system default network. Applications or system components desiring to do
4298 * determine network state as seen by applications should use other methods such as
4299 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4300 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004301 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4302 * number of outstanding requests to 100 per app (identified by their UID), shared with
4303 * all variants of this method, of {@link #requestNetwork} as well as
4304 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4305 * Requesting a network with this method will count toward this limit. If this limit is
4306 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4307 * make sure to unregister the callbacks with
4308 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4309 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004310 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4311 * system default network changes.
4312 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004313 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004314 *
4315 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004316 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004317 @SystemApi(client = MODULE_LIBRARIES)
4318 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4319 @RequiresPermission(anyOf = {
4320 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4321 android.Manifest.permission.NETWORK_SETTINGS})
4322 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004323 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004324 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004325 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004326 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004327 }
4328
4329 /**
fenglub00f4882015-04-21 17:12:05 -07004330 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4331 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4332 * network connection for updated bandwidth information. The caller will be notified via
4333 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004334 * method assumes that the caller has previously called
4335 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4336 * changes.
fenglu3f357402015-03-20 11:29:56 -07004337 *
fengluea2d9282015-04-27 14:28:04 -07004338 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004339 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004340 */
Chalard Jean158702d2019-01-07 19:26:34 +09004341 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004342 try {
fenglub00f4882015-04-21 17:12:05 -07004343 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004344 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004345 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004346 }
4347 }
4348
4349 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004350 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004351 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4352 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4353 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004354 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4355 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004356 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004357 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4358 * triggering it as soon as this call returns.
4359 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004360 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004361 */
Chalard Jean158702d2019-01-07 19:26:34 +09004362 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004363 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004364 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004365 final List<NetworkRequest> reqs = new ArrayList<>();
4366 // Find all requests associated to this callback and stop callback triggers immediately.
4367 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4368 synchronized (sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09004369 Preconditions.checkArgument(networkCallback.networkRequest != null,
4370 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004371 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4372 Log.d(TAG, "NetworkCallback was already unregistered");
4373 return;
4374 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004375 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4376 if (e.getValue() == networkCallback) {
4377 reqs.add(e.getKey());
4378 }
4379 }
4380 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4381 for (NetworkRequest r : reqs) {
4382 try {
4383 mService.releaseNetworkRequest(r);
4384 } catch (RemoteException e) {
4385 throw e.rethrowFromSystemServer();
4386 }
4387 // Only remove mapping if rpc was successful.
4388 sCallbacks.remove(r);
4389 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004390 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004391 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004392 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004393
4394 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004395 * Unregisters a callback previously registered via
4396 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4397 *
4398 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4399 * PendingIntent passed to
4400 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4401 * Cannot be null.
4402 */
Chalard Jean158702d2019-01-07 19:26:34 +09004403 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004404 releaseNetworkRequest(operation);
4405 }
4406
4407 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004408 * Informs the system whether it should switch to {@code network} regardless of whether it is
4409 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4410 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4411 * the system default network regardless of any other network that's currently connected. If
4412 * {@code always} is true, then the choice is remembered, so that the next time the user
4413 * connects to this network, the system will switch to it.
4414 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004415 * @param network The network to accept.
4416 * @param accept Whether to accept the network even if unvalidated.
4417 * @param always Whether to remember this choice in the future.
4418 *
4419 * @hide
4420 */
lucaslin2240ef62019-03-12 13:08:03 +08004421 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004422 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4423 try {
4424 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004425 } catch (RemoteException e) {
4426 throw e.rethrowFromSystemServer();
4427 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004428 }
4429
4430 /**
lucaslin2240ef62019-03-12 13:08:03 +08004431 * Informs the system whether it should consider the network as validated even if it only has
4432 * partial connectivity. If {@code accept} is true, then the network will be considered as
4433 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4434 * is remembered, so that the next time the user connects to this network, the system will
4435 * switch to it.
4436 *
4437 * @param network The network to accept.
4438 * @param accept Whether to consider the network as validated even if it has partial
4439 * connectivity.
4440 * @param always Whether to remember this choice in the future.
4441 *
4442 * @hide
4443 */
4444 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4445 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4446 try {
4447 mService.setAcceptPartialConnectivity(network, accept, always);
4448 } catch (RemoteException e) {
4449 throw e.rethrowFromSystemServer();
4450 }
4451 }
4452
4453 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004454 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4455 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4456 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4457 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4458 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004459 * @param network The network to accept.
4460 *
4461 * @hide
4462 */
lucaslin2240ef62019-03-12 13:08:03 +08004463 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004464 public void setAvoidUnvalidated(Network network) {
4465 try {
4466 mService.setAvoidUnvalidated(network);
4467 } catch (RemoteException e) {
4468 throw e.rethrowFromSystemServer();
4469 }
4470 }
4471
4472 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004473 * Requests that the system open the captive portal app on the specified network.
4474 *
4475 * @param network The network to log into.
4476 *
4477 * @hide
4478 */
paulhu8e96a752019-08-12 16:25:11 +08004479 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004480 public void startCaptivePortalApp(Network network) {
4481 try {
4482 mService.startCaptivePortalApp(network);
4483 } catch (RemoteException e) {
4484 throw e.rethrowFromSystemServer();
4485 }
4486 }
4487
4488 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004489 * Requests that the system open the captive portal app with the specified extras.
4490 *
4491 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4492 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004493 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004494 * @param appExtras Extras to include in the app start intent.
4495 * @hide
4496 */
4497 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004498 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004499 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004500 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004501 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004502 } catch (RemoteException e) {
4503 throw e.rethrowFromSystemServer();
4504 }
4505 }
4506
4507 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004508 * Determine whether the device is configured to avoid bad wifi.
4509 * @hide
4510 */
4511 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004512 @RequiresPermission(anyOf = {
4513 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4514 android.Manifest.permission.NETWORK_STACK})
4515 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004516 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004517 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004518 } catch (RemoteException e) {
4519 throw e.rethrowFromSystemServer();
4520 }
4521 }
4522
4523 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004524 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4525 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004526 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4527 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004528 *
4529 * An example of such an operation might be a time-sensitive foreground activity, such as a
4530 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4531 */
4532 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4533
4534 /**
4535 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4536 * a backup channel for traffic that is primarily going over another network.
4537 *
4538 * An example might be maintaining backup connections to peers or servers for the purpose of
4539 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4540 * on backup paths should be negligible compared to the traffic on the main path.
4541 */
4542 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4543
4544 /**
4545 * It is acceptable to use metered data to improve network latency and performance.
4546 */
4547 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4548
4549 /**
4550 * Return value to use for unmetered networks. On such networks we currently set all the flags
4551 * to true.
4552 * @hide
4553 */
4554 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4555 MULTIPATH_PREFERENCE_HANDOVER |
4556 MULTIPATH_PREFERENCE_RELIABILITY |
4557 MULTIPATH_PREFERENCE_PERFORMANCE;
4558
4559 /** @hide */
4560 @Retention(RetentionPolicy.SOURCE)
4561 @IntDef(flag = true, value = {
4562 MULTIPATH_PREFERENCE_HANDOVER,
4563 MULTIPATH_PREFERENCE_RELIABILITY,
4564 MULTIPATH_PREFERENCE_PERFORMANCE,
4565 })
4566 public @interface MultipathPreference {
4567 }
4568
4569 /**
4570 * Provides a hint to the calling application on whether it is desirable to use the
4571 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4572 * for multipath data transfer on this network when it is not the system default network.
4573 * Applications desiring to use multipath network protocols should call this method before
4574 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004575 *
4576 * @param network The network on which the application desires to use multipath data.
4577 * If {@code null}, this method will return the a preference that will generally
4578 * apply to metered networks.
4579 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4580 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004581 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004582 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004583 try {
4584 return mService.getMultipathPreference(network);
4585 } catch (RemoteException e) {
4586 throw e.rethrowFromSystemServer();
4587 }
4588 }
4589
4590 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004591 * Resets all connectivity manager settings back to factory defaults.
4592 * @hide
4593 */
paulhu8e96a752019-08-12 16:25:11 +08004594 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004595 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004596 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004597 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004598 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004599 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004600 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004601 }
4602 }
4603
4604 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004605 * Binds the current process to {@code network}. All Sockets created in the future
4606 * (and not explicitly bound via a bound SocketFactory from
4607 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4608 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4609 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4610 * work and all host name resolutions will fail. This is by design so an application doesn't
4611 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4612 * To clear binding pass {@code null} for {@code network}. Using individually bound
4613 * Sockets created by Network.getSocketFactory().createSocket() and
4614 * performing network-specific host name resolutions via
4615 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004616 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004617 *
4618 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4619 * the current binding.
4620 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4621 */
Chalard Jean158702d2019-01-07 19:26:34 +09004622 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004623 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004624 // instantiated.
4625 return setProcessDefaultNetwork(network);
4626 }
4627
4628 /**
4629 * Binds the current process to {@code network}. All Sockets created in the future
4630 * (and not explicitly bound via a bound SocketFactory from
4631 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4632 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4633 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4634 * work and all host name resolutions will fail. This is by design so an application doesn't
4635 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4636 * To clear binding pass {@code null} for {@code network}. Using individually bound
4637 * Sockets created by Network.getSocketFactory().createSocket() and
4638 * performing network-specific host name resolutions via
4639 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4640 * {@code setProcessDefaultNetwork}.
4641 *
4642 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4643 * the current binding.
4644 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4645 * @deprecated This function can throw {@link IllegalStateException}. Use
4646 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4647 * is a direct replacement.
4648 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004649 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004650 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004651 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004652 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4653
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004654 if (netId != NETID_UNSET) {
4655 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004656 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004657
4658 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4659 return false;
4660 }
4661
4662 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004663 // Set HTTP proxy system properties to match network.
4664 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004665 try {
4666 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4667 } catch (SecurityException e) {
4668 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4669 Log.e(TAG, "Can't set proxy properties", e);
4670 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004671 // Must flush DNS cache as new network may have different DNS resolutions.
4672 InetAddress.clearDnsCache();
4673 // Must flush socket pool as idle sockets will be bound to previous network and may
4674 // cause subsequent fetches to be performed on old network.
4675 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004676 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004677
4678 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004679 }
4680
4681 /**
4682 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004683 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004684 *
4685 * @return {@code Network} to which this process is bound, or {@code null}.
4686 */
Chalard Jean158702d2019-01-07 19:26:34 +09004687 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004688 public Network getBoundNetworkForProcess() {
4689 // Forcing callers to call thru non-static function ensures ConnectivityManager
4690 // instantiated.
4691 return getProcessDefaultNetwork();
4692 }
4693
4694 /**
4695 * Returns the {@link Network} currently bound to this process via
4696 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4697 *
4698 * @return {@code Network} to which this process is bound, or {@code null}.
4699 * @deprecated Using this function can lead to other functions throwing
4700 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4701 * {@code getBoundNetworkForProcess} is a direct replacement.
4702 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004703 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004704 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004705 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004706 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004707 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004708 return new Network(netId);
4709 }
4710
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004711 private void unsupportedStartingFrom(int version) {
4712 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004713 // The getApplicationInfo() call we make below is not supported in system context. Let
4714 // the call through here, and rely on the fact that ConnectivityService will refuse to
4715 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004716 return;
4717 }
4718
4719 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4720 throw new UnsupportedOperationException(
4721 "This method is not supported in target SDK version " + version + " and above");
4722 }
4723 }
4724
4725 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4726 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004727 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004728 // remove these exemptions. Note that this check is not secure, and apps can still access these
4729 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4730 // so is unsupported and may break in the future. http://b/22728205
4731 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004732 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004733 }
4734
Paul Jensen8cdda642014-05-29 10:12:39 -04004735 /**
4736 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004737 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004738 *
4739 * @param network The {@link Network} to bind host resolutions from the current process to, or
4740 * {@code null} to clear the current binding.
4741 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4742 * @hide
4743 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4744 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004745 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004746 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004747 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004748 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004749 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004750 }
Felipe Leme30511352016-01-22 09:44:57 -08004751
4752 /**
4753 * Device is not restricting metered network activity while application is running on
4754 * background.
4755 */
4756 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4757
4758 /**
4759 * Device is restricting metered network activity while application is running on background,
4760 * but application is allowed to bypass it.
4761 * <p>
4762 * In this state, application should take action to mitigate metered network access.
4763 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4764 */
4765 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4766
4767 /**
4768 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004769 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004770 * In this state, application should not try to use the network while running on background,
4771 * because it would be denied.
4772 */
4773 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4774
Felipe Lemed34c9af2016-01-27 14:46:39 -08004775 /**
4776 * A change in the background metered network activity restriction has occurred.
4777 * <p>
4778 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4779 * applies to them.
4780 * <p>
4781 * This is only sent to registered receivers, not manifest receivers.
4782 */
4783 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4784 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4785 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4786
Felipe Leme7e4c1852016-01-25 11:48:04 -08004787 /** @hide */
4788 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004789 @IntDef(flag = false, value = {
4790 RESTRICT_BACKGROUND_STATUS_DISABLED,
4791 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4792 RESTRICT_BACKGROUND_STATUS_ENABLED,
4793 })
Felipe Leme30511352016-01-22 09:44:57 -08004794 public @interface RestrictBackgroundStatus {
4795 }
4796
4797 private INetworkPolicyManager getNetworkPolicyManager() {
4798 synchronized (this) {
4799 if (mNPManager != null) {
4800 return mNPManager;
4801 }
4802 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4803 .getService(Context.NETWORK_POLICY_SERVICE));
4804 return mNPManager;
4805 }
4806 }
4807
4808 /**
4809 * Determines if the calling application is subject to metered network restrictions while
4810 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004811 *
4812 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4813 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4814 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004815 */
4816 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4817 try {
4818 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4819 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004820 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004821 }
4822 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004823
4824 /**
4825 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004826 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4827 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004828 *
4829 * @return Hash of network watchlist config file. Null if config does not exist.
4830 */
Chalard Jean158702d2019-01-07 19:26:34 +09004831 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004832 public byte[] getNetworkWatchlistConfigHash() {
4833 try {
4834 return mService.getNetworkWatchlistConfigHash();
4835 } catch (RemoteException e) {
4836 Log.e(TAG, "Unable to get watchlist config hash");
4837 throw e.rethrowFromSystemServer();
4838 }
4839 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004840
4841 /**
4842 * Returns the {@code uid} of the owner of a network connection.
4843 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004844 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4845 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004846 * @param local The local {@link InetSocketAddress} of a connection.
4847 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004848 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004849 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4850 * android.os.Process#INVALID_UID} if the connection is not found.
4851 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4852 * user.
4853 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004854 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004855 public int getConnectionOwnerUid(
4856 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004857 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4858 try {
4859 return mService.getConnectionOwnerUid(connectionInfo);
4860 } catch (RemoteException e) {
4861 throw e.rethrowFromSystemServer();
4862 }
4863 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004864
4865 private void printStackTrace() {
4866 if (DEBUG) {
4867 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4868 final StringBuffer sb = new StringBuffer();
4869 for (int i = 3; i < callStack.length; i++) {
4870 final String stackTrace = callStack[i].toString();
4871 if (stackTrace == null || stackTrace.contains("android.os")) {
4872 break;
4873 }
4874 sb.append(" [").append(stackTrace).append("]");
4875 }
4876 Log.d(TAG, "StackLog:" + sb.toString());
4877 }
4878 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004879
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004880 /** @hide */
4881 public TestNetworkManager startOrGetTestNetworkManager() {
4882 final IBinder tnBinder;
4883 try {
4884 tnBinder = mService.startOrGetTestNetworkService();
4885 } catch (RemoteException e) {
4886 throw e.rethrowFromSystemServer();
4887 }
4888
4889 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4890 }
4891
4892 /** @hide */
4893 public VpnManager createVpnManager() {
4894 return new VpnManager(mContext, mService);
4895 }
4896
4897 /** @hide */
4898 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4899 return new ConnectivityDiagnosticsManager(mContext, mService);
4900 }
4901
Cody Kestingf53a0752020-04-15 12:33:28 -07004902 /**
4903 * Simulates a Data Stall for the specified Network.
4904 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004905 * <p>This method should only be used for tests.
4906 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004907 * <p>The caller must be the owner of the specified Network.
4908 *
4909 * @param detectionMethod The detection method used to identify the Data Stall.
4910 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4911 * @param network The Network for which a Data Stall is being simluated.
4912 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4913 * @throws SecurityException if the caller is not the owner of the given network.
4914 * @hide
4915 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004916 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004917 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4918 android.Manifest.permission.NETWORK_STACK})
4919 public void simulateDataStall(int detectionMethod, long timestampMillis,
4920 @NonNull Network network, @NonNull PersistableBundle extras) {
4921 try {
4922 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4923 } catch (RemoteException e) {
4924 e.rethrowFromSystemServer();
4925 }
4926 }
James Mattis356a8792020-10-28 21:48:54 -07004927
James Mattis47db0582021-01-01 14:13:35 -08004928 private void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
4929 try {
4930 mService.setOemNetworkPreference(preference);
4931 } catch (RemoteException e) {
4932 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
4933 throw e.rethrowFromSystemServer();
4934 }
James Mattis356a8792020-10-28 21:48:54 -07004935 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004936
4937 @NonNull
4938 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4939
4940 /**
4941 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4942 * receive available QoS events related to the {@link Network} and local ip + port
4943 * specified within socketInfo.
4944 * <p/>
4945 * The same {@link QosCallback} must be unregistered before being registered a second time,
4946 * otherwise {@link QosCallbackRegistrationException} is thrown.
4947 * <p/>
4948 * This API does not, in itself, require any permission if called with a network that is not
4949 * restricted. However, the underlying implementation currently only supports the IMS network,
4950 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4951 * useful, because they'd never be called back on networks that they would have access to.
4952 *
4953 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4954 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4955 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4956 * @throws RuntimeException if the app already has too many callbacks registered.
4957 *
4958 * Exceptions after the time of registration is passed through
4959 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4960 *
4961 * @param socketInfo the socket information used to match QoS events
4962 * @param callback receives qos events that satisfy socketInfo
4963 * @param executor The executor on which the callback will be invoked. The provided
4964 * {@link Executor} must run callback sequentially, otherwise the order of
4965 * callbacks cannot be guaranteed.
4966 *
4967 * @hide
4968 */
4969 @SystemApi
4970 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4971 @NonNull final QosCallback callback,
4972 @CallbackExecutor @NonNull final Executor executor) {
4973 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4974 Objects.requireNonNull(callback, "callback must be non-null");
4975 Objects.requireNonNull(executor, "executor must be non-null");
4976
4977 try {
4978 synchronized (mQosCallbackConnections) {
4979 if (getQosCallbackConnection(callback) == null) {
4980 final QosCallbackConnection connection =
4981 new QosCallbackConnection(this, callback, executor);
4982 mQosCallbackConnections.add(connection);
4983 mService.registerQosSocketCallback(socketInfo, connection);
4984 } else {
4985 Log.e(TAG, "registerQosCallback: Callback already registered");
4986 throw new QosCallbackRegistrationException();
4987 }
4988 }
4989 } catch (final RemoteException e) {
4990 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4991
4992 // The same unregister method method is called for consistency even though nothing
4993 // will be sent to the ConnectivityService since the callback was never successfully
4994 // registered.
4995 unregisterQosCallback(callback);
4996 e.rethrowFromSystemServer();
4997 } catch (final ServiceSpecificException e) {
4998 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4999 unregisterQosCallback(callback);
5000 throw convertServiceException(e);
5001 }
5002 }
5003
5004 /**
5005 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5006 * events once unregistered and can be registered a second time.
5007 * <p/>
5008 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5009 *
5010 * @param callback the callback being unregistered
5011 *
5012 * @hide
5013 */
5014 @SystemApi
5015 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5016 Objects.requireNonNull(callback, "The callback must be non-null");
5017 try {
5018 synchronized (mQosCallbackConnections) {
5019 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5020 if (connection != null) {
5021 connection.stopReceivingMessages();
5022 mService.unregisterQosCallback(connection);
5023 mQosCallbackConnections.remove(connection);
5024 } else {
5025 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5026 }
5027 }
5028 } catch (final RemoteException e) {
5029 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5030 e.rethrowFromSystemServer();
5031 }
5032 }
5033
5034 /**
5035 * Gets the connection related to the callback.
5036 *
5037 * @param callback the callback to look up
5038 * @return the related connection
5039 */
5040 @Nullable
5041 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5042 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5043 // Checking by reference here is intentional
5044 if (connection.getCallback() == callback) {
5045 return connection;
5046 }
5047 }
5048 return null;
5049 }
Junyu Laia62493f2021-01-19 11:10:56 +00005050
5051 /**
5052 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
5053 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5054 * be used to request that the system provide a network without causing the network to be
5055 * in the foreground.
5056 *
5057 * <p>This method will attempt to find the best network that matches the passed
5058 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5059 * criteria. The platform will evaluate which network is the best at its own discretion.
5060 * Throughput, latency, cost per byte, policy, user preference and other considerations
5061 * may be factored in the decision of what is considered the best network.
5062 *
5063 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5064 * matching this request, while always attempting to match the request to a better network if
5065 * possible. If a better match is found, the platform will switch this request to the now-best
5066 * network and inform the app of the newly best network by invoking
5067 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5068 * will not try to maintain any other network than the best one currently matching the request:
5069 * a network not matching any network request may be disconnected at any time.
5070 *
5071 * <p>For example, an application could use this method to obtain a connected cellular network
5072 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5073 * radio to consume additional power. Or, an application could inform the system that it wants
5074 * a network supporting sending MMSes and have the system let it know about the currently best
5075 * MMS-supporting network through the provided {@link NetworkCallback}.
5076 *
5077 * <p>The status of the request can be followed by listening to the various callbacks described
5078 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5079 * used to direct traffic to the network (although accessing some networks may be subject to
5080 * holding specific permissions). Callers will learn about the specific characteristics of the
5081 * network through
5082 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5083 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5084 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5085 * matching the request at any given time; therefore when a better network matching the request
5086 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5087 * with the new network after which no further updates are given about the previously-best
5088 * network, unless it becomes the best again at some later time. All callbacks are invoked
5089 * in order on the same thread, which by default is a thread created by the framework running
5090 * in the app.
5091 *
5092 * <p>This{@link NetworkRequest} will live until released via
5093 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5094 * which point the system may let go of the network at any time.
5095 *
5096 * <p>It is presently unsupported to request a network with mutable
5097 * {@link NetworkCapabilities} such as
5098 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5099 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5100 * as these {@code NetworkCapabilities} represent states that a particular
5101 * network may never attain, and whether a network will attain these states
5102 * is unknown prior to bringing up the network so the framework does not
5103 * know how to go about satisfying a request with these capabilities.
5104 *
5105 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5106 * number of outstanding requests to 100 per app (identified by their UID), shared with
5107 * all variants of this method, of {@link #registerNetworkCallback} as well as
5108 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5109 * Requesting a network with this method will count toward this limit. If this limit is
5110 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5111 * make sure to unregister the callbacks with
5112 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5113 *
5114 * @param request {@link NetworkRequest} describing this request.
5115 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5116 * If null, the callback is invoked on the default internal Handler.
5117 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5118 * the callback must not be shared - it uniquely specifies this request.
5119 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5120 * @throws SecurityException if missing the appropriate permissions.
5121 * @throws RuntimeException if the app already has too many callbacks registered.
5122 *
5123 * @hide
5124 */
5125 @SystemApi(client = MODULE_LIBRARIES)
5126 @SuppressLint("ExecutorRegistration")
5127 @RequiresPermission(anyOf = {
5128 android.Manifest.permission.NETWORK_SETTINGS,
5129 android.Manifest.permission.NETWORK_STACK,
5130 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5131 })
5132 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
5133 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
5134 final NetworkCapabilities nc = request.networkCapabilities;
5135 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
5136 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
5137 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005138}