blob: c820a7e80f4cfa21dea4d21c44814d5767d09115 [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 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001224 * Returns details about the currently active default data network
1225 * for a given uid. This is for internal use only to avoid spying
1226 * other apps.
1227 *
1228 * @return a {@link NetworkInfo} object for the current default network
1229 * for the given uid or {@code null} if no default network is
1230 * available for the specified uid.
1231 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001232 * {@hide}
1233 */
paulhu8e96a752019-08-12 16:25:11 +08001234 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001235 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001236 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001237 return getActiveNetworkInfoForUid(uid, false);
1238 }
1239
1240 /** {@hide} */
1241 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001242 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001243 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001244 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001245 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001246 }
1247 }
1248
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001249 /**
1250 * Returns connection status information about a particular
1251 * network type.
1252 *
1253 * @param networkType integer specifying which networkType in
1254 * which you're interested.
1255 * @return a {@link NetworkInfo} object for the requested
1256 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001257 * supported by the device. If {@code networkType} is
1258 * TYPE_VPN and a VPN is active for the calling app,
1259 * then this method will try to return one of the
1260 * underlying networks for the VPN or null if the
1261 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001262 *
Paul Jensendda8e592015-03-18 12:23:02 -04001263 * @deprecated This method does not support multiple connected networks
1264 * of the same type. Use {@link #getAllNetworks} and
1265 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001266 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001267 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001268 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001269 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001270 public NetworkInfo getNetworkInfo(int networkType) {
1271 try {
1272 return mService.getNetworkInfo(networkType);
1273 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001274 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001275 }
1276 }
1277
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001278 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001279 * Returns connection status information about a particular
1280 * Network.
1281 *
1282 * @param network {@link Network} specifying which network
1283 * in which you're interested.
1284 * @return a {@link NetworkInfo} object for the requested
1285 * network or {@code null} if the {@code Network}
1286 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001287 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001288 */
junyulai9826e7f2018-12-13 12:47:51 +08001289 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001290 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001291 @Nullable
1292 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001293 return getNetworkInfoForUid(network, Process.myUid(), false);
1294 }
1295
1296 /** {@hide} */
1297 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001298 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001299 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001300 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001301 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001302 }
1303 }
1304
1305 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001306 * Returns connection status information about all network
1307 * types supported by the device.
1308 *
1309 * @return an array of {@link NetworkInfo} objects. Check each
1310 * {@link NetworkInfo#getType} for which type each applies.
1311 *
Paul Jensendda8e592015-03-18 12:23:02 -04001312 * @deprecated This method does not support multiple connected networks
1313 * of the same type. Use {@link #getAllNetworks} and
1314 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001315 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001316 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001317 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001318 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001319 public NetworkInfo[] getAllNetworkInfo() {
1320 try {
1321 return mService.getAllNetworkInfo();
1322 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001323 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001324 }
1325 }
1326
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001327 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001328 * Returns the {@link Network} object currently serving a given type, or
1329 * null if the given type is not connected.
1330 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001331 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001332 * @deprecated This method does not support multiple connected networks
1333 * of the same type. Use {@link #getAllNetworks} and
1334 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001335 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001336 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001337 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001338 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001339 public Network getNetworkForType(int networkType) {
1340 try {
1341 return mService.getNetworkForType(networkType);
1342 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001343 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001344 }
1345 }
1346
1347 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001348 * Returns an array of all {@link Network} currently tracked by the
1349 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001350 *
1351 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001352 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001353 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001354 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001355 public Network[] getAllNetworks() {
1356 try {
1357 return mService.getAllNetworks();
1358 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001359 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001360 }
1361 }
1362
1363 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001364 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001365 * the Networks that applications run by the given user will use by default.
1366 * @hide
1367 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001368 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001369 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1370 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001371 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001372 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001373 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001374 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001375 }
1376 }
1377
1378 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001379 * Returns the IP information for the current default network.
1380 *
1381 * @return a {@link LinkProperties} object describing the IP info
1382 * for the current default network, or {@code null} if there
1383 * is no current default network.
1384 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001385 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001386 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1387 * value of {@link #getActiveNetwork()} instead. In particular,
1388 * this method will return non-null LinkProperties even if the
1389 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001390 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001391 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001392 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001393 public LinkProperties getActiveLinkProperties() {
1394 try {
1395 return mService.getActiveLinkProperties();
1396 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001397 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001398 }
1399 }
1400
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001401 /**
1402 * Returns the IP information for a given network type.
1403 *
1404 * @param networkType the network type of interest.
1405 * @return a {@link LinkProperties} object describing the IP info
1406 * for the given networkType, or {@code null} if there is
1407 * no current default network.
1408 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001409 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001410 * @deprecated This method does not support multiple connected networks
1411 * of the same type. Use {@link #getAllNetworks},
1412 * {@link #getNetworkInfo(android.net.Network)}, and
1413 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001414 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001415 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001416 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001417 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001418 public LinkProperties getLinkProperties(int networkType) {
1419 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001420 return mService.getLinkPropertiesForType(networkType);
1421 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001422 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001423 }
1424 }
1425
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001426 /**
1427 * Get the {@link LinkProperties} for the given {@link Network}. This
1428 * will return {@code null} if the network is unknown.
1429 *
1430 * @param network The {@link Network} object identifying the network in question.
1431 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001432 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001433 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001434 @Nullable
1435 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001436 try {
1437 return mService.getLinkProperties(network);
1438 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001439 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001440 }
1441 }
1442
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001443 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001444 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001445 * will return {@code null} if the network is unknown.
1446 *
1447 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001448 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001449 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001450 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001451 @Nullable
1452 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001453 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001454 return mService.getNetworkCapabilities(
1455 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001456 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001457 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001458 }
1459 }
1460
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001461 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001462 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001463 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1464 * portal is present.
1465 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1466 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1467 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001468 * The system network validation may be using different strategies to detect captive portals,
1469 * so this method does not necessarily return a URL used by the system. It only returns a URL
1470 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001471 *
Udam Sainicd645462016-01-04 12:16:14 -08001472 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001473 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1474 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001475 */
paulhu8e96a752019-08-12 16:25:11 +08001476 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001477 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001478 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001479 public String getCaptivePortalServerUrl() {
1480 try {
1481 return mService.getCaptivePortalServerUrl();
1482 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001483 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001484 }
1485 }
1486
1487 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001488 * Tells the underlying networking system that the caller wants to
1489 * begin using the named feature. The interpretation of {@code feature}
1490 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001491 *
1492 * <p>This method requires the caller to hold either the
1493 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1494 * or the ability to modify system settings as determined by
1495 * {@link android.provider.Settings.System#canWrite}.</p>
1496 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001497 * @param networkType specifies which network the request pertains to
1498 * @param feature the name of the feature to be used
1499 * @return an integer value representing the outcome of the request.
1500 * The interpretation of this value is specific to each networking
1501 * implementation+feature combination, except that the value {@code -1}
1502 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001503 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001504 * @deprecated Deprecated in favor of the cleaner
1505 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001506 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001507 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001508 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001509 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001510 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001511 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001512 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001513 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1514 if (netCap == null) {
1515 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1516 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001517 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001518 }
1519
1520 NetworkRequest request = null;
1521 synchronized (sLegacyRequests) {
1522 LegacyRequest l = sLegacyRequests.get(netCap);
1523 if (l != null) {
1524 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1525 renewRequestLocked(l);
1526 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001527 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001528 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001529 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001530 }
1531 }
1532
1533 request = requestNetworkForFeatureLocked(netCap);
1534 }
1535 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001536 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001537 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001538 } else {
1539 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001540 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001541 }
1542 }
1543
1544 /**
1545 * Tells the underlying networking system that the caller is finished
1546 * using the named feature. The interpretation of {@code feature}
1547 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001548 *
1549 * <p>This method requires the caller to hold either the
1550 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1551 * or the ability to modify system settings as determined by
1552 * {@link android.provider.Settings.System#canWrite}.</p>
1553 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001554 * @param networkType specifies which network the request pertains to
1555 * @param feature the name of the feature that is no longer needed
1556 * @return an integer value representing the outcome of the request.
1557 * The interpretation of this value is specific to each networking
1558 * implementation+feature combination, except that the value {@code -1}
1559 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001560 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001561 * @deprecated Deprecated in favor of the cleaner
1562 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001563 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001564 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001565 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001566 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001567 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001568 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001569 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001570 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1571 if (netCap == null) {
1572 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1573 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001574 return -1;
1575 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001576
Paul Jensen49f74a32014-12-17 10:39:34 -05001577 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001578 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001579 }
1580 return 1;
1581 }
1582
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001583 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001584 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1585 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001586 switch (feature) {
1587 case "enableCBS":
1588 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1589 case "enableDUN":
1590 case "enableDUNAlways":
1591 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1592 case "enableFOTA":
1593 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1594 case "enableHIPRI":
1595 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1596 case "enableIMS":
1597 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1598 case "enableMMS":
1599 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1600 case "enableSUPL":
1601 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1602 default:
1603 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001604 }
Erik Klinece55eb12017-01-26 18:08:28 +09001605 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1606 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001607 }
1608 return null;
1609 }
1610
Robert Greenwalt802c1102014-06-02 15:32:02 -07001611 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001612 if (netCap == null) return TYPE_NONE;
1613 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1614 return TYPE_MOBILE_CBS;
1615 }
1616 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1617 return TYPE_MOBILE_IMS;
1618 }
1619 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1620 return TYPE_MOBILE_FOTA;
1621 }
1622 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1623 return TYPE_MOBILE_DUN;
1624 }
1625 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1626 return TYPE_MOBILE_SUPL;
1627 }
1628 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1629 return TYPE_MOBILE_MMS;
1630 }
1631 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1632 return TYPE_MOBILE_HIPRI;
1633 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001634 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1635 return TYPE_WIFI_P2P;
1636 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001637 return TYPE_NONE;
1638 }
1639
1640 private static class LegacyRequest {
1641 NetworkCapabilities networkCapabilities;
1642 NetworkRequest networkRequest;
1643 int expireSequenceNumber;
1644 Network currentNetwork;
1645 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001646
1647 private void clearDnsBinding() {
1648 if (currentNetwork != null) {
1649 currentNetwork = null;
1650 setProcessDefaultNetworkForHostResolution(null);
1651 }
1652 }
1653
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001654 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001655 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001656 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001657 currentNetwork = network;
1658 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001659 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001660 }
1661 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001662 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001663 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001664 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1665 }
1666 };
1667 }
1668
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001669 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001670 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1671 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001672
1673 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1674 synchronized (sLegacyRequests) {
1675 LegacyRequest l = sLegacyRequests.get(netCap);
1676 if (l != null) return l.networkRequest;
1677 }
1678 return null;
1679 }
1680
1681 private void renewRequestLocked(LegacyRequest l) {
1682 l.expireSequenceNumber++;
1683 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1684 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1685 }
1686
1687 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1688 int ourSeqNum = -1;
1689 synchronized (sLegacyRequests) {
1690 LegacyRequest l = sLegacyRequests.get(netCap);
1691 if (l == null) return;
1692 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001693 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001694 }
1695 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1696 }
1697
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001698 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001699 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1700 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001701 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001702 try {
1703 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001704 } catch (RemoteException e) {
1705 throw e.rethrowFromSystemServer();
1706 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001707 LegacyRequest l = new LegacyRequest();
1708 l.networkCapabilities = netCap;
1709 l.delay = delay;
1710 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001711 l.networkRequest = sendRequestForNetwork(
1712 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001713 if (l.networkRequest == null) return null;
1714 sLegacyRequests.put(netCap, l);
1715 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1716 return l.networkRequest;
1717 }
1718
1719 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1720 if (delay >= 0) {
1721 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001722 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001723 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1724 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001725 }
1726 }
1727
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001728 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001729 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1730 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001731 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001732 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001733 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001734 if (l == null) return false;
1735 unregisterNetworkCallback(l.networkCallback);
1736 l.clearDnsBinding();
1737 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001738 }
1739
Erik Klinece55eb12017-01-26 18:08:28 +09001740 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1741 static {
1742 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1743 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1744 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1745 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1746 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1747 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1748 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1749 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1750 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1751 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1752 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1753 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1754 }
1755
1756 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1757 static {
1758 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1759 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1760 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1761 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1762 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1763 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1764 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1765 }
1766
1767 /**
1768 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1769 * instance suitable for registering a request or callback. Throws an
1770 * IllegalArgumentException if no mapping from the legacy type to
1771 * NetworkCapabilities is known.
1772 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001773 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1774 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001775 * @hide
1776 */
1777 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1778 final NetworkCapabilities nc = new NetworkCapabilities();
1779
1780 // Map from type to transports.
1781 final int NOT_FOUND = -1;
1782 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichibc1104b2017-05-09 15:19:01 +09001783 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001784 nc.addTransportType(transport);
1785
1786 // Map from type to capabilities.
1787 nc.addCapability(sLegacyTypeToCapability.get(
1788 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1789 nc.maybeMarkCapabilitiesRestricted();
1790 return nc;
1791 }
1792
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001793 /** @hide */
1794 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001795 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001796 public PacketKeepaliveCallback() {
1797 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001798 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001799 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001800 public void onStarted() {}
1801 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001802 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001803 public void onStopped() {}
1804 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001805 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001806 public void onError(int error) {}
1807 }
1808
1809 /**
1810 * Allows applications to request that the system periodically send specific packets on their
1811 * behalf, using hardware offload to save battery power.
1812 *
1813 * To request that the system send keepalives, call one of the methods that return a
1814 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1815 * passing in a non-null callback. If the callback is successfully started, the callback's
1816 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1817 * specifying one of the {@code ERROR_*} constants in this class.
1818 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001819 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1820 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1821 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001822 *
junyulai4c95b082018-12-27 17:25:29 +08001823 * @deprecated Use {@link SocketKeepalive} instead.
1824 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001825 * @hide
1826 */
1827 public class PacketKeepalive {
1828
1829 private static final String TAG = "PacketKeepalive";
1830
1831 /** @hide */
1832 public static final int SUCCESS = 0;
1833
1834 /** @hide */
1835 public static final int NO_KEEPALIVE = -1;
1836
1837 /** @hide */
1838 public static final int BINDER_DIED = -10;
1839
1840 /** The specified {@code Network} is not connected. */
1841 public static final int ERROR_INVALID_NETWORK = -20;
1842 /** The specified IP addresses are invalid. For example, the specified source IP address is
1843 * not configured on the specified {@code Network}. */
1844 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1845 /** The requested port is invalid. */
1846 public static final int ERROR_INVALID_PORT = -22;
1847 /** The packet length is invalid (e.g., too long). */
1848 public static final int ERROR_INVALID_LENGTH = -23;
1849 /** The packet transmission interval is invalid (e.g., too short). */
1850 public static final int ERROR_INVALID_INTERVAL = -24;
1851
1852 /** The hardware does not support this request. */
1853 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001854 /** The hardware returned an error. */
1855 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001856
Nathan Harold0990bc82018-02-14 13:09:45 -08001857 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001858 public static final int NATT_PORT = 4500;
1859
Nathan Harold0990bc82018-02-14 13:09:45 -08001860 /** The minimum interval in seconds between keepalive packet transmissions */
1861 public static final int MIN_INTERVAL = 10;
1862
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001863 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001864 private final ISocketKeepaliveCallback mCallback;
1865 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001866
1867 private volatile Integer mSlot;
1868
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001869 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001870 public void stop() {
1871 try {
junyulai070f9ff2019-01-16 20:23:34 +08001872 mExecutor.execute(() -> {
1873 try {
1874 if (mSlot != null) {
1875 mService.stopKeepalive(mNetwork, mSlot);
1876 }
1877 } catch (RemoteException e) {
1878 Log.e(TAG, "Error stopping packet keepalive: ", e);
1879 throw e.rethrowFromSystemServer();
1880 }
1881 });
1882 } catch (RejectedExecutionException e) {
1883 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001884 }
1885 }
1886
1887 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09001888 Preconditions.checkNotNull(network, "network cannot be null");
1889 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001890 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001891 mExecutor = Executors.newSingleThreadExecutor();
1892 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001893 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001894 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001895 final long token = Binder.clearCallingIdentity();
1896 try {
1897 mExecutor.execute(() -> {
1898 mSlot = slot;
1899 callback.onStarted();
1900 });
1901 } finally {
1902 Binder.restoreCallingIdentity(token);
1903 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001904 }
junyulai070f9ff2019-01-16 20:23:34 +08001905
1906 @Override
1907 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001908 final long token = Binder.clearCallingIdentity();
1909 try {
1910 mExecutor.execute(() -> {
1911 mSlot = null;
1912 callback.onStopped();
1913 });
1914 } finally {
1915 Binder.restoreCallingIdentity(token);
1916 }
junyulai070f9ff2019-01-16 20:23:34 +08001917 mExecutor.shutdown();
1918 }
1919
1920 @Override
1921 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001922 final long token = Binder.clearCallingIdentity();
1923 try {
1924 mExecutor.execute(() -> {
1925 mSlot = null;
1926 callback.onError(error);
1927 });
1928 } finally {
1929 Binder.restoreCallingIdentity(token);
1930 }
junyulai070f9ff2019-01-16 20:23:34 +08001931 mExecutor.shutdown();
1932 }
1933
1934 @Override
1935 public void onDataReceived() {
1936 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1937 // this callback when data is received.
1938 }
1939 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001940 }
1941 }
1942
1943 /**
1944 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1945 *
junyulai4c95b082018-12-27 17:25:29 +08001946 * @deprecated Use {@link #createSocketKeepalive} instead.
1947 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001948 * @hide
1949 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001950 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001951 public PacketKeepalive startNattKeepalive(
1952 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1953 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1954 final PacketKeepalive k = new PacketKeepalive(network, callback);
1955 try {
junyulai070f9ff2019-01-16 20:23:34 +08001956 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001957 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1958 } catch (RemoteException e) {
1959 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001960 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001961 }
1962 return k;
1963 }
1964
Chiachang Wang619319a2021-01-15 11:06:21 +08001965 // Construct an invalid fd.
1966 private ParcelFileDescriptor createInvalidFd() {
1967 final int invalidFd = -1;
1968 return ParcelFileDescriptor.adoptFd(invalidFd);
1969 }
1970
The Android Open Source Project28527d22009-03-03 19:31:44 -08001971 /**
junyulai4c95b082018-12-27 17:25:29 +08001972 * Request that keepalives be started on a IPsec NAT-T socket.
1973 *
1974 * @param network The {@link Network} the socket is on.
1975 * @param socket The socket that needs to be kept alive.
1976 * @param source The source address of the {@link UdpEncapsulationSocket}.
1977 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1978 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1979 * must run callback sequentially, otherwise the order of callbacks cannot be
1980 * guaranteed.
1981 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1982 * changes. Must be extended by applications that use this API.
1983 *
junyulai0835a1e2019-01-08 20:04:33 +08001984 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1985 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001986 **/
junyulai7e06ad42019-03-04 22:45:36 +08001987 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001988 @NonNull UdpEncapsulationSocket socket,
1989 @NonNull InetAddress source,
1990 @NonNull InetAddress destination,
1991 @NonNull @CallbackExecutor Executor executor,
1992 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001993 ParcelFileDescriptor dup;
1994 try {
junyulai828dad12019-03-27 11:00:37 +08001995 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1996 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001997 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1998 } catch (IOException ignored) {
1999 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2000 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002001 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002002 }
2003 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2004 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002005 }
2006
2007 /**
2008 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2009 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2010 *
2011 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002012 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2013 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2014 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002015 * @param source The source address of the {@link UdpEncapsulationSocket}.
2016 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2017 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2018 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2019 * must run callback sequentially, otherwise the order of callbacks cannot be
2020 * guaranteed.
2021 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2022 * changes. Must be extended by applications that use this API.
2023 *
junyulai0835a1e2019-01-08 20:04:33 +08002024 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2025 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002026 * @hide
2027 */
2028 @SystemApi
2029 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002030 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2031 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002032 @NonNull InetAddress source,
2033 @NonNull InetAddress destination,
2034 @NonNull @CallbackExecutor Executor executor,
2035 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002036 ParcelFileDescriptor dup;
2037 try {
junyulai828dad12019-03-27 11:00:37 +08002038 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002039 dup = pfd.dup();
2040 } catch (IOException ignored) {
2041 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2042 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002043 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002044 }
2045 return new NattSocketKeepalive(mService, network, dup,
2046 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002047 }
2048
2049 /**
junyulai0835a1e2019-01-08 20:04:33 +08002050 * Request that keepalives be started on a TCP socket.
2051 * The socket must be established.
2052 *
2053 * @param network The {@link Network} the socket is on.
2054 * @param socket The socket that needs to be kept alive.
2055 * @param executor The executor on which callback will be invoked. This implementation assumes
2056 * the provided {@link Executor} runs the callbacks in sequence with no
2057 * concurrency. Failing this, no guarantee of correctness can be made. It is
2058 * the responsibility of the caller to ensure the executor provides this
2059 * guarantee. A simple way of creating such an executor is with the standard
2060 * tool {@code Executors.newSingleThreadExecutor}.
2061 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2062 * changes. Must be extended by applications that use this API.
2063 *
2064 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2065 * given socket.
2066 * @hide
2067 */
2068 @SystemApi
2069 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002070 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002071 @NonNull Socket socket,
2072 @NonNull Executor executor,
2073 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002074 ParcelFileDescriptor dup;
2075 try {
2076 dup = ParcelFileDescriptor.fromSocket(socket);
2077 } catch (UncheckedIOException ignored) {
2078 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2079 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002080 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002081 }
2082 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002083 }
2084
2085 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002086 * Ensure that a network route exists to deliver traffic to the specified
2087 * host via the specified network interface. An attempt to add a route that
2088 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002089 *
2090 * <p>This method requires the caller to hold either the
2091 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2092 * or the ability to modify system settings as determined by
2093 * {@link android.provider.Settings.System#canWrite}.</p>
2094 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002095 * @param networkType the type of the network over which traffic to the specified
2096 * host is to be routed
2097 * @param hostAddress the IP address of the host to which the route is desired
2098 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002099 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002100 * @deprecated Deprecated in favor of the
2101 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2102 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002103 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002104 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002105 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002106 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002107 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002108 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002109 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002110 }
2111
2112 /**
2113 * Ensure that a network route exists to deliver traffic to the specified
2114 * host via the specified network interface. An attempt to add a route that
2115 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002116 *
2117 * <p>This method requires the caller to hold either the
2118 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2119 * or the ability to modify system settings as determined by
2120 * {@link android.provider.Settings.System#canWrite}.</p>
2121 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002122 * @param networkType the type of the network over which traffic to the specified
2123 * host is to be routed
2124 * @param hostAddress the IP address of the host to which the route is desired
2125 * @return {@code true} on success, {@code false} on failure
2126 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002127 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002128 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002129 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002130 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002131 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002132 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002133 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002135 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2136 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002138 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002139 }
2140 }
2141
2142 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002143 * @return the context's attribution tag
2144 */
2145 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2146 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002147 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002148 }
2149
2150 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002151 * Returns the value of the setting for background data usage. If false,
2152 * applications should not use the network if the application is not in the
2153 * foreground. Developers should respect this setting, and check the value
2154 * of this before performing any background data operations.
2155 * <p>
2156 * All applications that have background services that use the network
2157 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002158 * <p>
Scott Main50589142011-10-06 18:32:43 -07002159 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002160 * background data depends on several combined factors, and this method will
2161 * always return {@code true}. Instead, when background data is unavailable,
2162 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002163 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002164 * @return Whether background data usage is allowed.
2165 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002166 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002167 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002168 // assume that background data is allowed; final authority is
2169 // NetworkInfo which may be blocked.
2170 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002171 }
2172
2173 /**
2174 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002175 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002176 * @param allowBackgroundData Whether an application should use data while
2177 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002178 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002179 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2180 * @see #getBackgroundDataSetting()
2181 * @hide
2182 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002183 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002184 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002185 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002186 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002187 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002188
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002189 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002190 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002191 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002192 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002193 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002194 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002195 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002196 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2197 if (tm != null) {
2198 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2199 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2200 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2201 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2202 + " retVal=" + retVal);
2203 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002204 }
Wink Saville689f7042014-12-05 11:10:30 -08002205 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002206 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002207 }
2208
The Android Open Source Project28527d22009-03-03 19:31:44 -08002209 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002210 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002211 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002212 */
2213 public interface OnNetworkActiveListener {
2214 /**
2215 * Called on the main thread of the process to report that the current data network
2216 * has become active, and it is now a good time to perform any pending network
2217 * operations. Note that this listener only tells you when the network becomes
2218 * active; if at any other time you want to know whether it is active (and thus okay
2219 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002220 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002221 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002222 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002223 }
2224
2225 private INetworkManagementService getNetworkManagementService() {
2226 synchronized (this) {
2227 if (mNMService != null) {
2228 return mNMService;
2229 }
2230 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2231 mNMService = INetworkManagementService.Stub.asInterface(b);
2232 return mNMService;
2233 }
2234 }
2235
2236 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002237 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002238
2239 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002240 * Start listening to reports when the system's default data network is active, meaning it is
2241 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2242 * to determine the current state of the system's default network after registering the
2243 * listener.
2244 * <p>
2245 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002246 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002247 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002248 *
2249 * @param l The listener to be told when the network is active.
2250 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002251 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002252 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2253 @Override
2254 public void onNetworkActive() throws RemoteException {
2255 l.onNetworkActive();
2256 }
2257 };
2258
2259 try {
2260 getNetworkManagementService().registerNetworkActivityListener(rl);
2261 mNetworkActivityListeners.put(l, rl);
2262 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002263 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002264 }
2265 }
2266
2267 /**
2268 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002269 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002270 *
2271 * @param l Previously registered listener.
2272 */
Chalard Jean158702d2019-01-07 19:26:34 +09002273 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002274 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichibc1104b2017-05-09 15:19:01 +09002275 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002276 try {
2277 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2278 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002279 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002280 }
2281 }
2282
2283 /**
2284 * Return whether the data network is currently active. An active network means that
2285 * it is currently in a high power state for performing data transmission. On some
2286 * types of networks, it may be expensive to move and stay in such a state, so it is
2287 * more power efficient to batch network traffic together when the radio is already in
2288 * this state. This method tells you whether right now is currently a good time to
2289 * initiate network traffic, as the network is already active.
2290 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002291 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002292 try {
2293 return getNetworkManagementService().isNetworkActive();
2294 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002295 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002296 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002297 }
2298
2299 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002300 * {@hide}
2301 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002302 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002303 mContext = Preconditions.checkNotNull(context, "missing context");
2304 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002305 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002306 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002307 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002308
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002309 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002310 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002311 public static ConnectivityManager from(Context context) {
2312 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2313 }
2314
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002315 /** @hide */
2316 public NetworkRequest getDefaultRequest() {
2317 try {
2318 // This is not racy as the default request is final in ConnectivityService.
2319 return mService.getDefaultRequest();
2320 } catch (RemoteException e) {
2321 throw e.rethrowFromSystemServer();
2322 }
2323 }
2324
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09002325 /* TODO: These permissions checks don't belong in client-side code. Move them to
2326 * services.jar, possibly in com.android.server.net. */
2327
2328 /** {@hide} */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002329 public static final void enforceChangePermission(Context context,
2330 String callingPkg, String callingAttributionTag) {
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002331 int uid = Binder.getCallingUid();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002332 checkAndNoteChangeNetworkStateOperation(context, uid, callingPkg,
2333 callingAttributionTag, true /* throwException */);
2334 }
2335
2336 /**
2337 * Check if the package is a allowed to change the network state. This also accounts that such
2338 * an access happened.
2339 *
2340 * @return {@code true} iff the package is allowed to change the network state.
2341 */
2342 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2343 private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context,
2344 int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag,
2345 boolean throwException) {
2346 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, callingPackage,
2347 throwException);
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002348 }
2349
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002350 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002351 * Check if the package is a allowed to write settings. This also accounts that such an access
2352 * happened.
2353 *
2354 * @return {@code true} iff the package is allowed to write settings.
2355 */
2356 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2357 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2358 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2359 boolean throwException) {
2360 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2361 throwException);
2362 }
2363
2364 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002365 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2366 * situations where a Context pointer is unavailable.
2367 * @hide
2368 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002369 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002370 static ConnectivityManager getInstanceOrNull() {
2371 return sInstance;
2372 }
2373
2374 /**
2375 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2376 * situations where a Context pointer is unavailable.
2377 * @hide
2378 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002379 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002380 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002381 private static ConnectivityManager getInstance() {
2382 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002383 throw new IllegalStateException("No ConnectivityManager yet constructed");
2384 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002385 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002386 }
2387
2388 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002389 * Get the set of tetherable, available interfaces. This list is limited by
2390 * device configuration and current interface existence.
2391 *
2392 * @return an array of 0 or more Strings of tetherable interface names.
2393 *
markchien6ae63e52020-01-21 13:11:06 +08002394 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002395 * {@hide}
2396 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002397 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002398 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002399 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002400 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002401 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002402 }
2403
2404 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002405 * Get the set of tethered interfaces.
2406 *
2407 * @return an array of 0 or more String of currently tethered interface names.
2408 *
markchien6ae63e52020-01-21 13:11:06 +08002409 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002410 * {@hide}
2411 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002412 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002413 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002414 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002415 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002416 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002417 }
2418
2419 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002420 * Get the set of interface names which attempted to tether but
2421 * failed. Re-attempting to tether may cause them to reset to the Tethered
2422 * state. Alternatively, causing the interface to be destroyed and recreated
2423 * may cause them to reset to the available state.
2424 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2425 * information on the cause of the errors.
2426 *
2427 * @return an array of 0 or more String indicating the interface names
2428 * which failed to tether.
2429 *
markchien6ae63e52020-01-21 13:11:06 +08002430 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002431 * {@hide}
2432 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002433 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002434 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002435 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002436 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002437 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002438 }
2439
2440 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002441 * Get the set of tethered dhcp ranges.
2442 *
markchien2e6ba522020-02-14 11:55:48 +08002443 * @deprecated This method is not supported.
2444 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002445 * {@hide}
2446 */
paulhu8e96a752019-08-12 16:25:11 +08002447 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002448 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002449 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002450 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002451 }
2452
2453 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002454 * Attempt to tether the named interface. This will setup a dhcp server
2455 * on the interface, forward and NAT IP packets and forward DNS requests
2456 * to the best active upstream network interface. Note that if no upstream
2457 * IP network interface is available, dhcp will still run and traffic will be
2458 * allowed between the tethered devices and this device, though upstream net
2459 * access will of course fail until an upstream network interface becomes
2460 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002461 *
2462 * <p>This method requires the caller to hold either the
2463 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2464 * or the ability to modify system settings as determined by
2465 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002466 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002467 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2468 * and WifiStateMachine which need direct access. All other clients should use
2469 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2470 * logic.</p>
2471 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002472 * @param iface the interface name to tether.
2473 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002474 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002475 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002476 * {@hide}
2477 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002478 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002479 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002480 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002481 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002482 }
2483
2484 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002485 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002486 *
2487 * <p>This method requires the caller to hold either the
2488 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2489 * or the ability to modify system settings as determined by
2490 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002491 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002492 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2493 * and WifiStateMachine which need direct access. All other clients should use
2494 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2495 * logic.</p>
2496 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002497 * @param iface the interface name to untether.
2498 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2499 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002500 * {@hide}
2501 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002502 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002503 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002504 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002505 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002506 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002507
2508 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002509 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002510 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002511 * due to device configuration.
2512 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002513 * <p>If this app does not have permission to use this API, it will always
2514 * return false rather than throw an exception.</p>
2515 *
2516 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2517 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2518 *
2519 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2520 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2521 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002522 * @return a boolean - {@code true} indicating Tethering is supported.
2523 *
markchien6ae63e52020-01-21 13:11:06 +08002524 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002525 * {@hide}
2526 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002527 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002528 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2529 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002530 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002531 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002532 }
2533
2534 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002535 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002536 *
2537 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002538 * @hide
2539 */
2540 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002541 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002542 public static abstract class OnStartTetheringCallback {
2543 /**
2544 * Called when tethering has been successfully started.
2545 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002546 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002547
2548 /**
2549 * Called when starting tethering failed.
2550 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002551 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002552 }
2553
2554 /**
2555 * Convenient overload for
2556 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2557 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002558 *
2559 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002560 * @hide
2561 */
2562 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002563 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002564 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002565 public void startTethering(int type, boolean showProvisioningUi,
2566 final OnStartTetheringCallback callback) {
2567 startTethering(type, showProvisioningUi, callback, null);
2568 }
2569
2570 /**
2571 * Runs tether provisioning for the given type if needed and then starts tethering if
2572 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2573 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2574 * schedules tether provisioning re-checks if appropriate.
2575 *
2576 * @param type The type of tethering to start. Must be one of
2577 * {@link ConnectivityManager.TETHERING_WIFI},
2578 * {@link ConnectivityManager.TETHERING_USB}, or
2579 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2580 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2581 * is one. This should be true the first time this function is called and also any time
2582 * the user can see this UI. It gives users information from their carrier about the
2583 * check failing and how they can sign up for tethering if possible.
2584 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2585 * of the result of trying to tether.
2586 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002587 *
2588 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002589 * @hide
2590 */
2591 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002592 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002593 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002594 public void startTethering(int type, boolean showProvisioningUi,
2595 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002596 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002597
markchien91c78e52020-01-20 19:31:56 +08002598 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002599 @Override
markchien91c78e52020-01-20 19:31:56 +08002600 public void execute(Runnable command) {
2601 if (handler == null) {
2602 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002603 } else {
markchien91c78e52020-01-20 19:31:56 +08002604 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002605 }
2606 }
2607 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002608
markchien91c78e52020-01-20 19:31:56 +08002609 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2610 @Override
2611 public void onTetheringStarted() {
2612 callback.onTetheringStarted();
2613 }
2614
2615 @Override
markchienf47d8342020-03-19 13:37:43 +08002616 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002617 callback.onTetheringFailed();
2618 }
2619 };
2620
2621 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002622 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002623
Amos Bianchia9b415a2020-03-04 11:07:38 -08002624 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002625 }
2626
2627 /**
2628 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2629 * applicable.
2630 *
2631 * @param type The type of tethering to stop. Must be one of
2632 * {@link ConnectivityManager.TETHERING_WIFI},
2633 * {@link ConnectivityManager.TETHERING_USB}, or
2634 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002635 *
2636 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002637 * @hide
2638 */
2639 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002640 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002641 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002642 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002643 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002644 }
2645
2646 /**
markchien4ef53e82019-02-27 14:56:11 +08002647 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2648 * upstream status.
2649 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002650 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002651 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002652 */
2653 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002654 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002655 public abstract static class OnTetheringEventCallback {
2656
2657 /**
2658 * Called when tethering upstream changed. This can be called multiple times and can be
2659 * called any time.
2660 *
2661 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2662 * have any upstream.
2663 */
2664 public void onUpstreamChanged(@Nullable Network network) {}
2665 }
2666
markchien6ae63e52020-01-21 13:11:06 +08002667 @GuardedBy("mTetheringEventCallbacks")
2668 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2669 mTetheringEventCallbacks = new ArrayMap<>();
2670
markchien4ef53e82019-02-27 14:56:11 +08002671 /**
2672 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002673 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002674 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2675 * with a null argument. The same callback object cannot be registered twice.
2676 *
2677 * @param executor the executor on which callback will be invoked.
2678 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002679 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002680 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002681 * @hide
2682 */
2683 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002684 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002685 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2686 public void registerTetheringEventCallback(
2687 @NonNull @CallbackExecutor Executor executor,
2688 @NonNull final OnTetheringEventCallback callback) {
2689 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2690
markchien6ae63e52020-01-21 13:11:06 +08002691 final TetheringEventCallback tetherCallback =
2692 new TetheringEventCallback() {
2693 @Override
2694 public void onUpstreamChanged(@Nullable Network network) {
2695 callback.onUpstreamChanged(network);
2696 }
2697 };
2698
2699 synchronized (mTetheringEventCallbacks) {
2700 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002701 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002702 }
markchien4ef53e82019-02-27 14:56:11 +08002703 }
2704
2705 /**
2706 * Remove tethering event callback previously registered with
2707 * {@link #registerTetheringEventCallback}.
2708 *
2709 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002710 *
2711 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002712 * @hide
2713 */
2714 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002715 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002716 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2717 public void unregisterTetheringEventCallback(
2718 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002719 Objects.requireNonNull(callback, "The callback must be non-null");
2720 synchronized (mTetheringEventCallbacks) {
2721 final TetheringEventCallback tetherCallback =
2722 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002723 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002724 }
markchien4ef53e82019-02-27 14:56:11 +08002725 }
2726
2727
2728 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002729 * Get the list of regular expressions that define any tetherable
2730 * USB network interfaces. If USB tethering is not supported by the
2731 * device, this list should be empty.
2732 *
2733 * @return an array of 0 or more regular expression Strings defining
2734 * what interfaces are considered tetherable usb interfaces.
2735 *
markchien6ae63e52020-01-21 13:11:06 +08002736 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002737 * {@hide}
2738 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002739 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002740 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002741 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002742 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002743 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002744 }
2745
2746 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002747 * Get the list of regular expressions that define any tetherable
2748 * Wifi network interfaces. If Wifi tethering is not supported by the
2749 * device, this list should be empty.
2750 *
2751 * @return an array of 0 or more regular expression Strings defining
2752 * what interfaces are considered tetherable wifi interfaces.
2753 *
markchien6ae63e52020-01-21 13:11:06 +08002754 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002755 * {@hide}
2756 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002757 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002758 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002759 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002760 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002761 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002762 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002763
Danica Chang96567052010-08-11 14:54:43 -07002764 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002765 * Get the list of regular expressions that define any tetherable
2766 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2767 * device, this list should be empty.
2768 *
2769 * @return an array of 0 or more regular expression Strings defining
2770 * what interfaces are considered tetherable bluetooth interfaces.
2771 *
markchien6ae63e52020-01-21 13:11:06 +08002772 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2773 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002774 * {@hide}
2775 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002776 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002777 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002778 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002779 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002780 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002781 }
2782
Mike Lockwooded4a1742011-07-19 13:04:47 -07002783 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002784 * Attempt to both alter the mode of USB and Tethering of USB. A
2785 * utility method to deal with some of the complexity of USB - will
2786 * attempt to switch to Rndis and subsequently tether the resulting
2787 * interface on {@code true} or turn off tethering and switch off
2788 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002789 *
2790 * <p>This method requires the caller to hold either the
2791 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2792 * or the ability to modify system settings as determined by
2793 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002794 *
2795 * @param enable a boolean - {@code true} to enable tethering
2796 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002797 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002798 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002799 * {@hide}
2800 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002801 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002802 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002803 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002804 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002805 }
2806
markchien6ae63e52020-01-21 13:11:06 +08002807 /**
2808 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2809 * {@hide}
2810 */
markchien0f45bb92019-01-16 17:44:13 +08002811 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002812 @Deprecated
2813 public static final int TETHER_ERROR_NO_ERROR = TetheringManager.TETHER_ERROR_NO_ERROR;
2814 /**
2815 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2816 * {@hide}
2817 */
2818 @Deprecated
2819 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2820 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2821 /**
2822 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2823 * {@hide}
2824 */
2825 @Deprecated
2826 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2827 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2828 /**
2829 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2830 * {@hide}
2831 */
2832 @Deprecated
2833 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2834 /**
2835 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2836 * {@hide}
2837 */
2838 @Deprecated
2839 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2840 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2841 /**
markchienf47d8342020-03-19 13:37:43 +08002842 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002843 * {@hide}
2844 */
2845 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002846 public static final int TETHER_ERROR_MASTER_ERROR =
2847 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002848 /**
2849 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2850 * {@hide}
2851 */
2852 @Deprecated
2853 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2854 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2855 /**
2856 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2857 * {@hide}
2858 */
2859 @Deprecated
2860 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2861 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2862 /**
markchienf47d8342020-03-19 13:37:43 +08002863 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002864 * {@hide}
2865 */
2866 @Deprecated
2867 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002868 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002869 /**
markchienf47d8342020-03-19 13:37:43 +08002870 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002871 * {@hide}
2872 */
2873 @Deprecated
2874 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002875 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002876 /**
2877 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2878 * {@hide}
2879 */
2880 @Deprecated
2881 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2882 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2883 /**
markchienf47d8342020-03-19 13:37:43 +08002884 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002885 * {@hide}
2886 */
markchien0f45bb92019-01-16 17:44:13 +08002887 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002888 @Deprecated
2889 public static final int TETHER_ERROR_PROVISION_FAILED =
markchienf47d8342020-03-19 13:37:43 +08002890 TetheringManager.TETHER_ERROR_PROVISIONING_FAILED;
markchien6ae63e52020-01-21 13:11:06 +08002891 /**
2892 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2893 * {@hide}
2894 */
2895 @Deprecated
2896 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2897 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2898 /**
2899 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2900 * {@hide}
2901 */
markchien0f45bb92019-01-16 17:44:13 +08002902 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002903 @Deprecated
2904 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN =
2905 TetheringManager.TETHER_ERROR_ENTITLEMENT_UNKNOWN;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002906
2907 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002908 * Get a more detailed error code after a Tethering or Untethering
2909 * request asynchronously failed.
2910 *
2911 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002912 * @return error The error code of the last error tethering or untethering the named
2913 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002914 *
markchien6ae63e52020-01-21 13:11:06 +08002915 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002916 * {@hide}
2917 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002918 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002919 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002920 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002921 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002922 int error = mTetheringManager.getLastTetherError(iface);
2923 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2924 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2925 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2926 // instead.
2927 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2928 }
2929 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002930 }
2931
markchienbf5ab012019-03-06 16:25:00 +08002932 /** @hide */
2933 @Retention(RetentionPolicy.SOURCE)
2934 @IntDef(value = {
2935 TETHER_ERROR_NO_ERROR,
2936 TETHER_ERROR_PROVISION_FAILED,
2937 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2938 })
2939 public @interface EntitlementResultCode {
2940 }
2941
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002942 /**
markchienbf5ab012019-03-06 16:25:00 +08002943 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002944 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002945 *
2946 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002947 * @hide
2948 */
2949 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002950 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002951 public interface OnTetheringEntitlementResultListener {
2952 /**
2953 * Called to notify entitlement result.
2954 *
2955 * @param resultCode an int value of entitlement result. It may be one of
2956 * {@link #TETHER_ERROR_NO_ERROR},
2957 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2958 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2959 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002960 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002961 }
2962
2963 /**
markchien0f45bb92019-01-16 17:44:13 +08002964 * Get the last value of the entitlement check on this downstream. If the cached value is
2965 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2966 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2967 * guaranteed that the UI-based entitlement check will complete in any specific time period
2968 * and may in fact never complete. Any successful entitlement check the platform performs for
2969 * any reason will update the cached value.
2970 *
2971 * @param type the downstream type of tethering. Must be one of
2972 * {@link #TETHERING_WIFI},
2973 * {@link #TETHERING_USB}, or
2974 * {@link #TETHERING_BLUETOOTH}.
2975 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002976 * @param executor the executor on which callback will be invoked.
2977 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2978 * notify the caller of the result of entitlement check. The listener may be called zero
2979 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002980 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002981 * {@hide}
2982 */
2983 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002984 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002985 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002986 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2987 @NonNull @CallbackExecutor Executor executor,
2988 @NonNull final OnTetheringEntitlementResultListener listener) {
2989 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2990 ResultReceiver wrappedListener = new ResultReceiver(null) {
2991 @Override
2992 protected void onReceiveResult(int resultCode, Bundle resultData) {
2993 Binder.withCleanCallingIdentity(() ->
2994 executor.execute(() -> {
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002995 listener.onTetheringEntitlementResult(resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002996 }));
2997 }
2998 };
2999
Amos Bianchia9b415a2020-03-04 11:07:38 -08003000 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08003001 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08003002 }
3003
3004 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003005 * Report network connectivity status. This is currently used only
3006 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003007 * <p>This method requires the caller to hold the permission
3008 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003009 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003010 * @param networkType The type of network you want to report on
3011 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003012 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003013 * {@hide}
3014 */
3015 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003016 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003017 try {
3018 mService.reportInetCondition(networkType, percentage);
3019 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003020 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003021 }
3022 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003023
3024 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003025 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003026 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003027 * the framework to re-evaluate network connectivity and/or switch to another
3028 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003029 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003030 * @param network The {@link Network} the application was attempting to use
3031 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003032 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3033 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003034 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003035 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003036 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003037 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003038 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003039 // One of these will be ignored because it matches system's current state.
3040 // The other will trigger the necessary reevaluation.
3041 mService.reportNetworkConnectivity(network, true);
3042 mService.reportNetworkConnectivity(network, false);
3043 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003044 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003045 }
3046 }
3047
3048 /**
3049 * Report to the framework whether a network has working connectivity.
3050 * This provides a hint to the system that a particular network is providing
3051 * working connectivity or not. In response the framework may re-evaluate
3052 * the network's connectivity and might take further action thereafter.
3053 *
3054 * @param network The {@link Network} the application was attempting to use
3055 * or {@code null} to indicate the current default network.
3056 * @param hasConnectivity {@code true} if the application was able to successfully access the
3057 * Internet using {@code network} or {@code false} if not.
3058 */
Chalard Jean158702d2019-01-07 19:26:34 +09003059 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003060 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003061 try {
3062 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003063 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003064 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003065 }
3066 }
3067
3068 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003069 * Set a network-independent global http proxy. This is not normally what you want
3070 * for typical HTTP proxies - they are general network dependent. However if you're
3071 * doing something unusual like general internal filtering this may be useful. On
3072 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003073 *
3074 * @param p A {@link ProxyInfo} object defining the new global
3075 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003076 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003077 */
paulhu8e96a752019-08-12 16:25:11 +08003078 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04003079 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003080 try {
3081 mService.setGlobalProxy(p);
3082 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003083 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003084 }
3085 }
3086
3087 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003088 * Retrieve any network-independent global HTTP proxy.
3089 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003090 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003091 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003092 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003093 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003094 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003095 try {
3096 return mService.getGlobalProxy();
3097 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003098 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003099 }
3100 }
3101
3102 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003103 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3104 * network-specific HTTP proxy. If {@code network} is null, the
3105 * network-specific proxy returned is the proxy of the default active
3106 * network.
3107 *
3108 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3109 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3110 * or when {@code network} is {@code null},
3111 * the {@code ProxyInfo} for the default active network. Returns
3112 * {@code null} when no proxy applies or the caller doesn't have
3113 * permission to use {@code network}.
3114 * @hide
3115 */
3116 public ProxyInfo getProxyForNetwork(Network network) {
3117 try {
3118 return mService.getProxyForNetwork(network);
3119 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003120 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003121 }
3122 }
3123
3124 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003125 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3126 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003127 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003128 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003129 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003130 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003131 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003132 */
Chalard Jean158702d2019-01-07 19:26:34 +09003133 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003134 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003135 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003136 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003137
3138 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003139 * Returns true if the hardware supports the given network type
3140 * else it returns false. This doesn't indicate we have coverage
3141 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003142 * hardware supports it. For example a GSM phone without a SIM
3143 * should still return {@code true} for mobile data, but a wifi only
3144 * tablet would return {@code false}.
3145 *
3146 * @param networkType The network type we'd like to check
3147 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003148 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003149 * @hide
3150 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003151 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003152 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003153 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003154 public boolean isNetworkSupported(int networkType) {
3155 try {
3156 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003157 } catch (RemoteException e) {
3158 throw e.rethrowFromSystemServer();
3159 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003160 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003161
3162 /**
3163 * Returns if the currently active data network is metered. A network is
3164 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003165 * that connection due to monetary costs, data limitations or
3166 * battery/performance issues. You should check this before doing large
3167 * data transfers, and warn the user or delay the operation until another
3168 * network is available.
3169 *
3170 * @return {@code true} if large transfers should be avoided, otherwise
3171 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003172 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003173 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003174 public boolean isActiveNetworkMetered() {
3175 try {
3176 return mService.isActiveNetworkMetered();
3177 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003178 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003179 }
3180 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003181
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003182 /**
3183 * If the LockdownVpn mechanism is enabled, updates the vpn
3184 * with a reload of its profile.
3185 *
3186 * @return a boolean with {@code} indicating success
3187 *
3188 * <p>This method can only be called by the system UID
3189 * {@hide}
3190 */
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003191 public boolean updateLockdownVpn() {
3192 try {
3193 return mService.updateLockdownVpn();
3194 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003195 throw e.rethrowFromSystemServer();
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003196 }
3197 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07003198
3199 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003200 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003201 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003202 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003203 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003204 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003205 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003206 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003207 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003208 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003209 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003210 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003211 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003212 }
3213 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003214
3215 /**
3216 * Set the value for enabling/disabling airplane mode
3217 *
3218 * @param enable whether to enable airplane mode or not
3219 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003220 * @hide
3221 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003222 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003223 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003224 android.Manifest.permission.NETWORK_SETTINGS,
3225 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3226 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003227 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003228 public void setAirplaneMode(boolean enable) {
3229 try {
3230 mService.setAirplaneMode(enable);
3231 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003232 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003233 }
3234 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003235
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003236 /**
3237 * Registers the specified {@link NetworkProvider}.
3238 * Each listener must only be registered once. The listener can be unregistered with
3239 * {@link #unregisterNetworkProvider}.
3240 *
3241 * @param provider the provider to register
3242 * @return the ID of the provider. This ID must be used by the provider when registering
3243 * {@link android.net.NetworkAgent}s.
3244 * @hide
3245 */
3246 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003247 @RequiresPermission(anyOf = {
3248 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3249 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003250 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3251 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003252 throw new IllegalStateException("NetworkProviders can only be registered once");
3253 }
3254
3255 try {
3256 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3257 provider.getName());
3258 provider.setProviderId(providerId);
3259 } catch (RemoteException e) {
3260 throw e.rethrowFromSystemServer();
3261 }
3262 return provider.getProviderId();
3263 }
3264
3265 /**
3266 * Unregisters the specified NetworkProvider.
3267 *
3268 * @param provider the provider to unregister
3269 * @hide
3270 */
3271 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003272 @RequiresPermission(anyOf = {
3273 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3274 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003275 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3276 try {
3277 mService.unregisterNetworkProvider(provider.getMessenger());
3278 } catch (RemoteException e) {
3279 throw e.rethrowFromSystemServer();
3280 }
3281 provider.setProviderId(NetworkProvider.ID_NONE);
3282 }
3283
3284
3285 /** @hide exposed via the NetworkProvider class. */
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 void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3290 try {
3291 mService.declareNetworkRequestUnfulfillable(request);
3292 } catch (RemoteException e) {
3293 throw e.rethrowFromSystemServer();
3294 }
3295 }
3296
Chalard Jean29d06db2018-05-02 21:14:54 +09003297 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3298 // of dependent changes that would conflict throughout the automerger graph. Having this
3299 // temporarily helps with the process of going through with all these dependent changes across
3300 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003301 /**
3302 * @hide
3303 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003304 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003305 */
paulhub6ba8e82020-03-04 09:43:41 +08003306 @RequiresPermission(anyOf = {
3307 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3308 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003309 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003310 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003311 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003312 }
3313
3314 /**
3315 * @hide
3316 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003317 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003318 */
paulhub6ba8e82020-03-04 09:43:41 +08003319 @RequiresPermission(anyOf = {
3320 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3321 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003322 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003323 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003324 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003325 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003326 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003327 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003328 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003329 }
3330
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003331 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003332 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3333 * changes. Should be extended by applications wanting notifications.
3334 *
3335 * A {@code NetworkCallback} is registered by calling
3336 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3337 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003338 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003339 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3340 * A {@code NetworkCallback} should be registered at most once at any time.
3341 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003342 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003343 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003344 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003345 * Called when the framework connects to a new network to evaluate whether it satisfies this
3346 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3347 * callback. There is no guarantee that this new network will satisfy any requests, or that
3348 * the network will stay connected for longer than the time necessary to evaluate it.
3349 * <p>
3350 * Most applications <b>should not</b> act on this callback, and should instead use
3351 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3352 * the framework in properly evaluating the network &mdash; for example, an application that
3353 * can automatically log in to a captive portal without user intervention.
3354 *
3355 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003356 *
3357 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003358 */
paulhu1a407652019-03-22 16:35:06 +08003359 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003360
3361 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003362 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003363 * This callback may be called more than once if the {@link Network} that is
3364 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003365 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003366 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003367 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3368 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003369 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003370 * @hide
3371 */
paulhu1a407652019-03-22 16:35:06 +08003372 public void onAvailable(@NonNull Network network,
3373 @NonNull NetworkCapabilities networkCapabilities,
3374 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003375 // Internally only this method is called when a new network is available, and
3376 // it calls the callback in the same way and order that older versions used
3377 // to call so as not to change the behavior.
3378 onAvailable(network);
3379 if (!networkCapabilities.hasCapability(
3380 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3381 onNetworkSuspended(network);
3382 }
3383 onCapabilitiesChanged(network, networkCapabilities);
3384 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003385 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003386 }
3387
3388 /**
3389 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003390 *
3391 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3392 * be available at the same time, and onAvailable will be called for each of these as they
3393 * appear.
3394 *
3395 * <p>For callbacks registered with {@link #requestNetwork} and
3396 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3397 * is the new best network for this request and is now tracked by this callback ; this
3398 * callback will no longer receive method calls about other networks that may have been
3399 * passed to this method previously. The previously-best network may have disconnected, or
3400 * it may still be around and the newly-best network may simply be better.
3401 *
3402 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3403 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3404 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3405 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3406 *
3407 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3408 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3409 * this callback as this is prone to race conditions (there is no guarantee the objects
3410 * returned by these methods will be current). Instead, wait for a call to
3411 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3412 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3413 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003414 *
3415 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003416 */
paulhu1a407652019-03-22 16:35:06 +08003417 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003418
3419 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003420 * Called when the network is about to be lost, typically because there are no outstanding
3421 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3422 * with the new replacement network for graceful handover. This method is not guaranteed
3423 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3424 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003425 *
Chalard Jean01378b62019-08-30 16:27:28 +09003426 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3427 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3428 * this callback as this is prone to race conditions ; calling these methods while in a
3429 * callback may return an outdated or even a null object.
3430 *
3431 * @param network The {@link Network} that is about to be lost.
3432 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3433 * connected for graceful handover; note that the network may still
3434 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003435 */
paulhu1a407652019-03-22 16:35:06 +08003436 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003437
3438 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003439 * Called when a network disconnects or otherwise no longer satisfies this request or
3440 * callback.
3441 *
3442 * <p>If the callback was registered with requestNetwork() or
3443 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3444 * returned by onAvailable() when that network is lost and no other network satisfies
3445 * the criteria of the request.
3446 *
3447 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3448 * each network which no longer satisfies the criteria of the callback.
3449 *
3450 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3451 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3452 * this callback as this is prone to race conditions ; calling these methods while in a
3453 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003454 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003455 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003456 */
paulhu1a407652019-03-22 16:35:06 +08003457 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003458
3459 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003460 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003461 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3462 * requested network request cannot be fulfilled (whether or not a timeout was
3463 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003464 * {@link NetworkRequest} will have already been removed and released, as if
3465 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003466 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003467 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003468
3469 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003470 * Called when the network corresponding to this request changes capabilities but still
3471 * satisfies the requested criteria.
3472 *
3473 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3474 * to be called immediately after {@link #onAvailable}.
3475 *
3476 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3477 * ConnectivityManager methods in this callback as this is prone to race conditions :
3478 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003479 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003480 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003481 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3482 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003483 */
paulhu1a407652019-03-22 16:35:06 +08003484 public void onCapabilitiesChanged(@NonNull Network network,
3485 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003486
3487 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003488 * Called when the network corresponding to this request changes {@link LinkProperties}.
3489 *
3490 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3491 * to be called immediately after {@link #onAvailable}.
3492 *
3493 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3494 * ConnectivityManager methods in this callback as this is prone to race conditions :
3495 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003496 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003497 * @param network The {@link Network} whose link properties have changed.
3498 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003499 */
paulhu1a407652019-03-22 16:35:06 +08003500 public void onLinkPropertiesChanged(@NonNull Network network,
3501 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003502
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003503 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003504 * Called when the network the framework connected to for this request suspends data
3505 * transmission temporarily.
3506 *
3507 * <p>This generally means that while the TCP connections are still live temporarily
3508 * network data fails to transfer. To give a specific example, this is used on cellular
3509 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3510 * means read operations on sockets on this network will block once the buffers are
3511 * drained, and write operations will block once the buffers are full.
3512 *
3513 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3514 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3515 * this callback as this is prone to race conditions (there is no guarantee the objects
3516 * returned by these methods will be current).
3517 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003518 * @hide
3519 */
paulhu1a407652019-03-22 16:35:06 +08003520 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003521
3522 /**
3523 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003524 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3525 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003526
3527 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3528 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3529 * this callback as this is prone to race conditions : calling these methods while in a
3530 * callback may return an outdated or even a null object.
3531 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003532 * @hide
3533 */
paulhu1a407652019-03-22 16:35:06 +08003534 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003535
junyulaif2c67e42018-08-07 19:50:45 +08003536 /**
3537 * Called when access to the specified network is blocked or unblocked.
3538 *
Chalard Jean01378b62019-08-30 16:27:28 +09003539 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3540 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3541 * this callback as this is prone to race conditions : calling these methods while in a
3542 * callback may return an outdated or even a null object.
3543 *
junyulaif2c67e42018-08-07 19:50:45 +08003544 * @param network The {@link Network} whose blocked status has changed.
3545 * @param blocked The blocked status of this {@link Network}.
3546 */
junyulai7e06ad42019-03-04 22:45:36 +08003547 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003548
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003549 private NetworkRequest networkRequest;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003550 }
3551
Hugo Benichia590ab82017-05-11 13:16:17 +09003552 /**
3553 * Constant error codes used by ConnectivityService to communicate about failures and errors
3554 * across a Binder boundary.
3555 * @hide
3556 */
3557 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003558 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003559 }
3560
3561 /** @hide */
3562 public static class TooManyRequestsException extends RuntimeException {}
3563
3564 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3565 switch (e.errorCode) {
3566 case Errors.TOO_MANY_REQUESTS:
3567 return new TooManyRequestsException();
3568 default:
3569 Log.w(TAG, "Unknown service error code " + e.errorCode);
3570 return new RuntimeException(e);
3571 }
3572 }
3573
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003574 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003575 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003576 public static final int CALLBACK_PRECHECK = BASE + 1;
3577 /** @hide */
3578 public static final int CALLBACK_AVAILABLE = BASE + 2;
3579 /** @hide arg1 = TTL */
3580 public static final int CALLBACK_LOSING = BASE + 3;
3581 /** @hide */
3582 public static final int CALLBACK_LOST = BASE + 4;
3583 /** @hide */
3584 public static final int CALLBACK_UNAVAIL = BASE + 5;
3585 /** @hide */
3586 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3587 /** @hide */
3588 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003589 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003590 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003591 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003592 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003593 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003594 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003595 /** @hide */
3596 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003597
Erik Kline155a59a2015-11-25 12:49:38 +09003598 /** @hide */
3599 public static String getCallbackName(int whichCallback) {
3600 switch (whichCallback) {
3601 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3602 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3603 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3604 case CALLBACK_LOST: return "CALLBACK_LOST";
3605 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3606 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3607 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003608 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3609 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3610 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003611 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003612 default:
3613 return Integer.toString(whichCallback);
3614 }
3615 }
3616
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003617 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003618 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003619 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003620
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003621 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003622 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003623 }
3624
Hugo Benichifd44e912017-02-02 17:02:36 +09003625 CallbackHandler(Handler handler) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003626 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003627 }
3628
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003629 @Override
3630 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003631 if (message.what == EXPIRE_LEGACY_REQUEST) {
3632 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3633 return;
3634 }
3635
3636 final NetworkRequest request = getObject(message, NetworkRequest.class);
3637 final Network network = getObject(message, Network.class);
3638 final NetworkCallback callback;
3639 synchronized (sCallbacks) {
3640 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003641 if (callback == null) {
3642 Log.w(TAG,
3643 "callback not found for " + getCallbackName(message.what) + " message");
3644 return;
3645 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003646 if (message.what == CALLBACK_UNAVAIL) {
3647 sCallbacks.remove(request);
3648 callback.networkRequest = ALREADY_UNREGISTERED;
3649 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003650 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003651 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003652 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003653 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003654
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003655 switch (message.what) {
3656 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003657 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003658 break;
3659 }
3660 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003661 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3662 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003663 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003664 break;
3665 }
3666 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003667 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003668 break;
3669 }
3670 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003671 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003672 break;
3673 }
3674 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003675 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003676 break;
3677 }
3678 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003679 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3680 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003681 break;
3682 }
3683 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003684 LinkProperties lp = getObject(message, LinkProperties.class);
3685 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003686 break;
3687 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003688 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003689 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003690 break;
3691 }
3692 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003693 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003694 break;
3695 }
junyulaif2c67e42018-08-07 19:50:45 +08003696 case CALLBACK_BLK_CHANGED: {
3697 boolean blocked = message.arg1 != 0;
3698 callback.onBlockedStatusChanged(network, blocked);
3699 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003700 }
3701 }
3702
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003703 private <T> T getObject(Message msg, Class<T> c) {
3704 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003705 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003706 }
3707
Hugo Benichifd44e912017-02-02 17:02:36 +09003708 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003709 synchronized (sCallbacks) {
3710 if (sCallbackHandler == null) {
3711 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003712 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003713 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003714 }
3715 }
3716
Hugo Benichibc4ac972017-02-03 14:18:44 +09003717 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3718 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003719
Hugo Benichibc4ac972017-02-03 14:18:44 +09003720 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003721 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003722 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003723 checkCallbackNotNull(callback);
junyulaiad010792021-01-11 16:53:38 +08003724 Preconditions.checkArgument(
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09003725 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3726 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003727 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003728 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003729 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003730 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003731 if (callback.networkRequest != null
3732 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003733 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3734 // and requests (http://b/20701525).
3735 Log.e(TAG, "NetworkCallback was already registered");
3736 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003737 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003738 Binder binder = new Binder();
junyulaiad010792021-01-11 16:53:38 +08003739 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003740 request = mService.listenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003741 need, messenger, binder, callingPackageName,
3742 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003743 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003744 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003745 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3746 callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003747 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003748 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003749 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003750 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003751 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003752 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003753 } catch (RemoteException e) {
3754 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003755 } catch (ServiceSpecificException e) {
3756 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003757 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003758 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003759 }
3760
3761 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003762 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003763 *
markchienfac84a22020-03-18 21:16:15 +08003764 * This API is only for use in internal system code that requests networks with legacy type and
3765 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003766 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003767 *
markchiend6eeffd2020-01-14 00:55:21 +08003768 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003769 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3770 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3771 * be a positive value (i.e. >0).
3772 * @param legacyType to specify the network type(#TYPE_*).
3773 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003774 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3775 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003776 *
3777 * @hide
3778 */
markchiend6eeffd2020-01-14 00:55:21 +08003779 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003780 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003781 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003782 int timeoutMs, int legacyType, @NonNull Handler handler,
3783 @NonNull NetworkCallback networkCallback) {
3784 if (legacyType == TYPE_NONE) {
3785 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3786 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003787 CallbackHandler cbHandler = new CallbackHandler(handler);
3788 NetworkCapabilities nc = request.networkCapabilities;
3789 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003790 }
3791
3792 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003793 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003794 *
Chalard Jean01378b62019-08-30 16:27:28 +09003795 * <p>This method will attempt to find the best network that matches the passed
3796 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3797 * criteria. The platform will evaluate which network is the best at its own discretion.
3798 * Throughput, latency, cost per byte, policy, user preference and other considerations
3799 * may be factored in the decision of what is considered the best network.
3800 *
3801 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3802 * matching this request, while always attempting to match the request to a better network if
3803 * possible. If a better match is found, the platform will switch this request to the now-best
3804 * network and inform the app of the newly best network by invoking
3805 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3806 * will not try to maintain any other network than the best one currently matching the request:
3807 * a network not matching any network request may be disconnected at any time.
3808 *
3809 * <p>For example, an application could use this method to obtain a connected cellular network
3810 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3811 * radio to consume additional power. Or, an application could inform the system that it wants
3812 * a network supporting sending MMSes and have the system let it know about the currently best
3813 * MMS-supporting network through the provided {@link NetworkCallback}.
3814 *
3815 * <p>The status of the request can be followed by listening to the various callbacks described
3816 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3817 * used to direct traffic to the network (although accessing some networks may be subject to
3818 * holding specific permissions). Callers will learn about the specific characteristics of the
3819 * network through
3820 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3821 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3822 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3823 * matching the request at any given time; therefore when a better network matching the request
3824 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3825 * with the new network after which no further updates are given about the previously-best
3826 * network, unless it becomes the best again at some later time. All callbacks are invoked
3827 * in order on the same thread, which by default is a thread created by the framework running
3828 * in the app.
3829 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3830 * callbacks are invoked.
3831 *
3832 * <p>This{@link NetworkRequest} will live until released via
3833 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3834 * which point the system may let go of the network at any time.
3835 *
3836 * <p>A version of this method which takes a timeout is
3837 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3838 * wait for a limited amount of time for the network to become unavailable.
3839 *
Paul Jensenee52d232015-06-16 15:11:58 -04003840 * <p>It is presently unsupported to request a network with mutable
3841 * {@link NetworkCapabilities} such as
3842 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3843 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3844 * as these {@code NetworkCapabilities} represent states that a particular
3845 * network may never attain, and whether a network will attain these states
3846 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003847 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003848 *
3849 * <p>This method requires the caller to hold either the
3850 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3851 * or the ability to modify system settings as determined by
3852 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003853 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003854 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3855 * number of outstanding requests to 100 per app (identified by their UID), shared with
3856 * all variants of this method, of {@link #registerNetworkCallback} as well as
3857 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3858 * Requesting a network with this method will count toward this limit. If this limit is
3859 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3860 * make sure to unregister the callbacks with
3861 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3862 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003863 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003864 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3865 * the callback must not be shared - it uniquely specifies this request.
3866 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003867 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3868 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003869 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003870 */
Chalard Jean158702d2019-01-07 19:26:34 +09003871 public void requestNetwork(@NonNull NetworkRequest request,
3872 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003873 requestNetwork(request, networkCallback, getDefaultHandler());
3874 }
3875
3876 /**
3877 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3878 *
Chalard Jean01378b62019-08-30 16:27:28 +09003879 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3880 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003881 *
Chalard Jean01378b62019-08-30 16:27:28 +09003882 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003883 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3884 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003885 *
3886 * @param request {@link NetworkRequest} describing this request.
3887 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3888 * the callback must not be shared - it uniquely specifies this request.
3889 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003890 */
Chalard Jean158702d2019-01-07 19:26:34 +09003891 public void requestNetwork(@NonNull NetworkRequest request,
3892 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003893 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003894 NetworkCapabilities nc = request.networkCapabilities;
3895 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003896 }
3897
3898 /**
Etan Cohenf67bde92017-03-01 12:47:28 -08003899 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3900 * by a timeout.
3901 *
3902 * This function behaves identically to the non-timed-out version
3903 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3904 * is not found within the given time (in milliseconds) the
3905 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3906 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3907 * not have to be released if timed-out (it is automatically released). Unregistering a
3908 * request that timed out is not an error.
3909 *
3910 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3911 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3912 * for that purpose. Calling this method will attempt to bring up the requested network.
3913 *
Chalard Jean01378b62019-08-30 16:27:28 +09003914 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003915 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3916 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003917 *
3918 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003919 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3920 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003921 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3922 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3923 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003924 */
Chalard Jean158702d2019-01-07 19:26:34 +09003925 public void requestNetwork(@NonNull NetworkRequest request,
3926 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003927 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003928 NetworkCapabilities nc = request.networkCapabilities;
3929 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3930 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003931 }
3932
Hugo Benichifd44e912017-02-02 17:02:36 +09003933 /**
3934 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3935 * by a timeout.
3936 *
Chalard Jean01378b62019-08-30 16:27:28 +09003937 * This method behaves identically to
3938 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3939 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003940 *
Chalard Jean01378b62019-08-30 16:27:28 +09003941 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003942 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3943 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003944 *
3945 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003946 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3947 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003948 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003949 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3950 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003951 */
Chalard Jean158702d2019-01-07 19:26:34 +09003952 public void requestNetwork(@NonNull NetworkRequest request,
3953 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003954 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003955 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003956 NetworkCapabilities nc = request.networkCapabilities;
3957 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003958 }
3959
3960 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003961 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003962 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003963 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003964 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003965 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3966 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003967 */
Erik Kline8a826212014-11-19 12:12:24 +09003968 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003969
3970 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003971 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003972 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003973 * {@link android.content.Intent#getParcelableExtra(String)}.
3974 */
Erik Kline8a826212014-11-19 12:12:24 +09003975 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003976
3977
3978 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003979 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003980 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003981 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003982 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003983 * the request may outlive the calling application and get called back when a suitable
3984 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003985 * <p>
3986 * The operation is an Intent broadcast that goes to a broadcast receiver that
3987 * you registered with {@link Context#registerReceiver} or through the
3988 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3989 * <p>
3990 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003991 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3992 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003993 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003994 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003995 * Intent to reserve the network or it will be released shortly after the Intent
3996 * is processed.
3997 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003998 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003999 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004000 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004001 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004002 * The request may be released normally by calling
4003 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04004004 * <p>It is presently unsupported to request a network with either
4005 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4006 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4007 * as these {@code NetworkCapabilities} represent states that a particular
4008 * network may never attain, and whether a network will attain these states
4009 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09004010 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004011 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004012 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4013 * number of outstanding requests to 100 per app (identified by their UID), shared with
4014 * all variants of this method, of {@link #registerNetworkCallback} as well as
4015 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4016 * Requesting a network with this method will count toward this limit. If this limit is
4017 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4018 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4019 * or {@link #releaseNetworkRequest(PendingIntent)}.
4020 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004021 * <p>This method requires the caller to hold either the
4022 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4023 * or the ability to modify system settings as determined by
4024 * {@link android.provider.Settings.System#canWrite}.</p>
4025 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004026 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004027 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004028 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004029 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004030 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4031 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004032 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004033 */
Chalard Jean158702d2019-01-07 19:26:34 +09004034 public void requestNetwork(@NonNull NetworkRequest request,
4035 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004036 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004037 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004038 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004039 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004040 request.networkCapabilities, operation, mContext.getOpPackageName(),
4041 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004042 } catch (RemoteException e) {
4043 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004044 } catch (ServiceSpecificException e) {
4045 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004046 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004047 }
4048
4049 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004050 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4051 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004052 * This method has the same behavior as
4053 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004054 * releasing network resources and disconnecting.
4055 *
4056 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4057 * PendingIntent passed to
4058 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4059 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4060 */
Chalard Jean158702d2019-01-07 19:26:34 +09004061 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004062 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004063 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004064 try {
4065 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004066 } catch (RemoteException e) {
4067 throw e.rethrowFromSystemServer();
4068 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004069 }
4070
Hugo Benichibc1104b2017-05-09 15:19:01 +09004071 private static void checkPendingIntentNotNull(PendingIntent intent) {
4072 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4073 }
4074
4075 private static void checkCallbackNotNull(NetworkCallback callback) {
4076 Preconditions.checkNotNull(callback, "null NetworkCallback");
4077 }
4078
4079 private static void checkTimeout(int timeoutMs) {
4080 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004081 }
4082
4083 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004084 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004085 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004086 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4087 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004088 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004089 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4090 * number of outstanding requests to 100 per app (identified by their UID), shared with
4091 * all variants of this method, of {@link #requestNetwork} as well as
4092 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4093 * Requesting a network with this method will count toward this limit. If this limit is
4094 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4095 * make sure to unregister the callbacks with
4096 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4097 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004098 * @param request {@link NetworkRequest} describing this request.
4099 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4100 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004101 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004102 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004103 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004104 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004105 public void registerNetworkCallback(@NonNull NetworkRequest request,
4106 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004107 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4108 }
4109
4110 /**
4111 * Registers to receive notifications about all networks which satisfy the given
4112 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004113 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4114 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004115 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004116 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4117 * number of outstanding requests to 100 per app (identified by their UID), shared with
4118 * all variants of this method, of {@link #requestNetwork} as well as
4119 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4120 * Requesting a network with this method will count toward this limit. If this limit is
4121 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4122 * make sure to unregister the callbacks with
4123 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4124 *
4125 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004126 * @param request {@link NetworkRequest} describing this request.
4127 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4128 * networks change state.
4129 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004130 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004131 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004132 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004133 public void registerNetworkCallback(@NonNull NetworkRequest request,
4134 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004135 CallbackHandler cbHandler = new CallbackHandler(handler);
4136 NetworkCapabilities nc = request.networkCapabilities;
4137 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004138 }
4139
4140 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004141 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4142 * {@link NetworkRequest}.
4143 *
4144 * This function behaves identically to the version that takes a NetworkCallback, but instead
4145 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4146 * the request may outlive the calling application and get called back when a suitable
4147 * network is found.
4148 * <p>
4149 * The operation is an Intent broadcast that goes to a broadcast receiver that
4150 * you registered with {@link Context#registerReceiver} or through the
4151 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4152 * <p>
4153 * The operation Intent is delivered with two extras, a {@link Network} typed
4154 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4155 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4156 * the original requests parameters.
4157 * <p>
4158 * If there is already a request for this Intent registered (with the equality of
4159 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4160 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4161 * <p>
4162 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004163 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004164 *
4165 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4166 * number of outstanding requests to 100 per app (identified by their UID), shared with
4167 * all variants of this method, of {@link #requestNetwork} as well as
4168 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4169 * Requesting a network with this method will count toward this limit. If this limit is
4170 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4171 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4172 * or {@link #releaseNetworkRequest(PendingIntent)}.
4173 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004174 * @param request {@link NetworkRequest} describing this request.
4175 * @param operation Action to perform when the network is available (corresponds
4176 * to the {@link NetworkCallback#onAvailable} call. Typically
4177 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004178 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004179 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004180 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004181 public void registerNetworkCallback(@NonNull NetworkRequest request,
4182 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004183 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004184 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004185 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004186 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004187 request.networkCapabilities, operation, mContext.getOpPackageName(),
4188 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004189 } catch (RemoteException e) {
4190 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004191 } catch (ServiceSpecificException e) {
4192 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004193 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004194 }
4195
4196 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004197 * Registers to receive notifications about changes in the application's default network. This
4198 * may be a physical network or a virtual network, such as a VPN that applies to the
4199 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004200 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004201 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004202 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4203 * number of outstanding requests to 100 per app (identified by their UID), shared with
4204 * all variants of this method, of {@link #requestNetwork} as well as
4205 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4206 * Requesting a network with this method will count toward this limit. If this limit is
4207 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4208 * make sure to unregister the callbacks with
4209 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4210 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004211 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004212 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004213 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004214 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004215 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004216 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004217 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004218 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4219 }
4220
4221 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004222 * Registers to receive notifications about changes in the application's default network. This
4223 * may be a physical network or a virtual network, such as a VPN that applies to the
4224 * application. The callbacks will continue to be called until either the application exits or
4225 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4226 *
4227 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4228 * number of outstanding requests to 100 per app (identified by their UID), shared with
4229 * all variants of this method, of {@link #requestNetwork} as well as
4230 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4231 * Requesting a network with this method will count toward this limit. If this limit is
4232 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4233 * make sure to unregister the callbacks with
4234 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4235 *
4236 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4237 * application's default network changes.
4238 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4239 * @throws RuntimeException if the app already has too many callbacks registered.
4240 */
4241 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4242 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4243 @NonNull Handler handler) {
4244 CallbackHandler cbHandler = new CallbackHandler(handler);
4245 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4246 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4247 }
4248
4249 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004250 * Registers to receive notifications about changes in the system default network. The callbacks
4251 * will continue to be called until either the application exits or
4252 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004253 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004254 * This method should not be used to determine networking state seen by applications, because in
4255 * many cases, most or even all application traffic may not use the default network directly,
4256 * and traffic from different applications may go on different networks by default. As an
4257 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4258 * and not onto the system default network. Applications or system components desiring to do
4259 * determine network state as seen by applications should use other methods such as
4260 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4261 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004262 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4263 * number of outstanding requests to 100 per app (identified by their UID), shared with
4264 * all variants of this method, of {@link #requestNetwork} as well as
4265 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4266 * Requesting a network with this method will count toward this limit. If this limit is
4267 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4268 * make sure to unregister the callbacks with
4269 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4270 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004271 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4272 * system default network changes.
4273 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004274 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004275 *
4276 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004277 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004278 @SystemApi(client = MODULE_LIBRARIES)
4279 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4280 @RequiresPermission(anyOf = {
4281 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4282 android.Manifest.permission.NETWORK_SETTINGS})
4283 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004284 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004285 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004286 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004287 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004288 }
4289
4290 /**
fenglub00f4882015-04-21 17:12:05 -07004291 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4292 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4293 * network connection for updated bandwidth information. The caller will be notified via
4294 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004295 * method assumes that the caller has previously called
4296 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4297 * changes.
fenglu3f357402015-03-20 11:29:56 -07004298 *
fengluea2d9282015-04-27 14:28:04 -07004299 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004300 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004301 */
Chalard Jean158702d2019-01-07 19:26:34 +09004302 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004303 try {
fenglub00f4882015-04-21 17:12:05 -07004304 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004305 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004306 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004307 }
4308 }
4309
4310 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004311 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004312 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4313 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4314 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004315 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4316 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004317 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004318 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4319 * triggering it as soon as this call returns.
4320 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004321 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004322 */
Chalard Jean158702d2019-01-07 19:26:34 +09004323 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004324 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004325 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004326 final List<NetworkRequest> reqs = new ArrayList<>();
4327 // Find all requests associated to this callback and stop callback triggers immediately.
4328 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4329 synchronized (sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09004330 Preconditions.checkArgument(networkCallback.networkRequest != null,
4331 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004332 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4333 Log.d(TAG, "NetworkCallback was already unregistered");
4334 return;
4335 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004336 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4337 if (e.getValue() == networkCallback) {
4338 reqs.add(e.getKey());
4339 }
4340 }
4341 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4342 for (NetworkRequest r : reqs) {
4343 try {
4344 mService.releaseNetworkRequest(r);
4345 } catch (RemoteException e) {
4346 throw e.rethrowFromSystemServer();
4347 }
4348 // Only remove mapping if rpc was successful.
4349 sCallbacks.remove(r);
4350 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004351 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004352 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004353 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004354
4355 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004356 * Unregisters a callback previously registered via
4357 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4358 *
4359 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4360 * PendingIntent passed to
4361 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4362 * Cannot be null.
4363 */
Chalard Jean158702d2019-01-07 19:26:34 +09004364 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004365 releaseNetworkRequest(operation);
4366 }
4367
4368 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004369 * Informs the system whether it should switch to {@code network} regardless of whether it is
4370 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4371 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4372 * the system default network regardless of any other network that's currently connected. If
4373 * {@code always} is true, then the choice is remembered, so that the next time the user
4374 * connects to this network, the system will switch to it.
4375 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004376 * @param network The network to accept.
4377 * @param accept Whether to accept the network even if unvalidated.
4378 * @param always Whether to remember this choice in the future.
4379 *
4380 * @hide
4381 */
lucaslin2240ef62019-03-12 13:08:03 +08004382 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004383 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4384 try {
4385 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004386 } catch (RemoteException e) {
4387 throw e.rethrowFromSystemServer();
4388 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004389 }
4390
4391 /**
lucaslin2240ef62019-03-12 13:08:03 +08004392 * Informs the system whether it should consider the network as validated even if it only has
4393 * partial connectivity. If {@code accept} is true, then the network will be considered as
4394 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4395 * is remembered, so that the next time the user connects to this network, the system will
4396 * switch to it.
4397 *
4398 * @param network The network to accept.
4399 * @param accept Whether to consider the network as validated even if it has partial
4400 * connectivity.
4401 * @param always Whether to remember this choice in the future.
4402 *
4403 * @hide
4404 */
4405 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4406 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4407 try {
4408 mService.setAcceptPartialConnectivity(network, accept, always);
4409 } catch (RemoteException e) {
4410 throw e.rethrowFromSystemServer();
4411 }
4412 }
4413
4414 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004415 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4416 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4417 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4418 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4419 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004420 * @param network The network to accept.
4421 *
4422 * @hide
4423 */
lucaslin2240ef62019-03-12 13:08:03 +08004424 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004425 public void setAvoidUnvalidated(Network network) {
4426 try {
4427 mService.setAvoidUnvalidated(network);
4428 } catch (RemoteException e) {
4429 throw e.rethrowFromSystemServer();
4430 }
4431 }
4432
4433 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004434 * Requests that the system open the captive portal app on the specified network.
4435 *
4436 * @param network The network to log into.
4437 *
4438 * @hide
4439 */
paulhu8e96a752019-08-12 16:25:11 +08004440 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004441 public void startCaptivePortalApp(Network network) {
4442 try {
4443 mService.startCaptivePortalApp(network);
4444 } catch (RemoteException e) {
4445 throw e.rethrowFromSystemServer();
4446 }
4447 }
4448
4449 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004450 * Requests that the system open the captive portal app with the specified extras.
4451 *
4452 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4453 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004454 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004455 * @param appExtras Extras to include in the app start intent.
4456 * @hide
4457 */
4458 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004459 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004460 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004461 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004462 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004463 } catch (RemoteException e) {
4464 throw e.rethrowFromSystemServer();
4465 }
4466 }
4467
4468 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004469 * Determine whether the device is configured to avoid bad wifi.
4470 * @hide
4471 */
4472 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004473 @RequiresPermission(anyOf = {
4474 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4475 android.Manifest.permission.NETWORK_STACK})
4476 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004477 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004478 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004479 } catch (RemoteException e) {
4480 throw e.rethrowFromSystemServer();
4481 }
4482 }
4483
4484 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004485 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4486 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004487 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4488 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004489 *
4490 * An example of such an operation might be a time-sensitive foreground activity, such as a
4491 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4492 */
4493 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4494
4495 /**
4496 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4497 * a backup channel for traffic that is primarily going over another network.
4498 *
4499 * An example might be maintaining backup connections to peers or servers for the purpose of
4500 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4501 * on backup paths should be negligible compared to the traffic on the main path.
4502 */
4503 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4504
4505 /**
4506 * It is acceptable to use metered data to improve network latency and performance.
4507 */
4508 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4509
4510 /**
4511 * Return value to use for unmetered networks. On such networks we currently set all the flags
4512 * to true.
4513 * @hide
4514 */
4515 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4516 MULTIPATH_PREFERENCE_HANDOVER |
4517 MULTIPATH_PREFERENCE_RELIABILITY |
4518 MULTIPATH_PREFERENCE_PERFORMANCE;
4519
4520 /** @hide */
4521 @Retention(RetentionPolicy.SOURCE)
4522 @IntDef(flag = true, value = {
4523 MULTIPATH_PREFERENCE_HANDOVER,
4524 MULTIPATH_PREFERENCE_RELIABILITY,
4525 MULTIPATH_PREFERENCE_PERFORMANCE,
4526 })
4527 public @interface MultipathPreference {
4528 }
4529
4530 /**
4531 * Provides a hint to the calling application on whether it is desirable to use the
4532 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4533 * for multipath data transfer on this network when it is not the system default network.
4534 * Applications desiring to use multipath network protocols should call this method before
4535 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004536 *
4537 * @param network The network on which the application desires to use multipath data.
4538 * If {@code null}, this method will return the a preference that will generally
4539 * apply to metered networks.
4540 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4541 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004542 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004543 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004544 try {
4545 return mService.getMultipathPreference(network);
4546 } catch (RemoteException e) {
4547 throw e.rethrowFromSystemServer();
4548 }
4549 }
4550
4551 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004552 * Resets all connectivity manager settings back to factory defaults.
4553 * @hide
4554 */
paulhu8e96a752019-08-12 16:25:11 +08004555 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004556 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004557 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004558 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004559 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004560 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004561 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004562 }
4563 }
4564
4565 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004566 * Binds the current process to {@code network}. All Sockets created in the future
4567 * (and not explicitly bound via a bound SocketFactory from
4568 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4569 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4570 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4571 * work and all host name resolutions will fail. This is by design so an application doesn't
4572 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4573 * To clear binding pass {@code null} for {@code network}. Using individually bound
4574 * Sockets created by Network.getSocketFactory().createSocket() and
4575 * performing network-specific host name resolutions via
4576 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004577 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004578 *
4579 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4580 * the current binding.
4581 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4582 */
Chalard Jean158702d2019-01-07 19:26:34 +09004583 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004584 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004585 // instantiated.
4586 return setProcessDefaultNetwork(network);
4587 }
4588
4589 /**
4590 * Binds the current process to {@code network}. All Sockets created in the future
4591 * (and not explicitly bound via a bound SocketFactory from
4592 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4593 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4594 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4595 * work and all host name resolutions will fail. This is by design so an application doesn't
4596 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4597 * To clear binding pass {@code null} for {@code network}. Using individually bound
4598 * Sockets created by Network.getSocketFactory().createSocket() and
4599 * performing network-specific host name resolutions via
4600 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4601 * {@code setProcessDefaultNetwork}.
4602 *
4603 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4604 * the current binding.
4605 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4606 * @deprecated This function can throw {@link IllegalStateException}. Use
4607 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4608 * is a direct replacement.
4609 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004610 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004611 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004612 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004613 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4614
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004615 if (netId != NETID_UNSET) {
4616 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004617 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004618
4619 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4620 return false;
4621 }
4622
4623 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004624 // Set HTTP proxy system properties to match network.
4625 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004626 try {
4627 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4628 } catch (SecurityException e) {
4629 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4630 Log.e(TAG, "Can't set proxy properties", e);
4631 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004632 // Must flush DNS cache as new network may have different DNS resolutions.
4633 InetAddress.clearDnsCache();
4634 // Must flush socket pool as idle sockets will be bound to previous network and may
4635 // cause subsequent fetches to be performed on old network.
4636 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004637 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004638
4639 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004640 }
4641
4642 /**
4643 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004644 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004645 *
4646 * @return {@code Network} to which this process is bound, or {@code null}.
4647 */
Chalard Jean158702d2019-01-07 19:26:34 +09004648 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004649 public Network getBoundNetworkForProcess() {
4650 // Forcing callers to call thru non-static function ensures ConnectivityManager
4651 // instantiated.
4652 return getProcessDefaultNetwork();
4653 }
4654
4655 /**
4656 * Returns the {@link Network} currently bound to this process via
4657 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4658 *
4659 * @return {@code Network} to which this process is bound, or {@code null}.
4660 * @deprecated Using this function can lead to other functions throwing
4661 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4662 * {@code getBoundNetworkForProcess} is a direct replacement.
4663 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004664 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004665 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004666 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004667 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004668 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004669 return new Network(netId);
4670 }
4671
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004672 private void unsupportedStartingFrom(int version) {
4673 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004674 // The getApplicationInfo() call we make below is not supported in system context. Let
4675 // the call through here, and rely on the fact that ConnectivityService will refuse to
4676 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004677 return;
4678 }
4679
4680 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4681 throw new UnsupportedOperationException(
4682 "This method is not supported in target SDK version " + version + " and above");
4683 }
4684 }
4685
4686 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4687 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004688 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004689 // remove these exemptions. Note that this check is not secure, and apps can still access these
4690 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4691 // so is unsupported and may break in the future. http://b/22728205
4692 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004693 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004694 }
4695
Paul Jensen8cdda642014-05-29 10:12:39 -04004696 /**
4697 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004698 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004699 *
4700 * @param network The {@link Network} to bind host resolutions from the current process to, or
4701 * {@code null} to clear the current binding.
4702 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4703 * @hide
4704 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4705 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004706 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004707 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004708 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004709 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004710 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004711 }
Felipe Leme30511352016-01-22 09:44:57 -08004712
4713 /**
4714 * Device is not restricting metered network activity while application is running on
4715 * background.
4716 */
4717 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4718
4719 /**
4720 * Device is restricting metered network activity while application is running on background,
4721 * but application is allowed to bypass it.
4722 * <p>
4723 * In this state, application should take action to mitigate metered network access.
4724 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4725 */
4726 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4727
4728 /**
4729 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004730 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004731 * In this state, application should not try to use the network while running on background,
4732 * because it would be denied.
4733 */
4734 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4735
Felipe Lemed34c9af2016-01-27 14:46:39 -08004736 /**
4737 * A change in the background metered network activity restriction has occurred.
4738 * <p>
4739 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4740 * applies to them.
4741 * <p>
4742 * This is only sent to registered receivers, not manifest receivers.
4743 */
4744 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4745 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4746 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4747
Felipe Leme7e4c1852016-01-25 11:48:04 -08004748 /** @hide */
4749 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004750 @IntDef(flag = false, value = {
4751 RESTRICT_BACKGROUND_STATUS_DISABLED,
4752 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4753 RESTRICT_BACKGROUND_STATUS_ENABLED,
4754 })
Felipe Leme30511352016-01-22 09:44:57 -08004755 public @interface RestrictBackgroundStatus {
4756 }
4757
4758 private INetworkPolicyManager getNetworkPolicyManager() {
4759 synchronized (this) {
4760 if (mNPManager != null) {
4761 return mNPManager;
4762 }
4763 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4764 .getService(Context.NETWORK_POLICY_SERVICE));
4765 return mNPManager;
4766 }
4767 }
4768
4769 /**
4770 * Determines if the calling application is subject to metered network restrictions while
4771 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004772 *
4773 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4774 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4775 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004776 */
4777 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4778 try {
4779 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4780 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004781 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004782 }
4783 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004784
4785 /**
4786 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004787 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4788 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004789 *
4790 * @return Hash of network watchlist config file. Null if config does not exist.
4791 */
Chalard Jean158702d2019-01-07 19:26:34 +09004792 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004793 public byte[] getNetworkWatchlistConfigHash() {
4794 try {
4795 return mService.getNetworkWatchlistConfigHash();
4796 } catch (RemoteException e) {
4797 Log.e(TAG, "Unable to get watchlist config hash");
4798 throw e.rethrowFromSystemServer();
4799 }
4800 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004801
4802 /**
4803 * Returns the {@code uid} of the owner of a network connection.
4804 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004805 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4806 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004807 * @param local The local {@link InetSocketAddress} of a connection.
4808 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004809 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004810 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4811 * android.os.Process#INVALID_UID} if the connection is not found.
4812 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4813 * user.
4814 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004815 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004816 public int getConnectionOwnerUid(
4817 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004818 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4819 try {
4820 return mService.getConnectionOwnerUid(connectionInfo);
4821 } catch (RemoteException e) {
4822 throw e.rethrowFromSystemServer();
4823 }
4824 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004825
4826 private void printStackTrace() {
4827 if (DEBUG) {
4828 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4829 final StringBuffer sb = new StringBuffer();
4830 for (int i = 3; i < callStack.length; i++) {
4831 final String stackTrace = callStack[i].toString();
4832 if (stackTrace == null || stackTrace.contains("android.os")) {
4833 break;
4834 }
4835 sb.append(" [").append(stackTrace).append("]");
4836 }
4837 Log.d(TAG, "StackLog:" + sb.toString());
4838 }
4839 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004840
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004841 /** @hide */
4842 public TestNetworkManager startOrGetTestNetworkManager() {
4843 final IBinder tnBinder;
4844 try {
4845 tnBinder = mService.startOrGetTestNetworkService();
4846 } catch (RemoteException e) {
4847 throw e.rethrowFromSystemServer();
4848 }
4849
4850 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4851 }
4852
4853 /** @hide */
4854 public VpnManager createVpnManager() {
4855 return new VpnManager(mContext, mService);
4856 }
4857
4858 /** @hide */
4859 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4860 return new ConnectivityDiagnosticsManager(mContext, mService);
4861 }
4862
Cody Kestingf53a0752020-04-15 12:33:28 -07004863 /**
4864 * Simulates a Data Stall for the specified Network.
4865 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004866 * <p>This method should only be used for tests.
4867 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004868 * <p>The caller must be the owner of the specified Network.
4869 *
4870 * @param detectionMethod The detection method used to identify the Data Stall.
4871 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4872 * @param network The Network for which a Data Stall is being simluated.
4873 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4874 * @throws SecurityException if the caller is not the owner of the given network.
4875 * @hide
4876 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004877 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004878 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4879 android.Manifest.permission.NETWORK_STACK})
4880 public void simulateDataStall(int detectionMethod, long timestampMillis,
4881 @NonNull Network network, @NonNull PersistableBundle extras) {
4882 try {
4883 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4884 } catch (RemoteException e) {
4885 e.rethrowFromSystemServer();
4886 }
4887 }
James Mattis356a8792020-10-28 21:48:54 -07004888
Daniel Brightf9e945b2020-06-15 16:10:01 -07004889 @NonNull
4890 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4891
4892 /**
4893 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4894 * receive available QoS events related to the {@link Network} and local ip + port
4895 * specified within socketInfo.
4896 * <p/>
4897 * The same {@link QosCallback} must be unregistered before being registered a second time,
4898 * otherwise {@link QosCallbackRegistrationException} is thrown.
4899 * <p/>
4900 * This API does not, in itself, require any permission if called with a network that is not
4901 * restricted. However, the underlying implementation currently only supports the IMS network,
4902 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4903 * useful, because they'd never be called back on networks that they would have access to.
4904 *
4905 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4906 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4907 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4908 * @throws RuntimeException if the app already has too many callbacks registered.
4909 *
4910 * Exceptions after the time of registration is passed through
4911 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4912 *
4913 * @param socketInfo the socket information used to match QoS events
4914 * @param callback receives qos events that satisfy socketInfo
4915 * @param executor The executor on which the callback will be invoked. The provided
4916 * {@link Executor} must run callback sequentially, otherwise the order of
4917 * callbacks cannot be guaranteed.
4918 *
4919 * @hide
4920 */
4921 @SystemApi
4922 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4923 @NonNull final QosCallback callback,
4924 @CallbackExecutor @NonNull final Executor executor) {
4925 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4926 Objects.requireNonNull(callback, "callback must be non-null");
4927 Objects.requireNonNull(executor, "executor must be non-null");
4928
4929 try {
4930 synchronized (mQosCallbackConnections) {
4931 if (getQosCallbackConnection(callback) == null) {
4932 final QosCallbackConnection connection =
4933 new QosCallbackConnection(this, callback, executor);
4934 mQosCallbackConnections.add(connection);
4935 mService.registerQosSocketCallback(socketInfo, connection);
4936 } else {
4937 Log.e(TAG, "registerQosCallback: Callback already registered");
4938 throw new QosCallbackRegistrationException();
4939 }
4940 }
4941 } catch (final RemoteException e) {
4942 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4943
4944 // The same unregister method method is called for consistency even though nothing
4945 // will be sent to the ConnectivityService since the callback was never successfully
4946 // registered.
4947 unregisterQosCallback(callback);
4948 e.rethrowFromSystemServer();
4949 } catch (final ServiceSpecificException e) {
4950 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4951 unregisterQosCallback(callback);
4952 throw convertServiceException(e);
4953 }
4954 }
4955
4956 /**
4957 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4958 * events once unregistered and can be registered a second time.
4959 * <p/>
4960 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4961 *
4962 * @param callback the callback being unregistered
4963 *
4964 * @hide
4965 */
4966 @SystemApi
4967 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4968 Objects.requireNonNull(callback, "The callback must be non-null");
4969 try {
4970 synchronized (mQosCallbackConnections) {
4971 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4972 if (connection != null) {
4973 connection.stopReceivingMessages();
4974 mService.unregisterQosCallback(connection);
4975 mQosCallbackConnections.remove(connection);
4976 } else {
4977 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4978 }
4979 }
4980 } catch (final RemoteException e) {
4981 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4982 e.rethrowFromSystemServer();
4983 }
4984 }
4985
4986 /**
4987 * Gets the connection related to the callback.
4988 *
4989 * @param callback the callback to look up
4990 * @return the related connection
4991 */
4992 @Nullable
4993 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4994 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4995 // Checking by reference here is intentional
4996 if (connection.getCallback() == callback) {
4997 return connection;
4998 }
4999 }
5000 return null;
5001 }
Junyu Laia62493f2021-01-19 11:10:56 +00005002
5003 /**
5004 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
5005 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5006 * be used to request that the system provide a network without causing the network to be
5007 * in the foreground.
5008 *
5009 * <p>This method will attempt to find the best network that matches the passed
5010 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5011 * criteria. The platform will evaluate which network is the best at its own discretion.
5012 * Throughput, latency, cost per byte, policy, user preference and other considerations
5013 * may be factored in the decision of what is considered the best network.
5014 *
5015 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5016 * matching this request, while always attempting to match the request to a better network if
5017 * possible. If a better match is found, the platform will switch this request to the now-best
5018 * network and inform the app of the newly best network by invoking
5019 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5020 * will not try to maintain any other network than the best one currently matching the request:
5021 * a network not matching any network request may be disconnected at any time.
5022 *
5023 * <p>For example, an application could use this method to obtain a connected cellular network
5024 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5025 * radio to consume additional power. Or, an application could inform the system that it wants
5026 * a network supporting sending MMSes and have the system let it know about the currently best
5027 * MMS-supporting network through the provided {@link NetworkCallback}.
5028 *
5029 * <p>The status of the request can be followed by listening to the various callbacks described
5030 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5031 * used to direct traffic to the network (although accessing some networks may be subject to
5032 * holding specific permissions). Callers will learn about the specific characteristics of the
5033 * network through
5034 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5035 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5036 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5037 * matching the request at any given time; therefore when a better network matching the request
5038 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5039 * with the new network after which no further updates are given about the previously-best
5040 * network, unless it becomes the best again at some later time. All callbacks are invoked
5041 * in order on the same thread, which by default is a thread created by the framework running
5042 * in the app.
5043 *
5044 * <p>This{@link NetworkRequest} will live until released via
5045 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5046 * which point the system may let go of the network at any time.
5047 *
5048 * <p>It is presently unsupported to request a network with mutable
5049 * {@link NetworkCapabilities} such as
5050 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5051 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5052 * as these {@code NetworkCapabilities} represent states that a particular
5053 * network may never attain, and whether a network will attain these states
5054 * is unknown prior to bringing up the network so the framework does not
5055 * know how to go about satisfying a request with these capabilities.
5056 *
5057 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5058 * number of outstanding requests to 100 per app (identified by their UID), shared with
5059 * all variants of this method, of {@link #registerNetworkCallback} as well as
5060 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5061 * Requesting a network with this method will count toward this limit. If this limit is
5062 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5063 * make sure to unregister the callbacks with
5064 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5065 *
5066 * @param request {@link NetworkRequest} describing this request.
5067 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5068 * If null, the callback is invoked on the default internal Handler.
5069 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5070 * the callback must not be shared - it uniquely specifies this request.
5071 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5072 * @throws SecurityException if missing the appropriate permissions.
5073 * @throws RuntimeException if the app already has too many callbacks registered.
5074 *
5075 * @hide
5076 */
5077 @SystemApi(client = MODULE_LIBRARIES)
5078 @SuppressLint("ExecutorRegistration")
5079 @RequiresPermission(anyOf = {
5080 android.Manifest.permission.NETWORK_SETTINGS,
5081 android.Manifest.permission.NETWORK_STACK,
5082 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5083 })
5084 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
5085 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
5086 final NetworkCapabilities nc = request.networkCapabilities;
5087 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
5088 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
5089 }
James Mattis45d81842021-01-10 14:24:24 -08005090
5091 /**
5092 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
5093 * OnSetOemNetworkPreferenceListener)}.
5094 */
5095 private interface OnSetOemNetworkPreferenceListener {
5096 /**
5097 * Called when setOemNetworkPreference() successfully completes.
5098 */
5099 void onComplete();
5100 }
5101
5102 /**
5103 * Used by automotive devices to set the network preferences used to direct traffic at an
5104 * application level as per the given OemNetworkPreferences. An example use-case would be an
5105 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5106 * vehicle via a particular network.
5107 *
5108 * Calling this will overwrite the existing preference.
5109 *
5110 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5111 * @param executor the executor on which listener will be invoked.
5112 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5113 * communicate completion of setOemNetworkPreference(). This will only be
5114 * called once upon successful completion of setOemNetworkPreference().
5115 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5116 * @throws SecurityException if missing the appropriate permissions.
5117 * @throws UnsupportedOperationException if called on a non-automotive device.
5118 */
5119 private void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
5120 @Nullable @CallbackExecutor final Executor executor,
5121 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5122 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5123 if (null != listener) {
5124 Objects.requireNonNull(executor, "Executor must be non-null");
5125 }
5126 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5127 new IOnSetOemNetworkPreferenceListener.Stub() {
5128 @Override
5129 public void onComplete() {
5130 executor.execute(listener::onComplete);
5131 }
5132 };
5133
5134 try {
5135 mService.setOemNetworkPreference(preference, listenerInternal);
5136 } catch (RemoteException e) {
5137 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5138 throw e.rethrowFromSystemServer();
5139 }
5140 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005141}