blob: c160d82375e0ba3b67ca6c17c658f1775a2739f7 [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;
junyulai7514e312021-03-05 15:51:17 +080023import static android.net.NetworkRequest.Type.TRACK_BEST;
junyulaiad010792021-01-11 16:53:38 +080024import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +090025import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Brightf9e945b2020-06-15 16:10:01 -070026import static android.net.QosCallback.QosCallbackRegistrationException;
junyulaid05a1922019-01-15 11:32:44 +080027
junyulai4c95b082018-12-27 17:25:29 +080028import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080029import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090030import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000031import android.annotation.Nullable;
Jeff Sharkey656584a2017-04-24 11:18:03 -060032import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080033import android.annotation.SdkConstant;
34import android.annotation.SdkConstant.SdkConstantType;
Junyu Laia62493f2021-01-19 11:10:56 +000035import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080036import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060037import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070038import android.app.PendingIntent;
Artur Satayev9c2add62019-12-10 17:47:52 +000039import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070040import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070041import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080042import android.net.IpSecManager.UdpEncapsulationSocket;
43import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080044import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080045import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080046import android.net.TetheringManager.TetheringRequest;
Roshan Pius951c0032020-12-22 15:10:42 -080047import android.net.wifi.WifiNetworkSuggestion;
Robert Greenwalt2034b912009-08-12 16:08:25 -070048import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000049import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070050import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080051import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070052import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080053import android.os.IBinder;
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
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900459 public static final int TETHERING_WIFI = 0;
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
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900467 public static final int TETHERING_USB = 1;
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
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900475 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800476
477 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800478 * Wifi P2p tethering type.
479 * Wifi P2p tethering is set through events automatically, and don't
480 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
481 * @hide
482 */
markchiena0f8fd92019-12-25 19:40:32 +0800483 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800484
485 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800486 * Extra used for communicating with the TetherService. Includes the type of tethering to
487 * enable if any.
488 * @hide
489 */
markchien6ae63e52020-01-21 13:11:06 +0800490 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800491
492 /**
493 * Extra used for communicating with the TetherService. Includes the type of tethering for
494 * which to cancel provisioning.
495 * @hide
496 */
markchien6ae63e52020-01-21 13:11:06 +0800497 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800498
499 /**
500 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
501 * provisioning.
502 * @hide
503 */
markchien6ae63e52020-01-21 13:11:06 +0800504 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800505
506 /**
507 * Tells the TetherService to run a provision check now.
508 * @hide
509 */
markchien6ae63e52020-01-21 13:11:06 +0800510 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800511
512 /**
513 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
514 * which will receive provisioning results. Can be left empty.
515 * @hide
516 */
markchien6ae63e52020-01-21 13:11:06 +0800517 public static final String EXTRA_PROVISION_CALLBACK =
518 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800519
520 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800521 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700522 * @hide
523 */
paulhu74357e72020-01-13 16:46:45 +0800524 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700525 public static final int TYPE_NONE = -1;
526
527 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900528 * A Mobile data connection. Devices may support more than one.
529 *
530 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
531 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
532 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700533 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900534 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700535 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900536
Robert Greenwalt2034b912009-08-12 16:08:25 -0700537 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900538 * A WIFI data connection. Devices may support more than one.
539 *
540 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
541 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
542 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700543 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900544 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700545 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900546
Robert Greenwalt2034b912009-08-12 16:08:25 -0700547 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800548 * An MMS-specific Mobile data connection. This network type may use the
549 * same network interface as {@link #TYPE_MOBILE} or it may use a different
550 * one. This is used by applications needing to talk to the carrier's
551 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900552 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900553 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900554 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900555 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700556 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700557 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700558 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900559
Robert Greenwalt2034b912009-08-12 16:08:25 -0700560 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800561 * A SUPL-specific Mobile data connection. This network type may use the
562 * same network interface as {@link #TYPE_MOBILE} or it may use a different
563 * one. This is used by applications needing to talk to the carrier's
564 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900565 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900566 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900567 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900568 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700569 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700570 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900572
Robert Greenwalt2034b912009-08-12 16:08:25 -0700573 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800574 * A DUN-specific Mobile data connection. This network type may use the
575 * same network interface as {@link #TYPE_MOBILE} or it may use a different
576 * one. This is sometimes by the system when setting up an upstream connection
577 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900578 *
579 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
580 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
581 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700582 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900583 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900585
Robert Greenwalt2034b912009-08-12 16:08:25 -0700586 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800587 * A High Priority Mobile data connection. This network type uses the
588 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900589 * is different.
590 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900591 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
592 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
593 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700594 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700595 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700596 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900597
jshbfa81722010-03-11 15:04:43 -0800598 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900599 * A WiMAX data connection.
600 *
601 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
602 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
603 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800604 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900605 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800606 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800607
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800608 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900609 * A Bluetooth data connection.
610 *
611 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
612 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
613 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800614 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900615 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800616 public static final int TYPE_BLUETOOTH = 7;
617
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700618 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800619 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900620 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700621 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900622 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800623 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800624
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700625 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900626 * An Ethernet data connection.
627 *
628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
630 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700631 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900632 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800633 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700634
Wink Savilleb7c92c72011-03-12 14:52:01 -0800635 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800636 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900637 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800638 * {@hide}
639 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900640 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900641 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800642 public static final int TYPE_MOBILE_FOTA = 10;
643
644 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800645 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900646 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800647 * {@hide}
648 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900649 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100650 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800651 public static final int TYPE_MOBILE_IMS = 11;
652
653 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800654 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900655 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800656 * {@hide}
657 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900658 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900659 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800660 public static final int TYPE_MOBILE_CBS = 12;
661
repo syncf5de5572011-07-29 23:55:49 -0700662 /**
663 * A Wi-Fi p2p connection. Only requesting processes will have access to
664 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900665 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700666 * {@hide}
667 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900668 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800669 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700670 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800671
Wink Saville512c2202013-07-29 15:00:57 -0700672 /**
673 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900674 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700675 * {@hide}
676 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900677 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100678 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700679 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700680
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900681 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700682 * Emergency PDN connection for emergency services. This
683 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900684 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700685 * {@hide}
686 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900687 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900688 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700689 public static final int TYPE_MOBILE_EMERGENCY = 15;
690
Hui Lu865b70d2014-01-15 11:05:36 -0500691 /**
692 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900693 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500694 * {@hide}
695 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900696 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900697 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500698 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700699
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700700 /**
701 * A virtual network using one or more native bearers.
702 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900703 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700704 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900705 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700706 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500707
Benedict Wongbdfaa482018-11-14 17:40:55 -0800708 /**
709 * A network that is exclusively meant to be used for testing
710 *
711 * @deprecated Use {@link NetworkCapabilities} instead.
712 * @hide
713 */
714 @Deprecated
715 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700716
Chalard Jeanaea539a2020-03-25 01:24:04 +0900717 /**
718 * @deprecated Use {@link NetworkCapabilities} instead.
719 * @hide
720 */
721 @Deprecated
722 @Retention(RetentionPolicy.SOURCE)
723 @IntDef(prefix = { "TYPE_" }, value = {
724 TYPE_NONE,
725 TYPE_MOBILE,
726 TYPE_WIFI,
727 TYPE_MOBILE_MMS,
728 TYPE_MOBILE_SUPL,
729 TYPE_MOBILE_DUN,
730 TYPE_MOBILE_HIPRI,
731 TYPE_WIMAX,
732 TYPE_BLUETOOTH,
733 TYPE_DUMMY,
734 TYPE_ETHERNET,
735 TYPE_MOBILE_FOTA,
736 TYPE_MOBILE_IMS,
737 TYPE_MOBILE_CBS,
738 TYPE_WIFI_P2P,
739 TYPE_MOBILE_IA,
740 TYPE_MOBILE_EMERGENCY,
741 TYPE_PROXY,
742 TYPE_VPN,
743 TYPE_TEST
744 })
745 public @interface LegacyNetworkType {}
746
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900747 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
748 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
749 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
750 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
751 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
752
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700753 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800754 public static final int MAX_RADIO_TYPE = TYPE_TEST;
755
756 /** {@hide} */
757 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800758
Hugo Benichiad353f42017-06-20 14:07:59 +0900759 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
760
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800761 /**
762 * If you want to set the default network preference,you can directly
763 * change the networkAttributes array in framework's config.xml.
764 *
765 * @deprecated Since we support so many more networks now, the single
766 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800767 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800768 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800769 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800770 * from an App.
771 */
772 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800773 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
774
Jeff Sharkey8c870452012-09-26 22:03:49 -0700775 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700776 * @hide
777 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900778 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700779
Paul Jensen5dea4352014-07-11 12:28:19 -0400780 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900781 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
782 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900783 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900784 * @hide
785 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900786 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900787 new NetworkRequest.Builder().clearCapabilities().build();
788
789 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400790 * A NetID indicating no Network is selected.
791 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
792 * @hide
793 */
794 public static final int NETID_UNSET = 0;
795
Erik Klineb0be3e62017-10-30 15:29:44 +0900796 /**
797 * Private DNS Mode values.
798 *
799 * The "private_dns_mode" global setting stores a String value which is
800 * expected to be one of the following.
801 */
802
803 /**
804 * @hide
805 */
806 public static final String PRIVATE_DNS_MODE_OFF = "off";
807 /**
808 * @hide
809 */
810 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
811 /**
812 * @hide
813 */
814 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
815 /**
816 * The default Private DNS mode.
817 *
818 * This may change from release to release or may become dependent upon
819 * the capabilities of the underlying platform.
820 *
821 * @hide
822 */
Erik Klinea7edf6f2018-05-16 16:41:57 +0900823 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Klineb0be3e62017-10-30 15:29:44 +0900824
Chalard Jeana3b77512019-04-09 15:46:21 +0900825 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700826 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900827
Paul Jensenc0618a62014-12-10 15:12:18 -0500828 /**
829 * A kludge to facilitate static access where a Context pointer isn't available, like in the
830 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
831 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
832 * methods that take a Context argument.
833 */
834 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800835
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900836 private final Context mContext;
837
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 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001072 * Adds or removes a requirement for given UID ranges to use the VPN.
1073 *
1074 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1075 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1076 * otherwise have permission to bypass the VPN (e.g., because they have the
1077 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1078 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1079 * set to {@code false}, a previously-added restriction is removed.
1080 * <p>
1081 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1082 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1083 * remove a previously-added range, the exact range must be removed as is.
1084 * <p>
1085 * The changes are applied asynchronously and may not have been applied by the time the method
1086 * returns. Apps will be notified about any changes that apply to them via
1087 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1088 * effect.
1089 * <p>
1090 * This method should be called only by the VPN code.
1091 *
1092 * @param ranges the UID ranges to restrict
1093 * @param requireVpn whether the specified UID ranges must use a VPN
1094 *
1095 * TODO: expose as @SystemApi.
1096 * @hide
1097 */
1098 @RequiresPermission(anyOf = {
1099 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1100 android.Manifest.permission.NETWORK_STACK})
1101 public void setRequireVpnForUids(boolean requireVpn,
1102 @NonNull Collection<Range<Integer>> ranges) {
1103 Objects.requireNonNull(ranges);
1104 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1105 // This method is not necessarily expected to be used outside the system server, so
1106 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1107 // stack process, or by tests.
1108 UidRange[] rangesArray = new UidRange[ranges.size()];
1109 int index = 0;
1110 for (Range<Integer> range : ranges) {
1111 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1112 }
1113 try {
1114 mService.setRequireVpnForUids(requireVpn, rangesArray);
1115 } catch (RemoteException e) {
1116 throw e.rethrowFromSystemServer();
1117 }
1118 }
1119
1120 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001121 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1122 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1123 * but is still supported for backwards compatibility.
1124 * <p>
1125 * This type of VPN is assumed always to use the system default network, and must always declare
1126 * exactly one underlying network, which is the network that was the default when the VPN
1127 * connected.
1128 * <p>
1129 * Calling this method with {@code true} enables legacy behaviour, specifically:
1130 * <ul>
1131 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1132 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1133 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1134 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1135 * underlying the VPN.</li>
1136 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1137 * similarly replaced by the VPN network state.</li>
1138 * <li>Information on current network interfaces passed to NetworkStatsService will not
1139 * include any VPN interfaces.</li>
1140 * </ul>
1141 *
1142 * @param enabled whether legacy lockdown VPN is enabled or disabled
1143 *
1144 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1145 *
1146 * @hide
1147 */
1148 @RequiresPermission(anyOf = {
1149 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1150 android.Manifest.permission.NETWORK_SETTINGS})
1151 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1152 try {
1153 mService.setLegacyLockdownVpnEnabled(enabled);
1154 } catch (RemoteException e) {
1155 throw e.rethrowFromSystemServer();
1156 }
1157 }
1158
1159 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001160 * Returns details about the currently active default data network
1161 * for a given uid. This is for internal use only to avoid spying
1162 * other apps.
1163 *
1164 * @return a {@link NetworkInfo} object for the current default network
1165 * for the given uid or {@code null} if no default network is
1166 * available for the specified uid.
1167 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001168 * {@hide}
1169 */
paulhu8e96a752019-08-12 16:25:11 +08001170 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001171 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001172 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001173 return getActiveNetworkInfoForUid(uid, false);
1174 }
1175
1176 /** {@hide} */
1177 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001178 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001179 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001180 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001181 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001182 }
1183 }
1184
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001185 /**
1186 * Returns connection status information about a particular
1187 * network type.
1188 *
1189 * @param networkType integer specifying which networkType in
1190 * which you're interested.
1191 * @return a {@link NetworkInfo} object for the requested
1192 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001193 * supported by the device. If {@code networkType} is
1194 * TYPE_VPN and a VPN is active for the calling app,
1195 * then this method will try to return one of the
1196 * underlying networks for the VPN or null if the
1197 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001198 *
Paul Jensendda8e592015-03-18 12:23:02 -04001199 * @deprecated This method does not support multiple connected networks
1200 * of the same type. Use {@link #getAllNetworks} and
1201 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001202 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001203 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001204 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001205 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001206 public NetworkInfo getNetworkInfo(int networkType) {
1207 try {
1208 return mService.getNetworkInfo(networkType);
1209 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001210 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001211 }
1212 }
1213
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001214 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001215 * Returns connection status information about a particular
1216 * Network.
1217 *
1218 * @param network {@link Network} specifying which network
1219 * in which you're interested.
1220 * @return a {@link NetworkInfo} object for the requested
1221 * network or {@code null} if the {@code Network}
1222 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001223 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001224 */
junyulai9826e7f2018-12-13 12:47:51 +08001225 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001226 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001227 @Nullable
1228 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001229 return getNetworkInfoForUid(network, Process.myUid(), false);
1230 }
1231
1232 /** {@hide} */
1233 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001234 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001235 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001236 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001237 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001238 }
1239 }
1240
1241 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001242 * Returns connection status information about all network
1243 * types supported by the device.
1244 *
1245 * @return an array of {@link NetworkInfo} objects. Check each
1246 * {@link NetworkInfo#getType} for which type each applies.
1247 *
Paul Jensendda8e592015-03-18 12:23:02 -04001248 * @deprecated This method does not support multiple connected networks
1249 * of the same type. Use {@link #getAllNetworks} and
1250 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001251 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001252 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001253 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001254 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001255 public NetworkInfo[] getAllNetworkInfo() {
1256 try {
1257 return mService.getAllNetworkInfo();
1258 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001259 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001260 }
1261 }
1262
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001263 /**
junyulaiebd15162021-03-03 12:09:05 +08001264 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1265 * connected.
1266 * @hide
1267 */
1268 @SystemApi(client = MODULE_LIBRARIES)
1269 @RequiresPermission(anyOf = {
1270 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1271 android.Manifest.permission.NETWORK_STACK,
1272 android.Manifest.permission.NETWORK_SETTINGS})
1273 @NonNull
1274 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1275 try {
1276 return mService.getAllNetworkStateSnapshot();
1277 } catch (RemoteException e) {
1278 throw e.rethrowFromSystemServer();
1279 }
1280 }
1281
1282 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001283 * Returns the {@link Network} object currently serving a given type, or
1284 * null if the given type is not connected.
1285 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001286 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001287 * @deprecated This method does not support multiple connected networks
1288 * of the same type. Use {@link #getAllNetworks} and
1289 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001290 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001291 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001292 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001293 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001294 public Network getNetworkForType(int networkType) {
1295 try {
1296 return mService.getNetworkForType(networkType);
1297 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001298 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001299 }
1300 }
1301
1302 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001303 * Returns an array of all {@link Network} currently tracked by the
1304 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001305 *
1306 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001307 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001308 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001309 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001310 public Network[] getAllNetworks() {
1311 try {
1312 return mService.getAllNetworks();
1313 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001314 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001315 }
1316 }
1317
1318 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001319 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001320 * the Networks that applications run by the given user will use by default.
1321 * @hide
1322 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001323 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001324 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1325 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001326 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001327 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001328 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001329 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001330 }
1331 }
1332
1333 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001334 * Returns the IP information for the current default network.
1335 *
1336 * @return a {@link LinkProperties} object describing the IP info
1337 * for the current default network, or {@code null} if there
1338 * is no current default network.
1339 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001340 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001341 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1342 * value of {@link #getActiveNetwork()} instead. In particular,
1343 * this method will return non-null LinkProperties even if the
1344 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001345 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001346 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001347 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001348 public LinkProperties getActiveLinkProperties() {
1349 try {
1350 return mService.getActiveLinkProperties();
1351 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001352 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001353 }
1354 }
1355
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001356 /**
1357 * Returns the IP information for a given network type.
1358 *
1359 * @param networkType the network type of interest.
1360 * @return a {@link LinkProperties} object describing the IP info
1361 * for the given networkType, or {@code null} if there is
1362 * no current default network.
1363 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001364 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001365 * @deprecated This method does not support multiple connected networks
1366 * of the same type. Use {@link #getAllNetworks},
1367 * {@link #getNetworkInfo(android.net.Network)}, and
1368 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001369 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001370 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001371 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001372 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001373 public LinkProperties getLinkProperties(int networkType) {
1374 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001375 return mService.getLinkPropertiesForType(networkType);
1376 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001377 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001378 }
1379 }
1380
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001381 /**
1382 * Get the {@link LinkProperties} for the given {@link Network}. This
1383 * will return {@code null} if the network is unknown.
1384 *
1385 * @param network The {@link Network} object identifying the network in question.
1386 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001387 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001388 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001389 @Nullable
1390 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001391 try {
1392 return mService.getLinkProperties(network);
1393 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001394 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001395 }
1396 }
1397
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001398 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001399 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001400 * will return {@code null} if the network is unknown.
1401 *
Roshan Pius951c0032020-12-22 15:10:42 -08001402 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1403 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1404 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1405 * this location sensitive information (subject to app's location permissions) will be
1406 * noted by system. To include any location sensitive data in {@link TransportInfo},
1407 * use a {@link NetworkCallback} with
1408 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1409 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001410 * @param network The {@link Network} object identifying the network in question.
Roshan Pius951c0032020-12-22 15:10:42 -08001411 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001412 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001413 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001414 @Nullable
1415 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001416 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001417 return mService.getNetworkCapabilities(
1418 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001419 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001420 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001421 }
1422 }
1423
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001424 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001425 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001426 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1427 * portal is present.
1428 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1429 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1430 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001431 * The system network validation may be using different strategies to detect captive portals,
1432 * so this method does not necessarily return a URL used by the system. It only returns a URL
1433 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001434 *
Udam Sainicd645462016-01-04 12:16:14 -08001435 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001436 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1437 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001438 */
paulhu8e96a752019-08-12 16:25:11 +08001439 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001440 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001441 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001442 public String getCaptivePortalServerUrl() {
1443 try {
1444 return mService.getCaptivePortalServerUrl();
1445 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001446 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001447 }
1448 }
1449
1450 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001451 * Tells the underlying networking system that the caller wants to
1452 * begin using the named feature. The interpretation of {@code feature}
1453 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001454 *
1455 * <p>This method requires the caller to hold either the
1456 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1457 * or the ability to modify system settings as determined by
1458 * {@link android.provider.Settings.System#canWrite}.</p>
1459 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001460 * @param networkType specifies which network the request pertains to
1461 * @param feature the name of the feature to be used
1462 * @return an integer value representing the outcome of the request.
1463 * The interpretation of this value is specific to each networking
1464 * implementation+feature combination, except that the value {@code -1}
1465 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001466 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001467 * @deprecated Deprecated in favor of the cleaner
1468 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001469 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001470 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001471 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001472 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001473 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001474 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001475 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001476 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1477 if (netCap == null) {
1478 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1479 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001480 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001481 }
1482
1483 NetworkRequest request = null;
1484 synchronized (sLegacyRequests) {
1485 LegacyRequest l = sLegacyRequests.get(netCap);
1486 if (l != null) {
1487 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1488 renewRequestLocked(l);
1489 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001490 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001491 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001492 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001493 }
1494 }
1495
1496 request = requestNetworkForFeatureLocked(netCap);
1497 }
1498 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001499 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001500 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001501 } else {
1502 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001503 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001504 }
1505 }
1506
1507 /**
1508 * Tells the underlying networking system that the caller is finished
1509 * using the named feature. The interpretation of {@code feature}
1510 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001511 *
1512 * <p>This method requires the caller to hold either the
1513 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1514 * or the ability to modify system settings as determined by
1515 * {@link android.provider.Settings.System#canWrite}.</p>
1516 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001517 * @param networkType specifies which network the request pertains to
1518 * @param feature the name of the feature that is no longer needed
1519 * @return an integer value representing the outcome of the request.
1520 * The interpretation of this value is specific to each networking
1521 * implementation+feature combination, except that the value {@code -1}
1522 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001523 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001524 * @deprecated Deprecated in favor of the cleaner
1525 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001526 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001527 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001528 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001529 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001530 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001531 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001532 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001533 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1534 if (netCap == null) {
1535 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1536 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001537 return -1;
1538 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001539
Paul Jensen49f74a32014-12-17 10:39:34 -05001540 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001541 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001542 }
1543 return 1;
1544 }
1545
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001546 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001547 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1548 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001549 switch (feature) {
1550 case "enableCBS":
1551 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1552 case "enableDUN":
1553 case "enableDUNAlways":
1554 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1555 case "enableFOTA":
1556 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1557 case "enableHIPRI":
1558 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1559 case "enableIMS":
1560 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1561 case "enableMMS":
1562 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1563 case "enableSUPL":
1564 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1565 default:
1566 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001567 }
Erik Klinece55eb12017-01-26 18:08:28 +09001568 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1569 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001570 }
1571 return null;
1572 }
1573
Robert Greenwalt802c1102014-06-02 15:32:02 -07001574 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001575 if (netCap == null) return TYPE_NONE;
1576 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1577 return TYPE_MOBILE_CBS;
1578 }
1579 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1580 return TYPE_MOBILE_IMS;
1581 }
1582 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1583 return TYPE_MOBILE_FOTA;
1584 }
1585 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1586 return TYPE_MOBILE_DUN;
1587 }
1588 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1589 return TYPE_MOBILE_SUPL;
1590 }
1591 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1592 return TYPE_MOBILE_MMS;
1593 }
1594 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1595 return TYPE_MOBILE_HIPRI;
1596 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001597 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1598 return TYPE_WIFI_P2P;
1599 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001600 return TYPE_NONE;
1601 }
1602
1603 private static class LegacyRequest {
1604 NetworkCapabilities networkCapabilities;
1605 NetworkRequest networkRequest;
1606 int expireSequenceNumber;
1607 Network currentNetwork;
1608 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001609
1610 private void clearDnsBinding() {
1611 if (currentNetwork != null) {
1612 currentNetwork = null;
1613 setProcessDefaultNetworkForHostResolution(null);
1614 }
1615 }
1616
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001617 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001618 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001619 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001620 currentNetwork = network;
1621 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001622 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001623 }
1624 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001625 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001626 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001627 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1628 }
1629 };
1630 }
1631
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001632 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001633 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1634 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001635
1636 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1637 synchronized (sLegacyRequests) {
1638 LegacyRequest l = sLegacyRequests.get(netCap);
1639 if (l != null) return l.networkRequest;
1640 }
1641 return null;
1642 }
1643
1644 private void renewRequestLocked(LegacyRequest l) {
1645 l.expireSequenceNumber++;
1646 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1647 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1648 }
1649
1650 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1651 int ourSeqNum = -1;
1652 synchronized (sLegacyRequests) {
1653 LegacyRequest l = sLegacyRequests.get(netCap);
1654 if (l == null) return;
1655 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001656 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001657 }
1658 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1659 }
1660
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001661 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001662 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1663 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001664 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001665 try {
1666 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001667 } catch (RemoteException e) {
1668 throw e.rethrowFromSystemServer();
1669 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001670 LegacyRequest l = new LegacyRequest();
1671 l.networkCapabilities = netCap;
1672 l.delay = delay;
1673 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001674 l.networkRequest = sendRequestForNetwork(
1675 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001676 if (l.networkRequest == null) return null;
1677 sLegacyRequests.put(netCap, l);
1678 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1679 return l.networkRequest;
1680 }
1681
1682 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1683 if (delay >= 0) {
1684 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001685 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001686 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1687 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001688 }
1689 }
1690
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001691 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001692 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1693 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001694 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001695 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001696 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001697 if (l == null) return false;
1698 unregisterNetworkCallback(l.networkCallback);
1699 l.clearDnsBinding();
1700 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001701 }
1702
Erik Klinece55eb12017-01-26 18:08:28 +09001703 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1704 static {
1705 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1706 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1707 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1708 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1709 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1710 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1711 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1712 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1713 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1714 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1715 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1716 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1717 }
1718
1719 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1720 static {
1721 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1722 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1723 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1724 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1725 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1726 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1727 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1728 }
1729
1730 /**
1731 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1732 * instance suitable for registering a request or callback. Throws an
1733 * IllegalArgumentException if no mapping from the legacy type to
1734 * NetworkCapabilities is known.
1735 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001736 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1737 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001738 * @hide
1739 */
1740 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1741 final NetworkCapabilities nc = new NetworkCapabilities();
1742
1743 // Map from type to transports.
1744 final int NOT_FOUND = -1;
1745 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichibc1104b2017-05-09 15:19:01 +09001746 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001747 nc.addTransportType(transport);
1748
1749 // Map from type to capabilities.
1750 nc.addCapability(sLegacyTypeToCapability.get(
1751 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1752 nc.maybeMarkCapabilitiesRestricted();
1753 return nc;
1754 }
1755
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001756 /** @hide */
1757 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001758 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001759 public PacketKeepaliveCallback() {
1760 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001761 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001762 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001763 public void onStarted() {}
1764 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001765 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001766 public void onStopped() {}
1767 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001768 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001769 public void onError(int error) {}
1770 }
1771
1772 /**
1773 * Allows applications to request that the system periodically send specific packets on their
1774 * behalf, using hardware offload to save battery power.
1775 *
1776 * To request that the system send keepalives, call one of the methods that return a
1777 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1778 * passing in a non-null callback. If the callback is successfully started, the callback's
1779 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1780 * specifying one of the {@code ERROR_*} constants in this class.
1781 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001782 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1783 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1784 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001785 *
junyulai4c95b082018-12-27 17:25:29 +08001786 * @deprecated Use {@link SocketKeepalive} instead.
1787 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001788 * @hide
1789 */
1790 public class PacketKeepalive {
1791
1792 private static final String TAG = "PacketKeepalive";
1793
1794 /** @hide */
1795 public static final int SUCCESS = 0;
1796
1797 /** @hide */
1798 public static final int NO_KEEPALIVE = -1;
1799
1800 /** @hide */
1801 public static final int BINDER_DIED = -10;
1802
1803 /** The specified {@code Network} is not connected. */
1804 public static final int ERROR_INVALID_NETWORK = -20;
1805 /** The specified IP addresses are invalid. For example, the specified source IP address is
1806 * not configured on the specified {@code Network}. */
1807 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1808 /** The requested port is invalid. */
1809 public static final int ERROR_INVALID_PORT = -22;
1810 /** The packet length is invalid (e.g., too long). */
1811 public static final int ERROR_INVALID_LENGTH = -23;
1812 /** The packet transmission interval is invalid (e.g., too short). */
1813 public static final int ERROR_INVALID_INTERVAL = -24;
1814
1815 /** The hardware does not support this request. */
1816 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001817 /** The hardware returned an error. */
1818 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001819
Nathan Harold0990bc82018-02-14 13:09:45 -08001820 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001821 public static final int NATT_PORT = 4500;
1822
Nathan Harold0990bc82018-02-14 13:09:45 -08001823 /** The minimum interval in seconds between keepalive packet transmissions */
1824 public static final int MIN_INTERVAL = 10;
1825
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001826 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001827 private final ISocketKeepaliveCallback mCallback;
1828 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001829
1830 private volatile Integer mSlot;
1831
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001832 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001833 public void stop() {
1834 try {
junyulai070f9ff2019-01-16 20:23:34 +08001835 mExecutor.execute(() -> {
1836 try {
1837 if (mSlot != null) {
1838 mService.stopKeepalive(mNetwork, mSlot);
1839 }
1840 } catch (RemoteException e) {
1841 Log.e(TAG, "Error stopping packet keepalive: ", e);
1842 throw e.rethrowFromSystemServer();
1843 }
1844 });
1845 } catch (RejectedExecutionException e) {
1846 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001847 }
1848 }
1849
1850 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09001851 Preconditions.checkNotNull(network, "network cannot be null");
1852 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001853 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001854 mExecutor = Executors.newSingleThreadExecutor();
1855 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001856 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001857 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001858 final long token = Binder.clearCallingIdentity();
1859 try {
1860 mExecutor.execute(() -> {
1861 mSlot = slot;
1862 callback.onStarted();
1863 });
1864 } finally {
1865 Binder.restoreCallingIdentity(token);
1866 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001867 }
junyulai070f9ff2019-01-16 20:23:34 +08001868
1869 @Override
1870 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001871 final long token = Binder.clearCallingIdentity();
1872 try {
1873 mExecutor.execute(() -> {
1874 mSlot = null;
1875 callback.onStopped();
1876 });
1877 } finally {
1878 Binder.restoreCallingIdentity(token);
1879 }
junyulai070f9ff2019-01-16 20:23:34 +08001880 mExecutor.shutdown();
1881 }
1882
1883 @Override
1884 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001885 final long token = Binder.clearCallingIdentity();
1886 try {
1887 mExecutor.execute(() -> {
1888 mSlot = null;
1889 callback.onError(error);
1890 });
1891 } finally {
1892 Binder.restoreCallingIdentity(token);
1893 }
junyulai070f9ff2019-01-16 20:23:34 +08001894 mExecutor.shutdown();
1895 }
1896
1897 @Override
1898 public void onDataReceived() {
1899 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1900 // this callback when data is received.
1901 }
1902 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001903 }
1904 }
1905
1906 /**
1907 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1908 *
junyulai4c95b082018-12-27 17:25:29 +08001909 * @deprecated Use {@link #createSocketKeepalive} instead.
1910 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001911 * @hide
1912 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001913 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001914 public PacketKeepalive startNattKeepalive(
1915 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1916 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1917 final PacketKeepalive k = new PacketKeepalive(network, callback);
1918 try {
junyulai070f9ff2019-01-16 20:23:34 +08001919 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001920 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1921 } catch (RemoteException e) {
1922 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001923 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001924 }
1925 return k;
1926 }
1927
Chiachang Wang619319a2021-01-15 11:06:21 +08001928 // Construct an invalid fd.
1929 private ParcelFileDescriptor createInvalidFd() {
1930 final int invalidFd = -1;
1931 return ParcelFileDescriptor.adoptFd(invalidFd);
1932 }
1933
The Android Open Source Project28527d22009-03-03 19:31:44 -08001934 /**
junyulai4c95b082018-12-27 17:25:29 +08001935 * Request that keepalives be started on a IPsec NAT-T socket.
1936 *
1937 * @param network The {@link Network} the socket is on.
1938 * @param socket The socket that needs to be kept alive.
1939 * @param source The source address of the {@link UdpEncapsulationSocket}.
1940 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1941 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1942 * must run callback sequentially, otherwise the order of callbacks cannot be
1943 * guaranteed.
1944 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1945 * changes. Must be extended by applications that use this API.
1946 *
junyulai0835a1e2019-01-08 20:04:33 +08001947 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1948 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001949 **/
junyulai7e06ad42019-03-04 22:45:36 +08001950 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001951 @NonNull UdpEncapsulationSocket socket,
1952 @NonNull InetAddress source,
1953 @NonNull InetAddress destination,
1954 @NonNull @CallbackExecutor Executor executor,
1955 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001956 ParcelFileDescriptor dup;
1957 try {
junyulai828dad12019-03-27 11:00:37 +08001958 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1959 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001960 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1961 } catch (IOException ignored) {
1962 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1963 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001964 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001965 }
1966 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1967 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08001968 }
1969
1970 /**
1971 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1972 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1973 *
1974 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08001975 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1976 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1977 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08001978 * @param source The source address of the {@link UdpEncapsulationSocket}.
1979 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1980 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1981 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1982 * must run callback sequentially, otherwise the order of callbacks cannot be
1983 * guaranteed.
1984 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1985 * changes. Must be extended by applications that use this API.
1986 *
junyulai0835a1e2019-01-08 20:04:33 +08001987 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1988 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08001989 * @hide
1990 */
1991 @SystemApi
1992 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08001993 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1994 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08001995 @NonNull InetAddress source,
1996 @NonNull InetAddress destination,
1997 @NonNull @CallbackExecutor Executor executor,
1998 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001999 ParcelFileDescriptor dup;
2000 try {
junyulai828dad12019-03-27 11:00:37 +08002001 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002002 dup = pfd.dup();
2003 } catch (IOException ignored) {
2004 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2005 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002006 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002007 }
2008 return new NattSocketKeepalive(mService, network, dup,
2009 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002010 }
2011
2012 /**
junyulai0835a1e2019-01-08 20:04:33 +08002013 * Request that keepalives be started on a TCP socket.
2014 * The socket must be established.
2015 *
2016 * @param network The {@link Network} the socket is on.
2017 * @param socket The socket that needs to be kept alive.
2018 * @param executor The executor on which callback will be invoked. This implementation assumes
2019 * the provided {@link Executor} runs the callbacks in sequence with no
2020 * concurrency. Failing this, no guarantee of correctness can be made. It is
2021 * the responsibility of the caller to ensure the executor provides this
2022 * guarantee. A simple way of creating such an executor is with the standard
2023 * tool {@code Executors.newSingleThreadExecutor}.
2024 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2025 * changes. Must be extended by applications that use this API.
2026 *
2027 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2028 * given socket.
2029 * @hide
2030 */
2031 @SystemApi
2032 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002033 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002034 @NonNull Socket socket,
2035 @NonNull Executor executor,
2036 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002037 ParcelFileDescriptor dup;
2038 try {
2039 dup = ParcelFileDescriptor.fromSocket(socket);
2040 } catch (UncheckedIOException 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 TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002046 }
2047
2048 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002049 * Ensure that a network route exists to deliver traffic to the specified
2050 * host via the specified network interface. An attempt to add a route that
2051 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002052 *
2053 * <p>This method requires the caller to hold either the
2054 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2055 * or the ability to modify system settings as determined by
2056 * {@link android.provider.Settings.System#canWrite}.</p>
2057 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002058 * @param networkType the type of the network over which traffic to the specified
2059 * host is to be routed
2060 * @param hostAddress the IP address of the host to which the route is desired
2061 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002062 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002063 * @deprecated Deprecated in favor of the
2064 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2065 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002066 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002067 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002068 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002069 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002070 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002071 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002072 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002073 }
2074
2075 /**
2076 * Ensure that a network route exists to deliver traffic to the specified
2077 * host via the specified network interface. An attempt to add a route that
2078 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002079 *
2080 * <p>This method requires the caller to hold either the
2081 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2082 * or the ability to modify system settings as determined by
2083 * {@link android.provider.Settings.System#canWrite}.</p>
2084 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002085 * @param networkType the type of the network over which traffic to the specified
2086 * host is to be routed
2087 * @param hostAddress the IP address of the host to which the route is desired
2088 * @return {@code true} on success, {@code false} on failure
2089 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002090 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002091 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002092 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002093 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002094 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002095 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002096 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002097 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002098 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2099 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002100 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002101 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002102 }
2103 }
2104
2105 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002106 * @return the context's attribution tag
2107 */
2108 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2109 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002110 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002111 }
2112
2113 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002114 * Returns the value of the setting for background data usage. If false,
2115 * applications should not use the network if the application is not in the
2116 * foreground. Developers should respect this setting, and check the value
2117 * of this before performing any background data operations.
2118 * <p>
2119 * All applications that have background services that use the network
2120 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002121 * <p>
Scott Main50589142011-10-06 18:32:43 -07002122 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002123 * background data depends on several combined factors, and this method will
2124 * always return {@code true}. Instead, when background data is unavailable,
2125 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002126 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002127 * @return Whether background data usage is allowed.
2128 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002129 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002130 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002131 // assume that background data is allowed; final authority is
2132 // NetworkInfo which may be blocked.
2133 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134 }
2135
2136 /**
2137 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002138 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002139 * @param allowBackgroundData Whether an application should use data while
2140 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002141 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002142 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2143 * @see #getBackgroundDataSetting()
2144 * @hide
2145 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002146 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002147 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002148 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002149 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002150 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002151
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002152 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002153 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002154 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002155 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002156 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002157 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002158 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002159 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2160 if (tm != null) {
2161 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2162 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2163 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2164 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2165 + " retVal=" + retVal);
2166 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002167 }
Wink Saville689f7042014-12-05 11:10:30 -08002168 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002169 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002170 }
2171
The Android Open Source Project28527d22009-03-03 19:31:44 -08002172 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002173 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002174 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002175 */
2176 public interface OnNetworkActiveListener {
2177 /**
2178 * Called on the main thread of the process to report that the current data network
2179 * has become active, and it is now a good time to perform any pending network
2180 * operations. Note that this listener only tells you when the network becomes
2181 * active; if at any other time you want to know whether it is active (and thus okay
2182 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002183 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002184 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002185 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002186 }
2187
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002188 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002189 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002190
2191 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002192 * Start listening to reports when the system's default data network is active, meaning it is
2193 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2194 * to determine the current state of the system's default network after registering the
2195 * listener.
2196 * <p>
2197 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002198 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002199 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002200 *
2201 * @param l The listener to be told when the network is active.
2202 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002203 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002204 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2205 @Override
2206 public void onNetworkActive() throws RemoteException {
2207 l.onNetworkActive();
2208 }
2209 };
2210
2211 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002212 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002213 mNetworkActivityListeners.put(l, rl);
2214 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002215 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002216 }
2217 }
2218
2219 /**
2220 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002221 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002222 *
2223 * @param l Previously registered listener.
2224 */
Chalard Jean158702d2019-01-07 19:26:34 +09002225 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002226 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichibc1104b2017-05-09 15:19:01 +09002227 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002228 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002229 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002230 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002231 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002232 }
2233 }
2234
2235 /**
2236 * Return whether the data network is currently active. An active network means that
2237 * it is currently in a high power state for performing data transmission. On some
2238 * types of networks, it may be expensive to move and stay in such a state, so it is
2239 * more power efficient to batch network traffic together when the radio is already in
2240 * this state. This method tells you whether right now is currently a good time to
2241 * initiate network traffic, as the network is already active.
2242 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002243 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002244 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002245 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002246 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002247 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002248 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002249 }
2250
2251 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002252 * {@hide}
2253 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002254 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002255 mContext = Preconditions.checkNotNull(context, "missing context");
2256 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002257 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002258 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002259 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002260
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002261 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002262 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002263 public static ConnectivityManager from(Context context) {
2264 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2265 }
2266
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002267 /** @hide */
2268 public NetworkRequest getDefaultRequest() {
2269 try {
2270 // This is not racy as the default request is final in ConnectivityService.
2271 return mService.getDefaultRequest();
2272 } catch (RemoteException e) {
2273 throw e.rethrowFromSystemServer();
2274 }
2275 }
2276
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002277 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002278 * Check if the package is a allowed to write settings. This also accounts that such an access
2279 * happened.
2280 *
2281 * @return {@code true} iff the package is allowed to write settings.
2282 */
2283 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2284 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2285 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2286 boolean throwException) {
2287 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2288 throwException);
2289 }
2290
2291 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002292 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2293 * situations where a Context pointer is unavailable.
2294 * @hide
2295 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002296 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002297 static ConnectivityManager getInstanceOrNull() {
2298 return sInstance;
2299 }
2300
2301 /**
2302 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2303 * situations where a Context pointer is unavailable.
2304 * @hide
2305 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002306 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002307 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002308 private static ConnectivityManager getInstance() {
2309 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002310 throw new IllegalStateException("No ConnectivityManager yet constructed");
2311 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002312 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002313 }
2314
2315 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002316 * Get the set of tetherable, available interfaces. This list is limited by
2317 * device configuration and current interface existence.
2318 *
2319 * @return an array of 0 or more Strings of tetherable interface names.
2320 *
markchien6ae63e52020-01-21 13:11:06 +08002321 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002322 * {@hide}
2323 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002324 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002325 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002326 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002327 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002328 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002329 }
2330
2331 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002332 * Get the set of tethered interfaces.
2333 *
2334 * @return an array of 0 or more String of currently tethered interface names.
2335 *
markchien6ae63e52020-01-21 13:11:06 +08002336 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002337 * {@hide}
2338 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002339 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002340 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002341 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002342 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002343 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002344 }
2345
2346 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002347 * Get the set of interface names which attempted to tether but
2348 * failed. Re-attempting to tether may cause them to reset to the Tethered
2349 * state. Alternatively, causing the interface to be destroyed and recreated
2350 * may cause them to reset to the available state.
2351 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2352 * information on the cause of the errors.
2353 *
2354 * @return an array of 0 or more String indicating the interface names
2355 * which failed to tether.
2356 *
markchien6ae63e52020-01-21 13:11:06 +08002357 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002358 * {@hide}
2359 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002360 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002361 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002362 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002363 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002364 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002365 }
2366
2367 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002368 * Get the set of tethered dhcp ranges.
2369 *
markchien2e6ba522020-02-14 11:55:48 +08002370 * @deprecated This method is not supported.
2371 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002372 * {@hide}
2373 */
paulhu8e96a752019-08-12 16:25:11 +08002374 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002375 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002376 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002377 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002378 }
2379
2380 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002381 * Attempt to tether the named interface. This will setup a dhcp server
2382 * on the interface, forward and NAT IP packets and forward DNS requests
2383 * to the best active upstream network interface. Note that if no upstream
2384 * IP network interface is available, dhcp will still run and traffic will be
2385 * allowed between the tethered devices and this device, though upstream net
2386 * access will of course fail until an upstream network interface becomes
2387 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002388 *
2389 * <p>This method requires the caller to hold either the
2390 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2391 * or the ability to modify system settings as determined by
2392 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002393 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002394 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2395 * and WifiStateMachine which need direct access. All other clients should use
2396 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2397 * logic.</p>
2398 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002399 * @param iface the interface name to tether.
2400 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002401 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002402 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002403 * {@hide}
2404 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002405 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002406 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002407 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002408 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002409 }
2410
2411 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002412 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002413 *
2414 * <p>This method requires the caller to hold either the
2415 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2416 * or the ability to modify system settings as determined by
2417 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002418 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002419 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2420 * and WifiStateMachine which need direct access. All other clients should use
2421 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2422 * logic.</p>
2423 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002424 * @param iface the interface name to untether.
2425 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2426 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002427 * {@hide}
2428 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002429 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002430 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002431 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002432 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002433 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002434
2435 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002436 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002437 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002438 * due to device configuration.
2439 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002440 * <p>If this app does not have permission to use this API, it will always
2441 * return false rather than throw an exception.</p>
2442 *
2443 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2444 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2445 *
2446 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2447 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2448 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002449 * @return a boolean - {@code true} indicating Tethering is supported.
2450 *
markchien6ae63e52020-01-21 13:11:06 +08002451 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002452 * {@hide}
2453 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002454 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002455 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2456 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002457 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002458 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002459 }
2460
2461 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002462 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002463 *
2464 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002465 * @hide
2466 */
2467 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002468 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002469 public static abstract class OnStartTetheringCallback {
2470 /**
2471 * Called when tethering has been successfully started.
2472 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002473 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002474
2475 /**
2476 * Called when starting tethering failed.
2477 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002478 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002479 }
2480
2481 /**
2482 * Convenient overload for
2483 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2484 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002485 *
2486 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002487 * @hide
2488 */
2489 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002490 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002491 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002492 public void startTethering(int type, boolean showProvisioningUi,
2493 final OnStartTetheringCallback callback) {
2494 startTethering(type, showProvisioningUi, callback, null);
2495 }
2496
2497 /**
2498 * Runs tether provisioning for the given type if needed and then starts tethering if
2499 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2500 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2501 * schedules tether provisioning re-checks if appropriate.
2502 *
2503 * @param type The type of tethering to start. Must be one of
2504 * {@link ConnectivityManager.TETHERING_WIFI},
2505 * {@link ConnectivityManager.TETHERING_USB}, or
2506 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2507 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2508 * is one. This should be true the first time this function is called and also any time
2509 * the user can see this UI. It gives users information from their carrier about the
2510 * check failing and how they can sign up for tethering if possible.
2511 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2512 * of the result of trying to tether.
2513 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002514 *
2515 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002516 * @hide
2517 */
2518 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002519 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002520 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002521 public void startTethering(int type, boolean showProvisioningUi,
2522 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002523 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002524
markchien91c78e52020-01-20 19:31:56 +08002525 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002526 @Override
markchien91c78e52020-01-20 19:31:56 +08002527 public void execute(Runnable command) {
2528 if (handler == null) {
2529 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002530 } else {
markchien91c78e52020-01-20 19:31:56 +08002531 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002532 }
2533 }
2534 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002535
markchien91c78e52020-01-20 19:31:56 +08002536 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2537 @Override
2538 public void onTetheringStarted() {
2539 callback.onTetheringStarted();
2540 }
2541
2542 @Override
markchienf47d8342020-03-19 13:37:43 +08002543 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002544 callback.onTetheringFailed();
2545 }
2546 };
2547
2548 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002549 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002550
Amos Bianchia9b415a2020-03-04 11:07:38 -08002551 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002552 }
2553
2554 /**
2555 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2556 * applicable.
2557 *
2558 * @param type The type of tethering to stop. Must be one of
2559 * {@link ConnectivityManager.TETHERING_WIFI},
2560 * {@link ConnectivityManager.TETHERING_USB}, or
2561 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002562 *
2563 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002564 * @hide
2565 */
2566 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002567 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002568 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002569 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002570 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002571 }
2572
2573 /**
markchien4ef53e82019-02-27 14:56:11 +08002574 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2575 * upstream status.
2576 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002577 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002578 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002579 */
2580 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002581 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002582 public abstract static class OnTetheringEventCallback {
2583
2584 /**
2585 * Called when tethering upstream changed. This can be called multiple times and can be
2586 * called any time.
2587 *
2588 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2589 * have any upstream.
2590 */
2591 public void onUpstreamChanged(@Nullable Network network) {}
2592 }
2593
markchien6ae63e52020-01-21 13:11:06 +08002594 @GuardedBy("mTetheringEventCallbacks")
2595 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2596 mTetheringEventCallbacks = new ArrayMap<>();
2597
markchien4ef53e82019-02-27 14:56:11 +08002598 /**
2599 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002600 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002601 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2602 * with a null argument. The same callback object cannot be registered twice.
2603 *
2604 * @param executor the executor on which callback will be invoked.
2605 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002606 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002607 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002608 * @hide
2609 */
2610 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002611 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002612 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2613 public void registerTetheringEventCallback(
2614 @NonNull @CallbackExecutor Executor executor,
2615 @NonNull final OnTetheringEventCallback callback) {
2616 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2617
markchien6ae63e52020-01-21 13:11:06 +08002618 final TetheringEventCallback tetherCallback =
2619 new TetheringEventCallback() {
2620 @Override
2621 public void onUpstreamChanged(@Nullable Network network) {
2622 callback.onUpstreamChanged(network);
2623 }
2624 };
2625
2626 synchronized (mTetheringEventCallbacks) {
2627 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002628 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002629 }
markchien4ef53e82019-02-27 14:56:11 +08002630 }
2631
2632 /**
2633 * Remove tethering event callback previously registered with
2634 * {@link #registerTetheringEventCallback}.
2635 *
2636 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002637 *
2638 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002639 * @hide
2640 */
2641 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002642 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002643 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2644 public void unregisterTetheringEventCallback(
2645 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002646 Objects.requireNonNull(callback, "The callback must be non-null");
2647 synchronized (mTetheringEventCallbacks) {
2648 final TetheringEventCallback tetherCallback =
2649 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002650 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002651 }
markchien4ef53e82019-02-27 14:56:11 +08002652 }
2653
2654
2655 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002656 * Get the list of regular expressions that define any tetherable
2657 * USB network interfaces. If USB tethering is not supported by the
2658 * device, this list should be empty.
2659 *
2660 * @return an array of 0 or more regular expression Strings defining
2661 * what interfaces are considered tetherable usb interfaces.
2662 *
markchien6ae63e52020-01-21 13:11:06 +08002663 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002664 * {@hide}
2665 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002666 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002667 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002668 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002669 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002670 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002671 }
2672
2673 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002674 * Get the list of regular expressions that define any tetherable
2675 * Wifi network interfaces. If Wifi tethering is not supported by the
2676 * device, this list should be empty.
2677 *
2678 * @return an array of 0 or more regular expression Strings defining
2679 * what interfaces are considered tetherable wifi interfaces.
2680 *
markchien6ae63e52020-01-21 13:11:06 +08002681 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002682 * {@hide}
2683 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002684 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002685 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002686 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002687 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002688 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002689 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002690
Danica Chang96567052010-08-11 14:54:43 -07002691 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002692 * Get the list of regular expressions that define any tetherable
2693 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2694 * device, this list should be empty.
2695 *
2696 * @return an array of 0 or more regular expression Strings defining
2697 * what interfaces are considered tetherable bluetooth interfaces.
2698 *
markchien6ae63e52020-01-21 13:11:06 +08002699 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2700 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002701 * {@hide}
2702 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002703 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002704 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002705 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002706 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002707 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002708 }
2709
Mike Lockwooded4a1742011-07-19 13:04:47 -07002710 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002711 * Attempt to both alter the mode of USB and Tethering of USB. A
2712 * utility method to deal with some of the complexity of USB - will
2713 * attempt to switch to Rndis and subsequently tether the resulting
2714 * interface on {@code true} or turn off tethering and switch off
2715 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002716 *
2717 * <p>This method requires the caller to hold either the
2718 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2719 * or the ability to modify system settings as determined by
2720 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002721 *
2722 * @param enable a boolean - {@code true} to enable tethering
2723 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002724 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002725 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002726 * {@hide}
2727 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002728 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002729 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002730 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002731 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002732 }
2733
markchien6ae63e52020-01-21 13:11:06 +08002734 /**
2735 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2736 * {@hide}
2737 */
markchien0f45bb92019-01-16 17:44:13 +08002738 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002739 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002740 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002741 /**
2742 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2743 * {@hide}
2744 */
2745 @Deprecated
2746 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2747 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2748 /**
2749 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2750 * {@hide}
2751 */
2752 @Deprecated
2753 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2754 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2755 /**
2756 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2757 * {@hide}
2758 */
2759 @Deprecated
2760 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2761 /**
2762 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2763 * {@hide}
2764 */
2765 @Deprecated
2766 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2767 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2768 /**
markchienf47d8342020-03-19 13:37:43 +08002769 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002770 * {@hide}
2771 */
2772 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002773 public static final int TETHER_ERROR_MASTER_ERROR =
2774 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002775 /**
2776 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2777 * {@hide}
2778 */
2779 @Deprecated
2780 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2781 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2782 /**
2783 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2784 * {@hide}
2785 */
2786 @Deprecated
2787 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2788 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2789 /**
markchienf47d8342020-03-19 13:37:43 +08002790 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002791 * {@hide}
2792 */
2793 @Deprecated
2794 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002795 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002796 /**
markchienf47d8342020-03-19 13:37:43 +08002797 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002798 * {@hide}
2799 */
2800 @Deprecated
2801 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002802 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002803 /**
2804 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2805 * {@hide}
2806 */
2807 @Deprecated
2808 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2809 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2810 /**
markchienf47d8342020-03-19 13:37:43 +08002811 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002812 * {@hide}
2813 */
markchien0f45bb92019-01-16 17:44:13 +08002814 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002815 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002816 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002817 /**
2818 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2819 * {@hide}
2820 */
2821 @Deprecated
2822 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2823 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2824 /**
2825 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2826 * {@hide}
2827 */
markchien0f45bb92019-01-16 17:44:13 +08002828 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002829 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002830 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002831
2832 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002833 * Get a more detailed error code after a Tethering or Untethering
2834 * request asynchronously failed.
2835 *
2836 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002837 * @return error The error code of the last error tethering or untethering the named
2838 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002839 *
markchien6ae63e52020-01-21 13:11:06 +08002840 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002841 * {@hide}
2842 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002843 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002844 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002845 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002846 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002847 int error = mTetheringManager.getLastTetherError(iface);
2848 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2849 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2850 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2851 // instead.
2852 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2853 }
2854 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002855 }
2856
markchienbf5ab012019-03-06 16:25:00 +08002857 /** @hide */
2858 @Retention(RetentionPolicy.SOURCE)
2859 @IntDef(value = {
2860 TETHER_ERROR_NO_ERROR,
2861 TETHER_ERROR_PROVISION_FAILED,
2862 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2863 })
2864 public @interface EntitlementResultCode {
2865 }
2866
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002867 /**
markchienbf5ab012019-03-06 16:25:00 +08002868 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002869 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002870 *
2871 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002872 * @hide
2873 */
2874 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002875 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002876 public interface OnTetheringEntitlementResultListener {
2877 /**
2878 * Called to notify entitlement result.
2879 *
2880 * @param resultCode an int value of entitlement result. It may be one of
2881 * {@link #TETHER_ERROR_NO_ERROR},
2882 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2883 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2884 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002885 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002886 }
2887
2888 /**
markchien0f45bb92019-01-16 17:44:13 +08002889 * Get the last value of the entitlement check on this downstream. If the cached value is
2890 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2891 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2892 * guaranteed that the UI-based entitlement check will complete in any specific time period
2893 * and may in fact never complete. Any successful entitlement check the platform performs for
2894 * any reason will update the cached value.
2895 *
2896 * @param type the downstream type of tethering. Must be one of
2897 * {@link #TETHERING_WIFI},
2898 * {@link #TETHERING_USB}, or
2899 * {@link #TETHERING_BLUETOOTH}.
2900 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002901 * @param executor the executor on which callback will be invoked.
2902 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2903 * notify the caller of the result of entitlement check. The listener may be called zero
2904 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002905 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002906 * {@hide}
2907 */
2908 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002909 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002910 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002911 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2912 @NonNull @CallbackExecutor Executor executor,
2913 @NonNull final OnTetheringEntitlementResultListener listener) {
2914 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2915 ResultReceiver wrappedListener = new ResultReceiver(null) {
2916 @Override
2917 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08002918 final long token = Binder.clearCallingIdentity();
2919 try {
2920 executor.execute(() -> {
2921 listener.onTetheringEntitlementResult(resultCode);
2922 });
2923 } finally {
2924 Binder.restoreCallingIdentity(token);
2925 }
markchienbf5ab012019-03-06 16:25:00 +08002926 }
2927 };
2928
Amos Bianchia9b415a2020-03-04 11:07:38 -08002929 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002930 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002931 }
2932
2933 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002934 * Report network connectivity status. This is currently used only
2935 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002936 * <p>This method requires the caller to hold the permission
2937 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002938 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002939 * @param networkType The type of network you want to report on
2940 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002941 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002942 * {@hide}
2943 */
2944 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002945 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002946 try {
2947 mService.reportInetCondition(networkType, percentage);
2948 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002949 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002950 }
2951 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002952
2953 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002954 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07002955 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002956 * the framework to re-evaluate network connectivity and/or switch to another
2957 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002958 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002959 * @param network The {@link Network} the application was attempting to use
2960 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04002961 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2962 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002963 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002964 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09002965 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002966 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002967 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04002968 // One of these will be ignored because it matches system's current state.
2969 // The other will trigger the necessary reevaluation.
2970 mService.reportNetworkConnectivity(network, true);
2971 mService.reportNetworkConnectivity(network, false);
2972 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002973 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04002974 }
2975 }
2976
2977 /**
2978 * Report to the framework whether a network has working connectivity.
2979 * This provides a hint to the system that a particular network is providing
2980 * working connectivity or not. In response the framework may re-evaluate
2981 * the network's connectivity and might take further action thereafter.
2982 *
2983 * @param network The {@link Network} the application was attempting to use
2984 * or {@code null} to indicate the current default network.
2985 * @param hasConnectivity {@code true} if the application was able to successfully access the
2986 * Internet using {@code network} or {@code false} if not.
2987 */
Chalard Jean158702d2019-01-07 19:26:34 +09002988 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002989 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04002990 try {
2991 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002992 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002993 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002994 }
2995 }
2996
2997 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002998 * Set a network-independent global http proxy. This is not normally what you want
2999 * for typical HTTP proxies - they are general network dependent. However if you're
3000 * doing something unusual like general internal filtering this may be useful. On
3001 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003002 *
3003 * @param p A {@link ProxyInfo} object defining the new global
3004 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003005 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003006 */
paulhu8e96a752019-08-12 16:25:11 +08003007 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04003008 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003009 try {
3010 mService.setGlobalProxy(p);
3011 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003012 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003013 }
3014 }
3015
3016 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003017 * Retrieve any network-independent global HTTP proxy.
3018 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003019 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003020 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003021 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003022 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003023 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003024 try {
3025 return mService.getGlobalProxy();
3026 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003027 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003028 }
3029 }
3030
3031 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003032 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3033 * network-specific HTTP proxy. If {@code network} is null, the
3034 * network-specific proxy returned is the proxy of the default active
3035 * network.
3036 *
3037 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3038 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3039 * or when {@code network} is {@code null},
3040 * the {@code ProxyInfo} for the default active network. Returns
3041 * {@code null} when no proxy applies or the caller doesn't have
3042 * permission to use {@code network}.
3043 * @hide
3044 */
3045 public ProxyInfo getProxyForNetwork(Network network) {
3046 try {
3047 return mService.getProxyForNetwork(network);
3048 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003049 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003050 }
3051 }
3052
3053 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003054 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3055 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003056 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003057 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003058 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003059 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003060 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003061 */
Chalard Jean158702d2019-01-07 19:26:34 +09003062 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003063 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003064 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003065 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003066
3067 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003068 * Returns true if the hardware supports the given network type
3069 * else it returns false. This doesn't indicate we have coverage
3070 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003071 * hardware supports it. For example a GSM phone without a SIM
3072 * should still return {@code true} for mobile data, but a wifi only
3073 * tablet would return {@code false}.
3074 *
3075 * @param networkType The network type we'd like to check
3076 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003077 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003078 * @hide
3079 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003080 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003081 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003082 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003083 public boolean isNetworkSupported(int networkType) {
3084 try {
3085 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003086 } catch (RemoteException e) {
3087 throw e.rethrowFromSystemServer();
3088 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003089 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003090
3091 /**
3092 * Returns if the currently active data network is metered. A network is
3093 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003094 * that connection due to monetary costs, data limitations or
3095 * battery/performance issues. You should check this before doing large
3096 * data transfers, and warn the user or delay the operation until another
3097 * network is available.
3098 *
3099 * @return {@code true} if large transfers should be avoided, otherwise
3100 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003101 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003102 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003103 public boolean isActiveNetworkMetered() {
3104 try {
3105 return mService.isActiveNetworkMetered();
3106 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003107 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003108 }
3109 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003110
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003111 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003112 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003113 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003114 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003115 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003116 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003117 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003118 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003119 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003120 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003121 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003122 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003123 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003124 }
3125 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003126
3127 /**
3128 * Set the value for enabling/disabling airplane mode
3129 *
3130 * @param enable whether to enable airplane mode or not
3131 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003132 * @hide
3133 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003134 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003135 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003136 android.Manifest.permission.NETWORK_SETTINGS,
3137 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3138 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003139 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003140 public void setAirplaneMode(boolean enable) {
3141 try {
3142 mService.setAirplaneMode(enable);
3143 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003144 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003145 }
3146 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003147
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003148 /**
3149 * Registers the specified {@link NetworkProvider}.
3150 * Each listener must only be registered once. The listener can be unregistered with
3151 * {@link #unregisterNetworkProvider}.
3152 *
3153 * @param provider the provider to register
3154 * @return the ID of the provider. This ID must be used by the provider when registering
3155 * {@link android.net.NetworkAgent}s.
3156 * @hide
3157 */
3158 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003159 @RequiresPermission(anyOf = {
3160 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3161 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003162 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3163 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003164 throw new IllegalStateException("NetworkProviders can only be registered once");
3165 }
3166
3167 try {
3168 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3169 provider.getName());
3170 provider.setProviderId(providerId);
3171 } catch (RemoteException e) {
3172 throw e.rethrowFromSystemServer();
3173 }
3174 return provider.getProviderId();
3175 }
3176
3177 /**
3178 * Unregisters the specified NetworkProvider.
3179 *
3180 * @param provider the provider to unregister
3181 * @hide
3182 */
3183 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003184 @RequiresPermission(anyOf = {
3185 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3186 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003187 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3188 try {
3189 mService.unregisterNetworkProvider(provider.getMessenger());
3190 } catch (RemoteException e) {
3191 throw e.rethrowFromSystemServer();
3192 }
3193 provider.setProviderId(NetworkProvider.ID_NONE);
3194 }
3195
3196
3197 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003198 @RequiresPermission(anyOf = {
3199 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3200 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003201 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3202 try {
3203 mService.declareNetworkRequestUnfulfillable(request);
3204 } catch (RemoteException e) {
3205 throw e.rethrowFromSystemServer();
3206 }
3207 }
3208
Chalard Jean29d06db2018-05-02 21:14:54 +09003209 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3210 // of dependent changes that would conflict throughout the automerger graph. Having this
3211 // temporarily helps with the process of going through with all these dependent changes across
3212 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003213 /**
3214 * @hide
3215 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003216 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003217 */
paulhub6ba8e82020-03-04 09:43:41 +08003218 @RequiresPermission(anyOf = {
3219 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3220 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003221 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003222 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003223 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003224 }
3225
3226 /**
3227 * @hide
3228 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003229 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003230 */
paulhub6ba8e82020-03-04 09:43:41 +08003231 @RequiresPermission(anyOf = {
3232 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3233 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003234 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003235 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003236 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003237 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003238 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003239 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003240 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003241 }
3242
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003243 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003244 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3245 * changes. Should be extended by applications wanting notifications.
3246 *
3247 * A {@code NetworkCallback} is registered by calling
3248 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3249 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003250 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003251 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3252 * A {@code NetworkCallback} should be registered at most once at any time.
3253 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003254 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003255 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003256 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003257 * No flags associated with this callback.
3258 * @hide
3259 */
3260 public static final int FLAG_NONE = 0;
3261 /**
3262 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3263 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3264 * <p>
3265 * These include:
3266 * <li> Some transport info instances (retrieved via
3267 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3268 * contain location sensitive information.
3269 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3270 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3271 * </p>
3272 * <p>
3273 * Note:
3274 * <li> Retrieving this location sensitive information (subject to app's location
3275 * permissions) will be noted by system. </li>
3276 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3277 * not include location sensitive info.
3278 * </p>
3279 */
3280 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3281
3282 /** @hide */
3283 @Retention(RetentionPolicy.SOURCE)
3284 @IntDef(flag = true, prefix = "FLAG_", value = {
3285 FLAG_NONE,
3286 FLAG_INCLUDE_LOCATION_INFO
3287 })
3288 public @interface Flag { }
3289
3290 /**
3291 * All the valid flags for error checking.
3292 */
3293 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3294
3295 public NetworkCallback() {
3296 this(FLAG_NONE);
3297 }
3298
3299 public NetworkCallback(@Flag int flags) {
3300 Preconditions.checkArgument((flags & VALID_FLAGS) == flags);
3301 mFlags = flags;
3302 }
3303
3304 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003305 * Called when the framework connects to a new network to evaluate whether it satisfies this
3306 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3307 * callback. There is no guarantee that this new network will satisfy any requests, or that
3308 * the network will stay connected for longer than the time necessary to evaluate it.
3309 * <p>
3310 * Most applications <b>should not</b> act on this callback, and should instead use
3311 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3312 * the framework in properly evaluating the network &mdash; for example, an application that
3313 * can automatically log in to a captive portal without user intervention.
3314 *
3315 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003316 *
3317 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003318 */
paulhu1a407652019-03-22 16:35:06 +08003319 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003320
3321 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003322 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003323 * This callback may be called more than once if the {@link Network} that is
3324 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003325 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003326 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003327 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3328 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003329 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003330 * @hide
3331 */
paulhu1a407652019-03-22 16:35:06 +08003332 public void onAvailable(@NonNull Network network,
3333 @NonNull NetworkCapabilities networkCapabilities,
3334 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003335 // Internally only this method is called when a new network is available, and
3336 // it calls the callback in the same way and order that older versions used
3337 // to call so as not to change the behavior.
3338 onAvailable(network);
3339 if (!networkCapabilities.hasCapability(
3340 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3341 onNetworkSuspended(network);
3342 }
3343 onCapabilitiesChanged(network, networkCapabilities);
3344 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003345 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003346 }
3347
3348 /**
3349 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003350 *
3351 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3352 * be available at the same time, and onAvailable will be called for each of these as they
3353 * appear.
3354 *
3355 * <p>For callbacks registered with {@link #requestNetwork} and
3356 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3357 * is the new best network for this request and is now tracked by this callback ; this
3358 * callback will no longer receive method calls about other networks that may have been
3359 * passed to this method previously. The previously-best network may have disconnected, or
3360 * it may still be around and the newly-best network may simply be better.
3361 *
3362 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3363 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3364 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3365 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3366 *
3367 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3368 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3369 * this callback as this is prone to race conditions (there is no guarantee the objects
3370 * returned by these methods will be current). Instead, wait for a call to
3371 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3372 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3373 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003374 *
3375 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003376 */
paulhu1a407652019-03-22 16:35:06 +08003377 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003378
3379 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003380 * Called when the network is about to be lost, typically because there are no outstanding
3381 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3382 * with the new replacement network for graceful handover. This method is not guaranteed
3383 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3384 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003385 *
Chalard Jean01378b62019-08-30 16:27:28 +09003386 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3387 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3388 * this callback as this is prone to race conditions ; calling these methods while in a
3389 * callback may return an outdated or even a null object.
3390 *
3391 * @param network The {@link Network} that is about to be lost.
3392 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3393 * connected for graceful handover; note that the network may still
3394 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003395 */
paulhu1a407652019-03-22 16:35:06 +08003396 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003397
3398 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003399 * Called when a network disconnects or otherwise no longer satisfies this request or
3400 * callback.
3401 *
3402 * <p>If the callback was registered with requestNetwork() or
3403 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3404 * returned by onAvailable() when that network is lost and no other network satisfies
3405 * the criteria of the request.
3406 *
3407 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3408 * each network which no longer satisfies the criteria of the callback.
3409 *
3410 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3411 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3412 * this callback as this is prone to race conditions ; calling these methods while in a
3413 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003414 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003415 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003416 */
paulhu1a407652019-03-22 16:35:06 +08003417 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003418
3419 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003420 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003421 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3422 * requested network request cannot be fulfilled (whether or not a timeout was
3423 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003424 * {@link NetworkRequest} will have already been removed and released, as if
3425 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003426 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003427 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003428
3429 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003430 * Called when the network corresponding to this request changes capabilities but still
3431 * satisfies the requested criteria.
3432 *
3433 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3434 * to be called immediately after {@link #onAvailable}.
3435 *
3436 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3437 * ConnectivityManager methods in this callback as this is prone to race conditions :
3438 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003439 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003440 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius951c0032020-12-22 15:10:42 -08003441 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003442 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003443 */
paulhu1a407652019-03-22 16:35:06 +08003444 public void onCapabilitiesChanged(@NonNull Network network,
3445 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003446
3447 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003448 * Called when the network corresponding to this request changes {@link LinkProperties}.
3449 *
3450 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3451 * to be called immediately after {@link #onAvailable}.
3452 *
3453 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3454 * ConnectivityManager methods in this callback as this is prone to race conditions :
3455 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003456 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003457 * @param network The {@link Network} whose link properties have changed.
3458 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003459 */
paulhu1a407652019-03-22 16:35:06 +08003460 public void onLinkPropertiesChanged(@NonNull Network network,
3461 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003462
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003463 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003464 * Called when the network the framework connected to for this request suspends data
3465 * transmission temporarily.
3466 *
3467 * <p>This generally means that while the TCP connections are still live temporarily
3468 * network data fails to transfer. To give a specific example, this is used on cellular
3469 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3470 * means read operations on sockets on this network will block once the buffers are
3471 * drained, and write operations will block once the buffers are full.
3472 *
3473 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3474 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3475 * this callback as this is prone to race conditions (there is no guarantee the objects
3476 * returned by these methods will be current).
3477 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003478 * @hide
3479 */
paulhu1a407652019-03-22 16:35:06 +08003480 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003481
3482 /**
3483 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003484 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3485 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003486
3487 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3488 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3489 * this callback as this is prone to race conditions : calling these methods while in a
3490 * callback may return an outdated or even a null object.
3491 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003492 * @hide
3493 */
paulhu1a407652019-03-22 16:35:06 +08003494 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003495
junyulaif2c67e42018-08-07 19:50:45 +08003496 /**
3497 * Called when access to the specified network is blocked or unblocked.
3498 *
Chalard Jean01378b62019-08-30 16:27:28 +09003499 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3500 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3501 * this callback as this is prone to race conditions : calling these methods while in a
3502 * callback may return an outdated or even a null object.
3503 *
junyulaif2c67e42018-08-07 19:50:45 +08003504 * @param network The {@link Network} whose blocked status has changed.
3505 * @param blocked The blocked status of this {@link Network}.
3506 */
junyulai7e06ad42019-03-04 22:45:36 +08003507 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003508
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003509 private NetworkRequest networkRequest;
Roshan Pius951c0032020-12-22 15:10:42 -08003510 private final int mFlags;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003511 }
3512
Hugo Benichia590ab82017-05-11 13:16:17 +09003513 /**
3514 * Constant error codes used by ConnectivityService to communicate about failures and errors
3515 * across a Binder boundary.
3516 * @hide
3517 */
3518 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003519 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003520 }
3521
3522 /** @hide */
3523 public static class TooManyRequestsException extends RuntimeException {}
3524
3525 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3526 switch (e.errorCode) {
3527 case Errors.TOO_MANY_REQUESTS:
3528 return new TooManyRequestsException();
3529 default:
3530 Log.w(TAG, "Unknown service error code " + e.errorCode);
3531 return new RuntimeException(e);
3532 }
3533 }
3534
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003535 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003536 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003537 public static final int CALLBACK_PRECHECK = BASE + 1;
3538 /** @hide */
3539 public static final int CALLBACK_AVAILABLE = BASE + 2;
3540 /** @hide arg1 = TTL */
3541 public static final int CALLBACK_LOSING = BASE + 3;
3542 /** @hide */
3543 public static final int CALLBACK_LOST = BASE + 4;
3544 /** @hide */
3545 public static final int CALLBACK_UNAVAIL = BASE + 5;
3546 /** @hide */
3547 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3548 /** @hide */
3549 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003550 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003551 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003552 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003553 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003554 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003555 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003556 /** @hide */
3557 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003558
Erik Kline155a59a2015-11-25 12:49:38 +09003559 /** @hide */
3560 public static String getCallbackName(int whichCallback) {
3561 switch (whichCallback) {
3562 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3563 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3564 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3565 case CALLBACK_LOST: return "CALLBACK_LOST";
3566 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3567 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3568 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003569 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3570 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3571 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003572 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003573 default:
3574 return Integer.toString(whichCallback);
3575 }
3576 }
3577
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003578 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003579 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003580 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003581
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003582 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003583 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003584 }
3585
Hugo Benichifd44e912017-02-02 17:02:36 +09003586 CallbackHandler(Handler handler) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003587 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003588 }
3589
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003590 @Override
3591 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003592 if (message.what == EXPIRE_LEGACY_REQUEST) {
3593 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3594 return;
3595 }
3596
3597 final NetworkRequest request = getObject(message, NetworkRequest.class);
3598 final Network network = getObject(message, Network.class);
3599 final NetworkCallback callback;
3600 synchronized (sCallbacks) {
3601 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003602 if (callback == null) {
3603 Log.w(TAG,
3604 "callback not found for " + getCallbackName(message.what) + " message");
3605 return;
3606 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003607 if (message.what == CALLBACK_UNAVAIL) {
3608 sCallbacks.remove(request);
3609 callback.networkRequest = ALREADY_UNREGISTERED;
3610 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003611 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003612 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003613 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003614 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003615
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003616 switch (message.what) {
3617 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003618 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003619 break;
3620 }
3621 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003622 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3623 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003624 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003625 break;
3626 }
3627 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003628 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003629 break;
3630 }
3631 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003632 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003633 break;
3634 }
3635 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003636 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003637 break;
3638 }
3639 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003640 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3641 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003642 break;
3643 }
3644 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003645 LinkProperties lp = getObject(message, LinkProperties.class);
3646 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003647 break;
3648 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003649 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003650 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003651 break;
3652 }
3653 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003654 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003655 break;
3656 }
junyulaif2c67e42018-08-07 19:50:45 +08003657 case CALLBACK_BLK_CHANGED: {
3658 boolean blocked = message.arg1 != 0;
3659 callback.onBlockedStatusChanged(network, blocked);
3660 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003661 }
3662 }
3663
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003664 private <T> T getObject(Message msg, Class<T> c) {
3665 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003666 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003667 }
3668
Hugo Benichifd44e912017-02-02 17:02:36 +09003669 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003670 synchronized (sCallbacks) {
3671 if (sCallbackHandler == null) {
3672 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003673 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003674 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003675 }
3676 }
3677
Hugo Benichibc4ac972017-02-03 14:18:44 +09003678 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3679 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003680
Hugo Benichibc4ac972017-02-03 14:18:44 +09003681 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003682 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003683 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003684 checkCallbackNotNull(callback);
junyulaiad010792021-01-11 16:53:38 +08003685 Preconditions.checkArgument(
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09003686 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3687 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003688 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003689 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003690 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003691 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003692 if (callback.networkRequest != null
3693 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003694 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3695 // and requests (http://b/20701525).
3696 Log.e(TAG, "NetworkCallback was already registered");
3697 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003698 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003699 Binder binder = new Binder();
Roshan Pius951c0032020-12-22 15:10:42 -08003700 final int callbackFlags = callback.mFlags;
junyulaiad010792021-01-11 16:53:38 +08003701 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003702 request = mService.listenForNetwork(
Roshan Pius951c0032020-12-22 15:10:42 -08003703 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003704 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003705 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003706 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003707 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
Roshan Pius951c0032020-12-22 15:10:42 -08003708 callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003709 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003710 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003711 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003712 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003713 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003714 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003715 } catch (RemoteException e) {
3716 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003717 } catch (ServiceSpecificException e) {
3718 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003719 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003720 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003721 }
3722
3723 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003724 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003725 *
markchienfac84a22020-03-18 21:16:15 +08003726 * This API is only for use in internal system code that requests networks with legacy type and
3727 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003728 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003729 *
markchiend6eeffd2020-01-14 00:55:21 +08003730 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003731 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3732 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3733 * be a positive value (i.e. >0).
3734 * @param legacyType to specify the network type(#TYPE_*).
3735 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003736 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3737 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003738 *
3739 * @hide
3740 */
markchiend6eeffd2020-01-14 00:55:21 +08003741 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003742 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003743 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003744 int timeoutMs, int legacyType, @NonNull Handler handler,
3745 @NonNull NetworkCallback networkCallback) {
3746 if (legacyType == TYPE_NONE) {
3747 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3748 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003749 CallbackHandler cbHandler = new CallbackHandler(handler);
3750 NetworkCapabilities nc = request.networkCapabilities;
3751 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003752 }
3753
3754 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003755 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003756 *
Chalard Jean01378b62019-08-30 16:27:28 +09003757 * <p>This method will attempt to find the best network that matches the passed
3758 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3759 * criteria. The platform will evaluate which network is the best at its own discretion.
3760 * Throughput, latency, cost per byte, policy, user preference and other considerations
3761 * may be factored in the decision of what is considered the best network.
3762 *
3763 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3764 * matching this request, while always attempting to match the request to a better network if
3765 * possible. If a better match is found, the platform will switch this request to the now-best
3766 * network and inform the app of the newly best network by invoking
3767 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3768 * will not try to maintain any other network than the best one currently matching the request:
3769 * a network not matching any network request may be disconnected at any time.
3770 *
3771 * <p>For example, an application could use this method to obtain a connected cellular network
3772 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3773 * radio to consume additional power. Or, an application could inform the system that it wants
3774 * a network supporting sending MMSes and have the system let it know about the currently best
3775 * MMS-supporting network through the provided {@link NetworkCallback}.
3776 *
3777 * <p>The status of the request can be followed by listening to the various callbacks described
3778 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3779 * used to direct traffic to the network (although accessing some networks may be subject to
3780 * holding specific permissions). Callers will learn about the specific characteristics of the
3781 * network through
3782 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3783 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3784 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3785 * matching the request at any given time; therefore when a better network matching the request
3786 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3787 * with the new network after which no further updates are given about the previously-best
3788 * network, unless it becomes the best again at some later time. All callbacks are invoked
3789 * in order on the same thread, which by default is a thread created by the framework running
3790 * in the app.
3791 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3792 * callbacks are invoked.
3793 *
3794 * <p>This{@link NetworkRequest} will live until released via
3795 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3796 * which point the system may let go of the network at any time.
3797 *
3798 * <p>A version of this method which takes a timeout is
3799 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3800 * wait for a limited amount of time for the network to become unavailable.
3801 *
Paul Jensenee52d232015-06-16 15:11:58 -04003802 * <p>It is presently unsupported to request a network with mutable
3803 * {@link NetworkCapabilities} such as
3804 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3805 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3806 * as these {@code NetworkCapabilities} represent states that a particular
3807 * network may never attain, and whether a network will attain these states
3808 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003809 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003810 *
3811 * <p>This method requires the caller to hold either the
3812 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3813 * or the ability to modify system settings as determined by
3814 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003815 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003816 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3817 * number of outstanding requests to 100 per app (identified by their UID), shared with
3818 * all variants of this method, of {@link #registerNetworkCallback} as well as
3819 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3820 * Requesting a network with this method will count toward this limit. If this limit is
3821 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3822 * make sure to unregister the callbacks with
3823 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3824 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003825 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003826 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3827 * the callback must not be shared - it uniquely specifies this request.
3828 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003829 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3830 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003831 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003832 */
Chalard Jean158702d2019-01-07 19:26:34 +09003833 public void requestNetwork(@NonNull NetworkRequest request,
3834 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003835 requestNetwork(request, networkCallback, getDefaultHandler());
3836 }
3837
3838 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003839 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichifd44e912017-02-02 17:02:36 +09003840 *
Chalard Jean01378b62019-08-30 16:27:28 +09003841 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3842 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003843 *
Chalard Jean01378b62019-08-30 16:27:28 +09003844 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003845 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3846 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003847 *
3848 * @param request {@link NetworkRequest} describing this request.
3849 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3850 * the callback must not be shared - it uniquely specifies this request.
3851 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003852 */
Chalard Jean158702d2019-01-07 19:26:34 +09003853 public void requestNetwork(@NonNull NetworkRequest request,
3854 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003855 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003856 NetworkCapabilities nc = request.networkCapabilities;
3857 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003858 }
3859
3860 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003861 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohenf67bde92017-03-01 12:47:28 -08003862 * by a timeout.
3863 *
3864 * This function behaves identically to the non-timed-out version
3865 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3866 * is not found within the given time (in milliseconds) the
3867 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3868 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3869 * not have to be released if timed-out (it is automatically released). Unregistering a
3870 * request that timed out is not an error.
3871 *
3872 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3873 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3874 * for that purpose. Calling this method will attempt to bring up the requested network.
3875 *
Chalard Jean01378b62019-08-30 16:27:28 +09003876 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003877 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3878 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003879 *
3880 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003881 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3882 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003883 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3884 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3885 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003886 */
Chalard Jean158702d2019-01-07 19:26:34 +09003887 public void requestNetwork(@NonNull NetworkRequest request,
3888 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003889 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003890 NetworkCapabilities nc = request.networkCapabilities;
3891 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3892 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003893 }
3894
Hugo Benichifd44e912017-02-02 17:02:36 +09003895 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003896 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichifd44e912017-02-02 17:02:36 +09003897 * by a timeout.
3898 *
Chalard Jean01378b62019-08-30 16:27:28 +09003899 * This method behaves identically to
3900 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3901 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003902 *
Chalard Jean01378b62019-08-30 16:27:28 +09003903 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003904 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3905 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003906 *
3907 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003908 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3909 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003910 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003911 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3912 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003913 */
Chalard Jean158702d2019-01-07 19:26:34 +09003914 public void requestNetwork(@NonNull NetworkRequest request,
3915 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003916 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003917 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003918 NetworkCapabilities nc = request.networkCapabilities;
3919 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003920 }
3921
3922 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003923 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003924 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003925 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003926 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003927 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3928 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003929 */
Erik Kline8a826212014-11-19 12:12:24 +09003930 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003931
3932 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003933 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003934 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003935 * {@link android.content.Intent#getParcelableExtra(String)}.
3936 */
Erik Kline8a826212014-11-19 12:12:24 +09003937 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003938
3939
3940 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003941 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003942 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003943 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003944 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003945 * the request may outlive the calling application and get called back when a suitable
3946 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003947 * <p>
3948 * The operation is an Intent broadcast that goes to a broadcast receiver that
3949 * you registered with {@link Context#registerReceiver} or through the
3950 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3951 * <p>
3952 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003953 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3954 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003955 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003956 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003957 * Intent to reserve the network or it will be released shortly after the Intent
3958 * is processed.
3959 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003960 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003961 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003962 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003963 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003964 * The request may be released normally by calling
3965 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003966 * <p>It is presently unsupported to request a network with either
3967 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3968 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3969 * as these {@code NetworkCapabilities} represent states that a particular
3970 * network may never attain, and whether a network will attain these states
3971 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003972 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003973 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003974 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3975 * number of outstanding requests to 100 per app (identified by their UID), shared with
3976 * all variants of this method, of {@link #registerNetworkCallback} as well as
3977 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3978 * Requesting a network with this method will count toward this limit. If this limit is
3979 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3980 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3981 * or {@link #releaseNetworkRequest(PendingIntent)}.
3982 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003983 * <p>This method requires the caller to hold either the
3984 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3985 * or the ability to modify system settings as determined by
3986 * {@link android.provider.Settings.System#canWrite}.</p>
3987 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003988 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003989 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003990 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003991 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09003992 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3993 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003994 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003995 */
Chalard Jean158702d2019-01-07 19:26:34 +09003996 public void requestNetwork(@NonNull NetworkRequest request,
3997 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003998 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003999 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004000 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004001 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004002 request.networkCapabilities, operation, mContext.getOpPackageName(),
4003 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004004 } catch (RemoteException e) {
4005 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004006 } catch (ServiceSpecificException e) {
4007 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004008 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004009 }
4010
4011 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004012 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4013 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004014 * This method has the same behavior as
4015 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004016 * releasing network resources and disconnecting.
4017 *
4018 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4019 * PendingIntent passed to
4020 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4021 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4022 */
Chalard Jean158702d2019-01-07 19:26:34 +09004023 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004024 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004025 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004026 try {
4027 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004028 } catch (RemoteException e) {
4029 throw e.rethrowFromSystemServer();
4030 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004031 }
4032
Hugo Benichibc1104b2017-05-09 15:19:01 +09004033 private static void checkPendingIntentNotNull(PendingIntent intent) {
4034 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4035 }
4036
4037 private static void checkCallbackNotNull(NetworkCallback callback) {
4038 Preconditions.checkNotNull(callback, "null NetworkCallback");
4039 }
4040
4041 private static void checkTimeout(int timeoutMs) {
4042 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004043 }
4044
4045 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004046 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004047 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004048 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4049 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004050 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004051 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4052 * number of outstanding requests to 100 per app (identified by their UID), shared with
4053 * all variants of this method, of {@link #requestNetwork} as well as
4054 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4055 * Requesting a network with this method will count toward this limit. If this limit is
4056 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4057 * make sure to unregister the callbacks with
4058 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4059 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004060 * @param request {@link NetworkRequest} describing this request.
4061 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4062 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004063 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004064 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004065 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004066 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004067 public void registerNetworkCallback(@NonNull NetworkRequest request,
4068 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004069 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4070 }
4071
4072 /**
4073 * Registers to receive notifications about all networks which satisfy the given
4074 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004075 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4076 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004077 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004078 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4079 * number of outstanding requests to 100 per app (identified by their UID), shared with
4080 * all variants of this method, of {@link #requestNetwork} as well as
4081 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4082 * Requesting a network with this method will count toward this limit. If this limit is
4083 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4084 * make sure to unregister the callbacks with
4085 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4086 *
4087 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004088 * @param request {@link NetworkRequest} describing this request.
4089 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4090 * networks change state.
4091 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004092 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004093 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004094 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004095 public void registerNetworkCallback(@NonNull NetworkRequest request,
4096 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004097 CallbackHandler cbHandler = new CallbackHandler(handler);
4098 NetworkCapabilities nc = request.networkCapabilities;
4099 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004100 }
4101
4102 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004103 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4104 * {@link NetworkRequest}.
4105 *
4106 * This function behaves identically to the version that takes a NetworkCallback, but instead
4107 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4108 * the request may outlive the calling application and get called back when a suitable
4109 * network is found.
4110 * <p>
4111 * The operation is an Intent broadcast that goes to a broadcast receiver that
4112 * you registered with {@link Context#registerReceiver} or through the
4113 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4114 * <p>
4115 * The operation Intent is delivered with two extras, a {@link Network} typed
4116 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4117 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4118 * the original requests parameters.
4119 * <p>
4120 * If there is already a request for this Intent registered (with the equality of
4121 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4122 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4123 * <p>
4124 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004125 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004126 *
4127 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4128 * number of outstanding requests to 100 per app (identified by their UID), shared with
4129 * all variants of this method, of {@link #requestNetwork} as well as
4130 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4131 * Requesting a network with this method will count toward this limit. If this limit is
4132 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4133 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4134 * or {@link #releaseNetworkRequest(PendingIntent)}.
4135 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004136 * @param request {@link NetworkRequest} describing this request.
4137 * @param operation Action to perform when the network is available (corresponds
4138 * to the {@link NetworkCallback#onAvailable} call. Typically
4139 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004140 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004141 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004142 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004143 public void registerNetworkCallback(@NonNull NetworkRequest request,
4144 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004145 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004146 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004147 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004148 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004149 request.networkCapabilities, operation, mContext.getOpPackageName(),
4150 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004151 } catch (RemoteException e) {
4152 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004153 } catch (ServiceSpecificException e) {
4154 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004155 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004156 }
4157
4158 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004159 * Registers to receive notifications about changes in the application's default network. This
4160 * may be a physical network or a virtual network, such as a VPN that applies to the
4161 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004162 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004163 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004164 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4165 * number of outstanding requests to 100 per app (identified by their UID), shared with
4166 * all variants of this method, of {@link #requestNetwork} as well as
4167 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4168 * Requesting a network with this method will count toward this limit. If this limit is
4169 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4170 * make sure to unregister the callbacks with
4171 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4172 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004173 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004174 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004175 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004176 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004177 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004178 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004179 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004180 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4181 }
4182
4183 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004184 * Registers to receive notifications about changes in the application's default network. This
4185 * may be a physical network or a virtual network, such as a VPN that applies to the
4186 * application. The callbacks will continue to be called until either the application exits or
4187 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4188 *
4189 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4190 * number of outstanding requests to 100 per app (identified by their UID), shared with
4191 * all variants of this method, of {@link #requestNetwork} as well as
4192 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4193 * Requesting a network with this method will count toward this limit. If this limit is
4194 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4195 * make sure to unregister the callbacks with
4196 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4197 *
4198 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4199 * application's default network changes.
4200 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4201 * @throws RuntimeException if the app already has too many callbacks registered.
4202 */
4203 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4204 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4205 @NonNull Handler handler) {
4206 CallbackHandler cbHandler = new CallbackHandler(handler);
4207 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4208 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4209 }
4210
4211 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004212 * Registers to receive notifications about changes in the system default network. The callbacks
4213 * will continue to be called until either the application exits or
4214 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004215 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004216 * This method should not be used to determine networking state seen by applications, because in
4217 * many cases, most or even all application traffic may not use the default network directly,
4218 * and traffic from different applications may go on different networks by default. As an
4219 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4220 * and not onto the system default network. Applications or system components desiring to do
4221 * determine network state as seen by applications should use other methods such as
4222 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4223 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004224 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4225 * number of outstanding requests to 100 per app (identified by their UID), shared with
4226 * all variants of this method, of {@link #requestNetwork} as well as
4227 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4228 * Requesting a network with this method will count toward this limit. If this limit is
4229 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4230 * make sure to unregister the callbacks with
4231 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4232 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004233 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4234 * system default network changes.
4235 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004236 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004237 *
4238 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004239 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004240 @SystemApi(client = MODULE_LIBRARIES)
4241 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4242 @RequiresPermission(anyOf = {
4243 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4244 android.Manifest.permission.NETWORK_SETTINGS})
4245 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004246 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004247 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004248 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004249 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004250 }
4251
4252 /**
junyulai7514e312021-03-05 15:51:17 +08004253 * @hide
4254 */
4255 // TODO: Make it public api.
4256 @SuppressLint("ExecutorRegistration")
4257 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4258 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4259 final NetworkCapabilities nc = request.networkCapabilities;
4260 final CallbackHandler cbHandler = new CallbackHandler(handler);
4261 sendRequestForNetwork(nc, networkCallback, 0, TRACK_BEST, TYPE_NONE, cbHandler);
4262 }
4263
4264 /**
fenglub00f4882015-04-21 17:12:05 -07004265 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4266 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4267 * network connection for updated bandwidth information. The caller will be notified via
4268 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004269 * method assumes that the caller has previously called
4270 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4271 * changes.
fenglu3f357402015-03-20 11:29:56 -07004272 *
fengluea2d9282015-04-27 14:28:04 -07004273 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004274 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004275 */
Chalard Jean158702d2019-01-07 19:26:34 +09004276 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004277 try {
fenglub00f4882015-04-21 17:12:05 -07004278 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004279 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004280 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004281 }
4282 }
4283
4284 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004285 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004286 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4287 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4288 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004289 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4290 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004291 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004292 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4293 * triggering it as soon as this call returns.
4294 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004295 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004296 */
Chalard Jean158702d2019-01-07 19:26:34 +09004297 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004298 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004299 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004300 final List<NetworkRequest> reqs = new ArrayList<>();
4301 // Find all requests associated to this callback and stop callback triggers immediately.
4302 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4303 synchronized (sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09004304 Preconditions.checkArgument(networkCallback.networkRequest != null,
4305 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004306 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4307 Log.d(TAG, "NetworkCallback was already unregistered");
4308 return;
4309 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004310 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4311 if (e.getValue() == networkCallback) {
4312 reqs.add(e.getKey());
4313 }
4314 }
4315 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4316 for (NetworkRequest r : reqs) {
4317 try {
4318 mService.releaseNetworkRequest(r);
4319 } catch (RemoteException e) {
4320 throw e.rethrowFromSystemServer();
4321 }
4322 // Only remove mapping if rpc was successful.
4323 sCallbacks.remove(r);
4324 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004325 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004326 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004327 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004328
4329 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004330 * Unregisters a callback previously registered via
4331 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4332 *
4333 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4334 * PendingIntent passed to
4335 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4336 * Cannot be null.
4337 */
Chalard Jean158702d2019-01-07 19:26:34 +09004338 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004339 releaseNetworkRequest(operation);
4340 }
4341
4342 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004343 * Informs the system whether it should switch to {@code network} regardless of whether it is
4344 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4345 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4346 * the system default network regardless of any other network that's currently connected. If
4347 * {@code always} is true, then the choice is remembered, so that the next time the user
4348 * connects to this network, the system will switch to it.
4349 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004350 * @param network The network to accept.
4351 * @param accept Whether to accept the network even if unvalidated.
4352 * @param always Whether to remember this choice in the future.
4353 *
4354 * @hide
4355 */
lucaslin2240ef62019-03-12 13:08:03 +08004356 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004357 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4358 try {
4359 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004360 } catch (RemoteException e) {
4361 throw e.rethrowFromSystemServer();
4362 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004363 }
4364
4365 /**
lucaslin2240ef62019-03-12 13:08:03 +08004366 * Informs the system whether it should consider the network as validated even if it only has
4367 * partial connectivity. If {@code accept} is true, then the network will be considered as
4368 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4369 * is remembered, so that the next time the user connects to this network, the system will
4370 * switch to it.
4371 *
4372 * @param network The network to accept.
4373 * @param accept Whether to consider the network as validated even if it has partial
4374 * connectivity.
4375 * @param always Whether to remember this choice in the future.
4376 *
4377 * @hide
4378 */
4379 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4380 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4381 try {
4382 mService.setAcceptPartialConnectivity(network, accept, always);
4383 } catch (RemoteException e) {
4384 throw e.rethrowFromSystemServer();
4385 }
4386 }
4387
4388 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004389 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4390 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4391 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4392 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4393 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004394 * @param network The network to accept.
4395 *
4396 * @hide
4397 */
lucaslin2240ef62019-03-12 13:08:03 +08004398 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004399 public void setAvoidUnvalidated(Network network) {
4400 try {
4401 mService.setAvoidUnvalidated(network);
4402 } catch (RemoteException e) {
4403 throw e.rethrowFromSystemServer();
4404 }
4405 }
4406
4407 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004408 * Requests that the system open the captive portal app on the specified network.
4409 *
4410 * @param network The network to log into.
4411 *
4412 * @hide
4413 */
paulhu8e96a752019-08-12 16:25:11 +08004414 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004415 public void startCaptivePortalApp(Network network) {
4416 try {
4417 mService.startCaptivePortalApp(network);
4418 } catch (RemoteException e) {
4419 throw e.rethrowFromSystemServer();
4420 }
4421 }
4422
4423 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004424 * Requests that the system open the captive portal app with the specified extras.
4425 *
4426 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4427 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004428 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004429 * @param appExtras Extras to include in the app start intent.
4430 * @hide
4431 */
4432 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004433 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004434 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004435 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004436 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004437 } catch (RemoteException e) {
4438 throw e.rethrowFromSystemServer();
4439 }
4440 }
4441
4442 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004443 * Determine whether the device is configured to avoid bad wifi.
4444 * @hide
4445 */
4446 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004447 @RequiresPermission(anyOf = {
4448 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4449 android.Manifest.permission.NETWORK_STACK})
4450 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004451 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004452 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004453 } catch (RemoteException e) {
4454 throw e.rethrowFromSystemServer();
4455 }
4456 }
4457
4458 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004459 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4460 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004461 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4462 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004463 *
4464 * An example of such an operation might be a time-sensitive foreground activity, such as a
4465 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4466 */
4467 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4468
4469 /**
4470 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4471 * a backup channel for traffic that is primarily going over another network.
4472 *
4473 * An example might be maintaining backup connections to peers or servers for the purpose of
4474 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4475 * on backup paths should be negligible compared to the traffic on the main path.
4476 */
4477 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4478
4479 /**
4480 * It is acceptable to use metered data to improve network latency and performance.
4481 */
4482 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4483
4484 /**
4485 * Return value to use for unmetered networks. On such networks we currently set all the flags
4486 * to true.
4487 * @hide
4488 */
4489 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4490 MULTIPATH_PREFERENCE_HANDOVER |
4491 MULTIPATH_PREFERENCE_RELIABILITY |
4492 MULTIPATH_PREFERENCE_PERFORMANCE;
4493
4494 /** @hide */
4495 @Retention(RetentionPolicy.SOURCE)
4496 @IntDef(flag = true, value = {
4497 MULTIPATH_PREFERENCE_HANDOVER,
4498 MULTIPATH_PREFERENCE_RELIABILITY,
4499 MULTIPATH_PREFERENCE_PERFORMANCE,
4500 })
4501 public @interface MultipathPreference {
4502 }
4503
4504 /**
4505 * Provides a hint to the calling application on whether it is desirable to use the
4506 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4507 * for multipath data transfer on this network when it is not the system default network.
4508 * Applications desiring to use multipath network protocols should call this method before
4509 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004510 *
4511 * @param network The network on which the application desires to use multipath data.
4512 * If {@code null}, this method will return the a preference that will generally
4513 * apply to metered networks.
4514 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4515 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004516 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004517 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004518 try {
4519 return mService.getMultipathPreference(network);
4520 } catch (RemoteException e) {
4521 throw e.rethrowFromSystemServer();
4522 }
4523 }
4524
4525 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004526 * Resets all connectivity manager settings back to factory defaults.
4527 * @hide
4528 */
paulhu8e96a752019-08-12 16:25:11 +08004529 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004530 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004531 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004532 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004533 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004534 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004535 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004536 }
4537 }
4538
4539 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004540 * Binds the current process to {@code network}. All Sockets created in the future
4541 * (and not explicitly bound via a bound SocketFactory from
4542 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4543 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4544 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4545 * work and all host name resolutions will fail. This is by design so an application doesn't
4546 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4547 * To clear binding pass {@code null} for {@code network}. Using individually bound
4548 * Sockets created by Network.getSocketFactory().createSocket() and
4549 * performing network-specific host name resolutions via
4550 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004551 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004552 *
4553 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4554 * the current binding.
4555 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4556 */
Chalard Jean158702d2019-01-07 19:26:34 +09004557 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004558 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004559 // instantiated.
4560 return setProcessDefaultNetwork(network);
4561 }
4562
4563 /**
4564 * Binds the current process to {@code network}. All Sockets created in the future
4565 * (and not explicitly bound via a bound SocketFactory from
4566 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4567 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4568 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4569 * work and all host name resolutions will fail. This is by design so an application doesn't
4570 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4571 * To clear binding pass {@code null} for {@code network}. Using individually bound
4572 * Sockets created by Network.getSocketFactory().createSocket() and
4573 * performing network-specific host name resolutions via
4574 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4575 * {@code setProcessDefaultNetwork}.
4576 *
4577 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4578 * the current binding.
4579 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4580 * @deprecated This function can throw {@link IllegalStateException}. Use
4581 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4582 * is a direct replacement.
4583 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004584 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004585 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004586 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004587 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4588
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004589 if (netId != NETID_UNSET) {
4590 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004591 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004592
4593 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4594 return false;
4595 }
4596
4597 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004598 // Set HTTP proxy system properties to match network.
4599 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004600 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004601 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004602 } catch (SecurityException e) {
4603 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4604 Log.e(TAG, "Can't set proxy properties", e);
4605 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004606 // Must flush DNS cache as new network may have different DNS resolutions.
4607 InetAddress.clearDnsCache();
4608 // Must flush socket pool as idle sockets will be bound to previous network and may
4609 // cause subsequent fetches to be performed on old network.
4610 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004611 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004612
4613 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004614 }
4615
4616 /**
4617 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004618 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004619 *
4620 * @return {@code Network} to which this process is bound, or {@code null}.
4621 */
Chalard Jean158702d2019-01-07 19:26:34 +09004622 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004623 public Network getBoundNetworkForProcess() {
4624 // Forcing callers to call thru non-static function ensures ConnectivityManager
4625 // instantiated.
4626 return getProcessDefaultNetwork();
4627 }
4628
4629 /**
4630 * Returns the {@link Network} currently bound to this process via
4631 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4632 *
4633 * @return {@code Network} to which this process is bound, or {@code null}.
4634 * @deprecated Using this function can lead to other functions throwing
4635 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4636 * {@code getBoundNetworkForProcess} is a direct replacement.
4637 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004638 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004639 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004640 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004641 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004642 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004643 return new Network(netId);
4644 }
4645
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004646 private void unsupportedStartingFrom(int version) {
4647 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004648 // The getApplicationInfo() call we make below is not supported in system context. Let
4649 // the call through here, and rely on the fact that ConnectivityService will refuse to
4650 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004651 return;
4652 }
4653
4654 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4655 throw new UnsupportedOperationException(
4656 "This method is not supported in target SDK version " + version + " and above");
4657 }
4658 }
4659
4660 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4661 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004662 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004663 // remove these exemptions. Note that this check is not secure, and apps can still access these
4664 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4665 // so is unsupported and may break in the future. http://b/22728205
4666 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004667 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004668 }
4669
Paul Jensen8cdda642014-05-29 10:12:39 -04004670 /**
4671 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004672 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004673 *
4674 * @param network The {@link Network} to bind host resolutions from the current process to, or
4675 * {@code null} to clear the current binding.
4676 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4677 * @hide
4678 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4679 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004680 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004681 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004682 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004683 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004684 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004685 }
Felipe Leme30511352016-01-22 09:44:57 -08004686
4687 /**
4688 * Device is not restricting metered network activity while application is running on
4689 * background.
4690 */
4691 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4692
4693 /**
4694 * Device is restricting metered network activity while application is running on background,
4695 * but application is allowed to bypass it.
4696 * <p>
4697 * In this state, application should take action to mitigate metered network access.
4698 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4699 */
4700 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4701
4702 /**
4703 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004704 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004705 * In this state, application should not try to use the network while running on background,
4706 * because it would be denied.
4707 */
4708 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4709
Felipe Lemed34c9af2016-01-27 14:46:39 -08004710 /**
4711 * A change in the background metered network activity restriction has occurred.
4712 * <p>
4713 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4714 * applies to them.
4715 * <p>
4716 * This is only sent to registered receivers, not manifest receivers.
4717 */
4718 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4719 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4720 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4721
Felipe Leme7e4c1852016-01-25 11:48:04 -08004722 /** @hide */
4723 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004724 @IntDef(flag = false, value = {
4725 RESTRICT_BACKGROUND_STATUS_DISABLED,
4726 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4727 RESTRICT_BACKGROUND_STATUS_ENABLED,
4728 })
Felipe Leme30511352016-01-22 09:44:57 -08004729 public @interface RestrictBackgroundStatus {
4730 }
4731
4732 private INetworkPolicyManager getNetworkPolicyManager() {
4733 synchronized (this) {
4734 if (mNPManager != null) {
4735 return mNPManager;
4736 }
4737 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4738 .getService(Context.NETWORK_POLICY_SERVICE));
4739 return mNPManager;
4740 }
4741 }
4742
4743 /**
4744 * Determines if the calling application is subject to metered network restrictions while
4745 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004746 *
4747 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4748 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4749 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004750 */
4751 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4752 try {
4753 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4754 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004755 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004756 }
4757 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004758
4759 /**
4760 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004761 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4762 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004763 *
4764 * @return Hash of network watchlist config file. Null if config does not exist.
4765 */
Chalard Jean158702d2019-01-07 19:26:34 +09004766 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004767 public byte[] getNetworkWatchlistConfigHash() {
4768 try {
4769 return mService.getNetworkWatchlistConfigHash();
4770 } catch (RemoteException e) {
4771 Log.e(TAG, "Unable to get watchlist config hash");
4772 throw e.rethrowFromSystemServer();
4773 }
4774 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004775
4776 /**
4777 * Returns the {@code uid} of the owner of a network connection.
4778 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004779 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4780 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004781 * @param local The local {@link InetSocketAddress} of a connection.
4782 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004783 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004784 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4785 * android.os.Process#INVALID_UID} if the connection is not found.
4786 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4787 * user.
4788 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004789 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004790 public int getConnectionOwnerUid(
4791 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004792 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4793 try {
4794 return mService.getConnectionOwnerUid(connectionInfo);
4795 } catch (RemoteException e) {
4796 throw e.rethrowFromSystemServer();
4797 }
4798 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004799
4800 private void printStackTrace() {
4801 if (DEBUG) {
4802 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4803 final StringBuffer sb = new StringBuffer();
4804 for (int i = 3; i < callStack.length; i++) {
4805 final String stackTrace = callStack[i].toString();
4806 if (stackTrace == null || stackTrace.contains("android.os")) {
4807 break;
4808 }
4809 sb.append(" [").append(stackTrace).append("]");
4810 }
4811 Log.d(TAG, "StackLog:" + sb.toString());
4812 }
4813 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004814
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004815 /** @hide */
4816 public TestNetworkManager startOrGetTestNetworkManager() {
4817 final IBinder tnBinder;
4818 try {
4819 tnBinder = mService.startOrGetTestNetworkService();
4820 } catch (RemoteException e) {
4821 throw e.rethrowFromSystemServer();
4822 }
4823
4824 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4825 }
4826
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004827 /** @hide */
4828 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4829 return new ConnectivityDiagnosticsManager(mContext, mService);
4830 }
4831
Cody Kestingf53a0752020-04-15 12:33:28 -07004832 /**
4833 * Simulates a Data Stall for the specified Network.
4834 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004835 * <p>This method should only be used for tests.
4836 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004837 * <p>The caller must be the owner of the specified Network.
4838 *
4839 * @param detectionMethod The detection method used to identify the Data Stall.
4840 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4841 * @param network The Network for which a Data Stall is being simluated.
4842 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4843 * @throws SecurityException if the caller is not the owner of the given network.
4844 * @hide
4845 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004846 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004847 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4848 android.Manifest.permission.NETWORK_STACK})
4849 public void simulateDataStall(int detectionMethod, long timestampMillis,
4850 @NonNull Network network, @NonNull PersistableBundle extras) {
4851 try {
4852 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4853 } catch (RemoteException e) {
4854 e.rethrowFromSystemServer();
4855 }
4856 }
James Mattis356a8792020-10-28 21:48:54 -07004857
Daniel Brightf9e945b2020-06-15 16:10:01 -07004858 @NonNull
4859 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4860
4861 /**
4862 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4863 * receive available QoS events related to the {@link Network} and local ip + port
4864 * specified within socketInfo.
4865 * <p/>
4866 * The same {@link QosCallback} must be unregistered before being registered a second time,
4867 * otherwise {@link QosCallbackRegistrationException} is thrown.
4868 * <p/>
4869 * This API does not, in itself, require any permission if called with a network that is not
4870 * restricted. However, the underlying implementation currently only supports the IMS network,
4871 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4872 * useful, because they'd never be called back on networks that they would have access to.
4873 *
4874 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4875 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4876 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4877 * @throws RuntimeException if the app already has too many callbacks registered.
4878 *
4879 * Exceptions after the time of registration is passed through
4880 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4881 *
4882 * @param socketInfo the socket information used to match QoS events
4883 * @param callback receives qos events that satisfy socketInfo
4884 * @param executor The executor on which the callback will be invoked. The provided
4885 * {@link Executor} must run callback sequentially, otherwise the order of
4886 * callbacks cannot be guaranteed.
4887 *
4888 * @hide
4889 */
4890 @SystemApi
4891 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4892 @NonNull final QosCallback callback,
4893 @CallbackExecutor @NonNull final Executor executor) {
4894 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4895 Objects.requireNonNull(callback, "callback must be non-null");
4896 Objects.requireNonNull(executor, "executor must be non-null");
4897
4898 try {
4899 synchronized (mQosCallbackConnections) {
4900 if (getQosCallbackConnection(callback) == null) {
4901 final QosCallbackConnection connection =
4902 new QosCallbackConnection(this, callback, executor);
4903 mQosCallbackConnections.add(connection);
4904 mService.registerQosSocketCallback(socketInfo, connection);
4905 } else {
4906 Log.e(TAG, "registerQosCallback: Callback already registered");
4907 throw new QosCallbackRegistrationException();
4908 }
4909 }
4910 } catch (final RemoteException e) {
4911 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4912
4913 // The same unregister method method is called for consistency even though nothing
4914 // will be sent to the ConnectivityService since the callback was never successfully
4915 // registered.
4916 unregisterQosCallback(callback);
4917 e.rethrowFromSystemServer();
4918 } catch (final ServiceSpecificException e) {
4919 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4920 unregisterQosCallback(callback);
4921 throw convertServiceException(e);
4922 }
4923 }
4924
4925 /**
4926 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4927 * events once unregistered and can be registered a second time.
4928 * <p/>
4929 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4930 *
4931 * @param callback the callback being unregistered
4932 *
4933 * @hide
4934 */
4935 @SystemApi
4936 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4937 Objects.requireNonNull(callback, "The callback must be non-null");
4938 try {
4939 synchronized (mQosCallbackConnections) {
4940 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4941 if (connection != null) {
4942 connection.stopReceivingMessages();
4943 mService.unregisterQosCallback(connection);
4944 mQosCallbackConnections.remove(connection);
4945 } else {
4946 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4947 }
4948 }
4949 } catch (final RemoteException e) {
4950 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4951 e.rethrowFromSystemServer();
4952 }
4953 }
4954
4955 /**
4956 * Gets the connection related to the callback.
4957 *
4958 * @param callback the callback to look up
4959 * @return the related connection
4960 */
4961 @Nullable
4962 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4963 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4964 // Checking by reference here is intentional
4965 if (connection.getCallback() == callback) {
4966 return connection;
4967 }
4968 }
4969 return null;
4970 }
Junyu Laia62493f2021-01-19 11:10:56 +00004971
4972 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004973 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Laia62493f2021-01-19 11:10:56 +00004974 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4975 * be used to request that the system provide a network without causing the network to be
4976 * in the foreground.
4977 *
4978 * <p>This method will attempt to find the best network that matches the passed
4979 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4980 * criteria. The platform will evaluate which network is the best at its own discretion.
4981 * Throughput, latency, cost per byte, policy, user preference and other considerations
4982 * may be factored in the decision of what is considered the best network.
4983 *
4984 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4985 * matching this request, while always attempting to match the request to a better network if
4986 * possible. If a better match is found, the platform will switch this request to the now-best
4987 * network and inform the app of the newly best network by invoking
4988 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4989 * will not try to maintain any other network than the best one currently matching the request:
4990 * a network not matching any network request may be disconnected at any time.
4991 *
4992 * <p>For example, an application could use this method to obtain a connected cellular network
4993 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4994 * radio to consume additional power. Or, an application could inform the system that it wants
4995 * a network supporting sending MMSes and have the system let it know about the currently best
4996 * MMS-supporting network through the provided {@link NetworkCallback}.
4997 *
4998 * <p>The status of the request can be followed by listening to the various callbacks described
4999 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5000 * used to direct traffic to the network (although accessing some networks may be subject to
5001 * holding specific permissions). Callers will learn about the specific characteristics of the
5002 * network through
5003 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5004 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5005 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5006 * matching the request at any given time; therefore when a better network matching the request
5007 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5008 * with the new network after which no further updates are given about the previously-best
5009 * network, unless it becomes the best again at some later time. All callbacks are invoked
5010 * in order on the same thread, which by default is a thread created by the framework running
5011 * in the app.
5012 *
5013 * <p>This{@link NetworkRequest} will live until released via
5014 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5015 * which point the system may let go of the network at any time.
5016 *
5017 * <p>It is presently unsupported to request a network with mutable
5018 * {@link NetworkCapabilities} such as
5019 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5020 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5021 * as these {@code NetworkCapabilities} represent states that a particular
5022 * network may never attain, and whether a network will attain these states
5023 * is unknown prior to bringing up the network so the framework does not
5024 * know how to go about satisfying a request with these capabilities.
5025 *
5026 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5027 * number of outstanding requests to 100 per app (identified by their UID), shared with
5028 * all variants of this method, of {@link #registerNetworkCallback} as well as
5029 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5030 * Requesting a network with this method will count toward this limit. If this limit is
5031 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5032 * make sure to unregister the callbacks with
5033 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5034 *
5035 * @param request {@link NetworkRequest} describing this request.
5036 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5037 * If null, the callback is invoked on the default internal Handler.
5038 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5039 * the callback must not be shared - it uniquely specifies this request.
5040 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5041 * @throws SecurityException if missing the appropriate permissions.
5042 * @throws RuntimeException if the app already has too many callbacks registered.
5043 *
5044 * @hide
5045 */
5046 @SystemApi(client = MODULE_LIBRARIES)
5047 @SuppressLint("ExecutorRegistration")
5048 @RequiresPermission(anyOf = {
5049 android.Manifest.permission.NETWORK_SETTINGS,
5050 android.Manifest.permission.NETWORK_STACK,
5051 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5052 })
5053 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai962bdb82021-03-09 20:49:48 +08005054 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Laia62493f2021-01-19 11:10:56 +00005055 final NetworkCapabilities nc = request.networkCapabilities;
5056 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulai962bdb82021-03-09 20:49:48 +08005057 TYPE_NONE, new CallbackHandler(handler));
Junyu Laia62493f2021-01-19 11:10:56 +00005058 }
James Mattis45d81842021-01-10 14:24:24 -08005059
5060 /**
5061 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
5062 * OnSetOemNetworkPreferenceListener)}.
James Mattisda32cfe2021-01-26 16:23:52 -08005063 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005064 */
James Mattisda32cfe2021-01-26 16:23:52 -08005065 @SystemApi
5066 public interface OnSetOemNetworkPreferenceListener {
James Mattis45d81842021-01-10 14:24:24 -08005067 /**
5068 * Called when setOemNetworkPreference() successfully completes.
5069 */
5070 void onComplete();
5071 }
5072
5073 /**
5074 * Used by automotive devices to set the network preferences used to direct traffic at an
5075 * application level as per the given OemNetworkPreferences. An example use-case would be an
5076 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5077 * vehicle via a particular network.
5078 *
5079 * Calling this will overwrite the existing preference.
5080 *
5081 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5082 * @param executor the executor on which listener will be invoked.
5083 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5084 * communicate completion of setOemNetworkPreference(). This will only be
5085 * called once upon successful completion of setOemNetworkPreference().
5086 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5087 * @throws SecurityException if missing the appropriate permissions.
5088 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005089 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005090 */
James Mattisda32cfe2021-01-26 16:23:52 -08005091 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005092 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005093 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005094 @Nullable @CallbackExecutor final Executor executor,
5095 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5096 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5097 if (null != listener) {
5098 Objects.requireNonNull(executor, "Executor must be non-null");
5099 }
5100 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5101 new IOnSetOemNetworkPreferenceListener.Stub() {
5102 @Override
5103 public void onComplete() {
5104 executor.execute(listener::onComplete);
5105 }
5106 };
5107
5108 try {
5109 mService.setOemNetworkPreference(preference, listenerInternal);
5110 } catch (RemoteException e) {
5111 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5112 throw e.rethrowFromSystemServer();
5113 }
5114 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005115}