blob: 001e3a72d22688b1d05b21afaeda819abe26c2c0 [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;
paulhu56e09df2021-03-17 20:30:33 +080019import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_DEFAULT_MODE;
20import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE;
Junyu Laia62493f2021-01-19 11:10:56 +000021import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaiad010792021-01-11 16:53:38 +080022import static android.net.NetworkRequest.Type.LISTEN;
junyulai1b1c8742021-03-12 20:05:08 +080023import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
junyulaiad010792021-01-11 16:53:38 +080024import static android.net.NetworkRequest.Type.REQUEST;
25import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +090026import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Brightf9e945b2020-06-15 16:10:01 -070027import static android.net.QosCallback.QosCallbackRegistrationException;
junyulaid05a1922019-01-15 11:32:44 +080028
junyulai4c95b082018-12-27 17:25:29 +080029import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080030import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090031import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000032import android.annotation.Nullable;
Jeff Sharkey656584a2017-04-24 11:18:03 -060033import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080034import android.annotation.SdkConstant;
35import android.annotation.SdkConstant.SdkConstantType;
lucaslin705c3332021-03-12 17:56:09 +080036import android.annotation.StringDef;
Junyu Laia62493f2021-01-19 11:10:56 +000037import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080038import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060039import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070040import android.app.PendingIntent;
Artur Satayev9c2add62019-12-10 17:47:52 +000041import android.compat.annotation.UnsupportedAppUsage;
lucaslin705c3332021-03-12 17:56:09 +080042import android.content.ContentResolver;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070043import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070044import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080045import android.net.IpSecManager.UdpEncapsulationSocket;
46import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080047import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080048import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080049import android.net.TetheringManager.TetheringRequest;
Roshan Pius951c0032020-12-22 15:10:42 -080050import android.net.wifi.WifiNetworkSuggestion;
Robert Greenwalt2034b912009-08-12 16:08:25 -070051import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000052import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070053import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080054import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070055import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080056import android.os.IBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070057import android.os.Looper;
58import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070059import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080060import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070061import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090062import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080064import android.os.ResultReceiver;
Hugo Benichia590ab82017-05-11 13:16:17 +090065import android.os.ServiceSpecificException;
Chalard Jeanfa45a682021-02-25 17:23:40 +090066import android.os.UserHandle;
Jeff Sharkey971cd162011-08-29 16:02:57 -070067import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080068import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080069import android.telephony.TelephonyManager;
lucaslin705c3332021-03-12 17:56:09 +080070import android.text.TextUtils;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080071import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070072import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090073import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090074import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080075
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090076import com.android.connectivity.aidl.INetworkAgent;
markchien6ae63e52020-01-21 13:11:06 +080077import com.android.internal.annotations.GuardedBy;
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +000078import com.android.internal.util.Preconditions;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070079
Paul Jensen3e2917c2014-08-27 12:38:45 -040080import libcore.net.event.NetworkEventDispatcher;
81
junyulai7e06ad42019-03-04 22:45:36 +080082import java.io.IOException;
83import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080084import java.lang.annotation.Retention;
85import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090086import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080087import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070088import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080089import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090090import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090091import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080092import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090093import java.util.List;
94import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080095import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080096import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080097import java.util.concurrent.ExecutorService;
98import java.util.concurrent.Executors;
99import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -0800100
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101/**
102 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600103 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800104 * <p>
105 * The primary responsibilities of this class are to:
106 * <ol>
107 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
108 * <li>Send broadcast intents when network connectivity changes</li>
109 * <li>Attempt to "fail over" to another network when connectivity to a network
110 * is lost</li>
111 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
112 * state of the available networks</li>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700113 * <li>Provide an API that allows applications to request and select networks for their data
114 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800115 * </ol>
116 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600117@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700118public class ConnectivityManager {
119 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900120 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700121
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700123 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800124 * been established or lost. The NetworkInfo for the affected network is
125 * sent as an extra; it should be consulted to see what kind of
126 * connectivity event occurred.
127 * <p/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800128 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
129 * broadcast if they declare the broadcast receiver in their manifest. Apps
130 * will still receive broadcasts if they register their
131 * {@link android.content.BroadcastReceiver} with
132 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
133 * and that context is still valid.
134 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135 * If this is a connection that was the result of failing over from a
136 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
137 * set to true.
138 * <p/>
139 * For a loss of connectivity, if the connectivity manager is attempting
140 * to connect (or has already connected) to another network, the
141 * NetworkInfo for the new network is also passed as an extra. This lets
142 * any receivers of the broadcast know that they should not necessarily
143 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800144 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145 * the failover attempt succeeded (and so there is still overall data
146 * connectivity), or that the failover attempt failed, meaning that all
147 * connectivity has been lost.
148 * <p/>
149 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
150 * is set to {@code true} if there are no connected networks at all.
Chalard Jean52e23962018-02-10 05:33:50 +0900151 *
152 * @deprecated apps should use the more versatile {@link #requestNetwork},
153 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
154 * functions instead for faster and more detailed updates about the network
155 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800157 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900158 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700160
The Android Open Source Project28527d22009-03-03 19:31:44 -0800161 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500162 * The device has connected to a network that has presented a captive
163 * portal, which is blocking Internet connectivity. The user was presented
164 * with a notification that network sign in is required,
165 * and the user invoked the notification's action indicating they
Paul Jensen75e0adb2015-05-22 10:50:39 -0400166 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500167 * facilitate signing in to the network. This action includes a
168 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
169 * the network presenting the captive portal; all communication with the
170 * captive portal must be done using this {@code Network} object.
171 * <p/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400172 * This activity includes a {@link CaptivePortal} extra named
173 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
174 * outcomes of the captive portal sign in to the system:
175 * <ul>
176 * <li> When the app handling this action believes the user has signed in to
177 * the network and the captive portal has been dismissed, the app should
178 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
179 * reevaluate the network. If reevaluation finds the network no longer
180 * subject to a captive portal, the network may become the default active
Chalard Jean9dd11612018-06-04 16:52:49 +0900181 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400182 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500183 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400184 * {@link CaptivePortal#ignoreNetwork}. </li>
185 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500186 */
187 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
188 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
189
190 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800191 * The lookup key for a {@link NetworkInfo} object. Retrieve with
192 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700193 *
Chalard Jean97021a12019-01-11 16:47:53 +0900194 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
195 * can't accurately represent modern network characteristics.
196 * Please obtain information about networks from the {@link NetworkCapabilities}
197 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700199 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800200 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700201
The Android Open Source Project28527d22009-03-03 19:31:44 -0800202 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700203 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700204 *
205 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900206 * @deprecated The network type is not rich enough to represent the characteristics
207 * of modern networks. Please use {@link NetworkCapabilities} instead,
208 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700209 */
Chalard Jean97021a12019-01-11 16:47:53 +0900210 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700211 public static final String EXTRA_NETWORK_TYPE = "networkType";
212
213 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214 * The lookup key for a boolean that indicates whether a connect event
215 * is for a network to which the connectivity manager was failing over
216 * following a disconnect on another network.
217 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai9826e7f2018-12-13 12:47:51 +0800218 *
219 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220 */
junyulai9826e7f2018-12-13 12:47:51 +0800221 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222 public static final String EXTRA_IS_FAILOVER = "isFailover";
223 /**
224 * The lookup key for a {@link NetworkInfo} object. This is supplied when
225 * there is another network that it may be possible to connect to. Retrieve with
226 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800227 *
228 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229 */
junyulai9826e7f2018-12-13 12:47:51 +0800230 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
232 /**
233 * The lookup key for a boolean that indicates whether there is a
234 * complete lack of connectivity, i.e., no network is available.
235 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
236 */
237 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
238 /**
239 * The lookup key for a string that indicates why an attempt to connect
240 * to a network failed. The string has no particular structure. It is
241 * intended to be used in notifications presented to users. Retrieve
242 * it with {@link android.content.Intent#getStringExtra(String)}.
243 */
244 public static final String EXTRA_REASON = "reason";
245 /**
246 * The lookup key for a string that provides optionally supplied
247 * extra information about the network state. The information
248 * may be passed up from the lower networking layers, and its
249 * meaning may be specific to a particular network type. Retrieve
250 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800251 *
252 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800253 */
junyulai9826e7f2018-12-13 12:47:51 +0800254 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800255 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700256 /**
257 * The lookup key for an int that provides information about
258 * our connection to the internet at large. 0 indicates no connection,
259 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700260 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700261 * {@hide}
262 */
263 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800264 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400265 * The lookup key for a {@link CaptivePortal} object included with the
266 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
267 * object can be used to either indicate to the system that the captive
268 * portal has been dismissed or that the user does not want to pursue
269 * signing in to captive portal. Retrieve it with
270 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500271 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400272 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700273
274 /**
275 * Key for passing a URL to the captive portal login activity.
276 */
277 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
278
Paul Jensen60df4aa2015-02-27 22:55:47 -0500279 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900280 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
281 * portal login activity.
282 * {@hide}
283 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900284 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900285 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
286 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
287
288 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900289 * Key for passing a user agent string to the captive portal login activity.
290 * {@hide}
291 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900292 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900293 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
294 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
295
296 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700297 * Broadcast action to indicate the change of data activity status
298 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800299 * The network becomes active when data transmission is started, or
300 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700301 * {@hide}
302 */
303 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900304 public static final String ACTION_DATA_ACTIVITY_CHANGE =
305 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700306 /**
307 * The lookup key for an enum that indicates the network device type on which this data activity
308 * change happens.
309 * {@hide}
310 */
311 public static final String EXTRA_DEVICE_TYPE = "deviceType";
312 /**
313 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
314 * it is actively sending or receiving data and {@code false} means it is idle.
315 * {@hide}
316 */
317 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700318 /**
319 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
320 * {@hide}
321 */
322 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700323
324 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800325 * Broadcast Action: The setting for background data usage has changed
326 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
327 * <p>
328 * If an application uses the network in the background, it should listen
329 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700330 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800331 * <p>
332 *
333 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
334 * of background data depends on several combined factors, and
335 * this broadcast is no longer sent. Instead, when background
336 * data is unavailable, {@link #getActiveNetworkInfo()} will now
337 * appear disconnected. During first boot after a platform
338 * upgrade, this broadcast will be sent once if
339 * {@link #getBackgroundDataSetting()} was {@code false} before
340 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800341 */
342 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800343 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800344 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
345 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
346
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700347 /**
348 * Broadcast Action: The network connection may not be good
349 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
350 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
351 * the network and it's condition.
352 * @hide
353 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800354 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100355 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700356 public static final String INET_CONDITION_ACTION =
357 "android.net.conn.INET_CONDITION_ACTION";
358
Robert Greenwalt2034b912009-08-12 16:08:25 -0700359 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800360 * Broadcast Action: A tetherable connection has come or gone.
361 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900362 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
363 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800364 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
365 * the current state of tethering. Each include a list of
366 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800367 * @hide
368 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800369 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000370 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800371 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800372 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800373
374 /**
375 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800376 * gives a String[] listing all the interfaces configured for
377 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800378 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000379 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800380 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800381
382 /**
383 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900384 * gives a String[] listing all the interfaces currently in local-only
385 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800386 */
markchiena0f8fd92019-12-25 19:40:32 +0800387 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900388
389 /**
390 * @hide
391 * gives a String[] listing all the interfaces currently tethered
392 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
393 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000394 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800395 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800396
397 /**
398 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800399 * gives a String[] listing all the interfaces we tried to tether and
400 * failed. Use {@link #getLastTetherError} to find the error code
401 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800402 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000403 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800404 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800405
406 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800407 * Broadcast Action: The captive portal tracker has finished its test.
408 * Sent only while running Setup Wizard, in lieu of showing a user
409 * notification.
410 * @hide
411 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800412 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800413 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
414 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
415 /**
416 * The lookup key for a boolean that indicates whether a captive portal was detected.
417 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
418 * @hide
419 */
420 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
421
422 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900423 * Action used to display a dialog that asks the user whether to connect to a network that is
424 * not validated. This intent is used to start the dialog in settings via startActivity.
425 *
426 * @hide
427 */
428 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
429
430 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900431 * Action used to display a dialog that asks the user whether to avoid a network that is no
432 * longer validated. This intent is used to start the dialog in settings via startActivity.
433 *
434 * @hide
435 */
436 public static final String ACTION_PROMPT_LOST_VALIDATION =
437 "android.net.conn.PROMPT_LOST_VALIDATION";
438
439 /**
lucaslin2240ef62019-03-12 13:08:03 +0800440 * Action used to display a dialog that asks the user whether to stay connected to a network
441 * that has not validated. This intent is used to start the dialog in settings via
442 * startActivity.
443 *
444 * @hide
445 */
446 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
447 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
448
449 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800450 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900451 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800452 * @hide
453 */
markchiena0f8fd92019-12-25 19:40:32 +0800454 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800455
456 /**
457 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900458 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800459 * @hide
460 */
461 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900462 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800463
464 /**
465 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900466 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800467 * @hide
468 */
469 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900470 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800471
472 /**
473 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900474 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800475 * @hide
476 */
477 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900478 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800479
480 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800481 * Wifi P2p tethering type.
482 * Wifi P2p tethering is set through events automatically, and don't
483 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
484 * @hide
485 */
markchiena0f8fd92019-12-25 19:40:32 +0800486 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800487
488 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800489 * Extra used for communicating with the TetherService. Includes the type of tethering to
490 * enable if any.
491 * @hide
492 */
markchien6ae63e52020-01-21 13:11:06 +0800493 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800494
495 /**
496 * Extra used for communicating with the TetherService. Includes the type of tethering for
497 * which to cancel provisioning.
498 * @hide
499 */
markchien6ae63e52020-01-21 13:11:06 +0800500 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800501
502 /**
503 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
504 * provisioning.
505 * @hide
506 */
markchien6ae63e52020-01-21 13:11:06 +0800507 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800508
509 /**
510 * Tells the TetherService to run a provision check now.
511 * @hide
512 */
markchien6ae63e52020-01-21 13:11:06 +0800513 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800514
515 /**
516 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
517 * which will receive provisioning results. Can be left empty.
518 * @hide
519 */
markchien6ae63e52020-01-21 13:11:06 +0800520 public static final String EXTRA_PROVISION_CALLBACK =
521 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800522
523 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800524 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700525 * @hide
526 */
paulhu74357e72020-01-13 16:46:45 +0800527 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700528 public static final int TYPE_NONE = -1;
529
530 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900531 * A Mobile data connection. Devices may support more than one.
532 *
533 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
534 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
535 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700536 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900537 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700538 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900539
Robert Greenwalt2034b912009-08-12 16:08:25 -0700540 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900541 * A WIFI data connection. Devices may support more than one.
542 *
543 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
544 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
545 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700546 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900547 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700548 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900549
Robert Greenwalt2034b912009-08-12 16:08:25 -0700550 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800551 * An MMS-specific Mobile data connection. This network type may use the
552 * same network interface as {@link #TYPE_MOBILE} or it may use a different
553 * one. This is used by applications needing to talk to the carrier's
554 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900555 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900556 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900557 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900558 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700559 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700560 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700561 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900562
Robert Greenwalt2034b912009-08-12 16:08:25 -0700563 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800564 * A SUPL-specific Mobile data connection. This network type may use the
565 * same network interface as {@link #TYPE_MOBILE} or it may use a different
566 * one. This is used by applications needing to talk to the carrier's
567 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900568 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900569 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900570 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900571 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700572 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700573 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700574 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900575
Robert Greenwalt2034b912009-08-12 16:08:25 -0700576 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800577 * A DUN-specific Mobile data connection. This network type may use the
578 * same network interface as {@link #TYPE_MOBILE} or it may use a different
579 * one. This is sometimes by the system when setting up an upstream connection
580 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900581 *
582 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
583 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
584 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700585 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900586 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700587 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900588
Robert Greenwalt2034b912009-08-12 16:08:25 -0700589 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800590 * A High Priority Mobile data connection. This network type uses the
591 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900592 * is different.
593 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900594 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
595 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
596 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700597 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700598 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700599 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900600
jshbfa81722010-03-11 15:04:43 -0800601 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900602 * A WiMAX data connection.
603 *
604 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
605 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
606 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800607 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900608 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800609 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800610
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800611 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900612 * A Bluetooth data connection.
613 *
614 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
615 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
616 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800617 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900618 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800619 public static final int TYPE_BLUETOOTH = 7;
620
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700621 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800622 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900623 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700624 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900625 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800626 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800627
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700628 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900629 * An Ethernet data connection.
630 *
631 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
632 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
633 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700634 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900635 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800636 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700637
Wink Savilleb7c92c72011-03-12 14:52:01 -0800638 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800639 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900640 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800641 * {@hide}
642 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900643 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900644 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800645 public static final int TYPE_MOBILE_FOTA = 10;
646
647 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800648 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900649 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800650 * {@hide}
651 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900652 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100653 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800654 public static final int TYPE_MOBILE_IMS = 11;
655
656 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800657 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900658 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800659 * {@hide}
660 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900661 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900662 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800663 public static final int TYPE_MOBILE_CBS = 12;
664
repo syncf5de5572011-07-29 23:55:49 -0700665 /**
666 * A Wi-Fi p2p connection. Only requesting processes will have access to
667 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900668 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700669 * {@hide}
670 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900671 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800672 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700673 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800674
Wink Saville512c2202013-07-29 15:00:57 -0700675 /**
676 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900677 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700678 * {@hide}
679 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900680 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100681 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700682 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700683
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900684 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700685 * Emergency PDN connection for emergency services. This
686 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900687 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700688 * {@hide}
689 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900690 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900691 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700692 public static final int TYPE_MOBILE_EMERGENCY = 15;
693
Hui Lu865b70d2014-01-15 11:05:36 -0500694 /**
695 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900696 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500697 * {@hide}
698 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900699 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900700 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500701 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700702
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700703 /**
704 * A virtual network using one or more native bearers.
705 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900706 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700707 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900708 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700709 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500710
Benedict Wongbdfaa482018-11-14 17:40:55 -0800711 /**
712 * A network that is exclusively meant to be used for testing
713 *
714 * @deprecated Use {@link NetworkCapabilities} instead.
715 * @hide
716 */
717 @Deprecated
718 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700719
Chalard Jeanaea539a2020-03-25 01:24:04 +0900720 /**
721 * @deprecated Use {@link NetworkCapabilities} instead.
722 * @hide
723 */
724 @Deprecated
725 @Retention(RetentionPolicy.SOURCE)
726 @IntDef(prefix = { "TYPE_" }, value = {
727 TYPE_NONE,
728 TYPE_MOBILE,
729 TYPE_WIFI,
730 TYPE_MOBILE_MMS,
731 TYPE_MOBILE_SUPL,
732 TYPE_MOBILE_DUN,
733 TYPE_MOBILE_HIPRI,
734 TYPE_WIMAX,
735 TYPE_BLUETOOTH,
736 TYPE_DUMMY,
737 TYPE_ETHERNET,
738 TYPE_MOBILE_FOTA,
739 TYPE_MOBILE_IMS,
740 TYPE_MOBILE_CBS,
741 TYPE_WIFI_P2P,
742 TYPE_MOBILE_IA,
743 TYPE_MOBILE_EMERGENCY,
744 TYPE_PROXY,
745 TYPE_VPN,
746 TYPE_TEST
747 })
748 public @interface LegacyNetworkType {}
749
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900750 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
751 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
752 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
753 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
754 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
755
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700756 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800757 public static final int MAX_RADIO_TYPE = TYPE_TEST;
758
759 /** {@hide} */
760 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800761
Hugo Benichiad353f42017-06-20 14:07:59 +0900762 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
763
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800764 /**
765 * If you want to set the default network preference,you can directly
766 * change the networkAttributes array in framework's config.xml.
767 *
768 * @deprecated Since we support so many more networks now, the single
769 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800770 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800771 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800772 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800773 * from an App.
774 */
775 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800776 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
777
Jeff Sharkey8c870452012-09-26 22:03:49 -0700778 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700779 * @hide
780 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900781 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700782
Paul Jensen5dea4352014-07-11 12:28:19 -0400783 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900784 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
785 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900786 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900787 * @hide
788 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900789 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900790 new NetworkRequest.Builder().clearCapabilities().build();
791
792 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400793 * A NetID indicating no Network is selected.
794 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
795 * @hide
796 */
797 public static final int NETID_UNSET = 0;
798
Erik Klineb0be3e62017-10-30 15:29:44 +0900799 /**
800 * Private DNS Mode values.
801 *
802 * The "private_dns_mode" global setting stores a String value which is
803 * expected to be one of the following.
804 */
805
806 /**
807 * @hide
808 */
lucaslin705c3332021-03-12 17:56:09 +0800809 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900810 public static final String PRIVATE_DNS_MODE_OFF = "off";
811 /**
812 * @hide
813 */
lucaslin705c3332021-03-12 17:56:09 +0800814 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900815 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
816 /**
817 * @hide
818 */
lucaslin705c3332021-03-12 17:56:09 +0800819 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900820 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin705c3332021-03-12 17:56:09 +0800821
822 /** @hide */
823 @Retention(RetentionPolicy.SOURCE)
824 @StringDef(value = {
825 PRIVATE_DNS_MODE_OFF,
826 PRIVATE_DNS_MODE_OPPORTUNISTIC,
827 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
828 })
829 public @interface PrivateDnsMode {}
Erik Klineb0be3e62017-10-30 15:29:44 +0900830
Chalard Jeana3b77512019-04-09 15:46:21 +0900831 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700832 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900833
Paul Jensenc0618a62014-12-10 15:12:18 -0500834 /**
835 * A kludge to facilitate static access where a Context pointer isn't available, like in the
836 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
837 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
838 * methods that take a Context argument.
839 */
840 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800841
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900842 private final Context mContext;
843
Amos Bianchia9b415a2020-03-04 11:07:38 -0800844 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800845
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800846 /**
847 * Tests if a given integer represents a valid network type.
848 * @param networkType the type to be tested
849 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400850 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
851 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800852 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700853 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700854 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900855 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800856 }
857
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800858 /**
859 * Returns a non-localized string representing a given network type.
860 * ONLY used for debugging output.
861 * @param type the type needing naming
862 * @return a String for the given type, or a string version of the type ("87")
863 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900864 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800865 * {@hide}
866 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900867 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000868 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700869 public static String getNetworkTypeName(int type) {
870 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900871 case TYPE_NONE:
872 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700873 case TYPE_MOBILE:
874 return "MOBILE";
875 case TYPE_WIFI:
876 return "WIFI";
877 case TYPE_MOBILE_MMS:
878 return "MOBILE_MMS";
879 case TYPE_MOBILE_SUPL:
880 return "MOBILE_SUPL";
881 case TYPE_MOBILE_DUN:
882 return "MOBILE_DUN";
883 case TYPE_MOBILE_HIPRI:
884 return "MOBILE_HIPRI";
885 case TYPE_WIMAX:
886 return "WIMAX";
887 case TYPE_BLUETOOTH:
888 return "BLUETOOTH";
889 case TYPE_DUMMY:
890 return "DUMMY";
891 case TYPE_ETHERNET:
892 return "ETHERNET";
893 case TYPE_MOBILE_FOTA:
894 return "MOBILE_FOTA";
895 case TYPE_MOBILE_IMS:
896 return "MOBILE_IMS";
897 case TYPE_MOBILE_CBS:
898 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700899 case TYPE_WIFI_P2P:
900 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700901 case TYPE_MOBILE_IA:
902 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700903 case TYPE_MOBILE_EMERGENCY:
904 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500905 case TYPE_PROXY:
906 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900907 case TYPE_VPN:
908 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700909 default:
910 return Integer.toString(type);
911 }
912 }
913
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800914 /**
Aaron Huang96011892020-06-27 07:18:23 +0800915 * @hide
Aaron Huang96011892020-06-27 07:18:23 +0800916 */
lucaslin7fc930b2021-03-17 14:16:01 +0800917 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huang96011892020-06-27 07:18:23 +0800918 public void systemReady() {
919 try {
920 mService.systemReady();
921 } catch (RemoteException e) {
922 throw e.rethrowFromSystemServer();
923 }
924 }
925
926 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800927 * Checks if a given type uses the cellular data connection.
928 * This should be replaced in the future by a network property.
929 * @param networkType the type to check
930 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900931 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800932 * {@hide}
933 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900934 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900935 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700936 public static boolean isNetworkTypeMobile(int networkType) {
937 switch (networkType) {
938 case TYPE_MOBILE:
939 case TYPE_MOBILE_MMS:
940 case TYPE_MOBILE_SUPL:
941 case TYPE_MOBILE_DUN:
942 case TYPE_MOBILE_HIPRI:
943 case TYPE_MOBILE_FOTA:
944 case TYPE_MOBILE_IMS:
945 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -0700946 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -0700947 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700948 return true;
949 default:
950 return false;
951 }
952 }
953
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800954 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700955 * Checks if the given network type is backed by a Wi-Fi radio.
956 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900957 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700958 * @hide
959 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900960 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700961 public static boolean isNetworkTypeWifi(int networkType) {
962 switch (networkType) {
963 case TYPE_WIFI:
964 case TYPE_WIFI_P2P:
965 return true;
966 default:
967 return false;
968 }
969 }
970
971 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +0900972 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
973 * Specify that the traffic for this user should by follow the default rules.
974 * @hide
975 */
Chalard Jeanb43f3962021-03-17 14:33:24 +0900976 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +0900977 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
978
979 /**
980 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
981 * Specify that the traffic for this user should by default go on a network with
982 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
983 * if no such network is available.
984 * @hide
985 */
Chalard Jeanb43f3962021-03-17 14:33:24 +0900986 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +0900987 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
988
989 /** @hide */
990 @Retention(RetentionPolicy.SOURCE)
991 @IntDef(value = {
992 PROFILE_NETWORK_PREFERENCE_DEFAULT,
993 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
994 })
995 public @interface ProfileNetworkPreference {
996 }
997
998 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800999 * Specifies the preferred network type. When the device has more
1000 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001001 *
1002 * @param preference the network type to prefer over all others. It is
1003 * unspecified what happens to the old preferred network in the
1004 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001005 * @deprecated Functionality has been removed as it no longer makes sense,
1006 * with many more than two networks - we'd need an array to express
1007 * preference. Instead we use dynamic network properties of
1008 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001009 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001010 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001011 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001012 }
1013
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001014 /**
1015 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001016 *
1017 * @return an integer representing the preferred network type
1018 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001019 * @deprecated Functionality has been removed as it no longer makes sense,
1020 * with many more than two networks - we'd need an array to express
1021 * preference. Instead we use dynamic network properties of
1022 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001023 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001024 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001025 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001026 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001027 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001028 }
1029
Scott Mainf58b7d82011-10-06 19:02:28 -07001030 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001031 * Returns details about the currently active default data network. When
1032 * connected, this network is the default route for outgoing connections.
1033 * You should always check {@link NetworkInfo#isConnected()} before initiating
1034 * network traffic. This may return {@code null} when there is no default
1035 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001036 * Note that if the default network is a VPN, this method will return the
1037 * NetworkInfo for one of its underlying networks instead, or null if the
1038 * VPN agent did not specify any. Apps interested in learning about VPNs
1039 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001040 *
1041 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001042 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001043 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001044 */
junyulai9826e7f2018-12-13 12:47:51 +08001045 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001046 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001047 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001048 public NetworkInfo getActiveNetworkInfo() {
1049 try {
1050 return mService.getActiveNetworkInfo();
1051 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001052 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001053 }
1054 }
1055
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001056 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001057 * Returns a {@link Network} object corresponding to the currently active
1058 * default data network. In the event that the current active default data
1059 * network disconnects, the returned {@code Network} object will no longer
1060 * be usable. This will return {@code null} when there is no default
1061 * network.
1062 *
1063 * @return a {@link Network} object for the current default network or
1064 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001065 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001066 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001067 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001068 public Network getActiveNetwork() {
1069 try {
1070 return mService.getActiveNetwork();
1071 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001072 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001073 }
1074 }
1075
1076 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001077 * Returns a {@link Network} object corresponding to the currently active
1078 * default data network for a specific UID. In the event that the default data
1079 * network disconnects, the returned {@code Network} object will no longer
1080 * be usable. This will return {@code null} when there is no default
1081 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001082 *
1083 * @return a {@link Network} object for the current default network for the
1084 * given UID or {@code null} if no default network is currently active
1085 *
1086 * @hide
1087 */
paulhu8e96a752019-08-12 16:25:11 +08001088 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001089 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001090 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001091 return getActiveNetworkForUid(uid, false);
1092 }
1093
1094 /** {@hide} */
1095 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001096 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001097 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001098 } catch (RemoteException e) {
1099 throw e.rethrowFromSystemServer();
1100 }
1101 }
1102
1103 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001104 * Adds or removes a requirement for given UID ranges to use the VPN.
1105 *
1106 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1107 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1108 * otherwise have permission to bypass the VPN (e.g., because they have the
1109 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1110 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1111 * set to {@code false}, a previously-added restriction is removed.
1112 * <p>
1113 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1114 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1115 * remove a previously-added range, the exact range must be removed as is.
1116 * <p>
1117 * The changes are applied asynchronously and may not have been applied by the time the method
1118 * returns. Apps will be notified about any changes that apply to them via
1119 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1120 * effect.
1121 * <p>
1122 * This method should be called only by the VPN code.
1123 *
1124 * @param ranges the UID ranges to restrict
1125 * @param requireVpn whether the specified UID ranges must use a VPN
1126 *
1127 * TODO: expose as @SystemApi.
1128 * @hide
1129 */
1130 @RequiresPermission(anyOf = {
1131 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1132 android.Manifest.permission.NETWORK_STACK})
1133 public void setRequireVpnForUids(boolean requireVpn,
1134 @NonNull Collection<Range<Integer>> ranges) {
1135 Objects.requireNonNull(ranges);
1136 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1137 // This method is not necessarily expected to be used outside the system server, so
1138 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1139 // stack process, or by tests.
1140 UidRange[] rangesArray = new UidRange[ranges.size()];
1141 int index = 0;
1142 for (Range<Integer> range : ranges) {
1143 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1144 }
1145 try {
1146 mService.setRequireVpnForUids(requireVpn, rangesArray);
1147 } catch (RemoteException e) {
1148 throw e.rethrowFromSystemServer();
1149 }
1150 }
1151
1152 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001153 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1154 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1155 * but is still supported for backwards compatibility.
1156 * <p>
1157 * This type of VPN is assumed always to use the system default network, and must always declare
1158 * exactly one underlying network, which is the network that was the default when the VPN
1159 * connected.
1160 * <p>
1161 * Calling this method with {@code true} enables legacy behaviour, specifically:
1162 * <ul>
1163 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1164 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1165 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1166 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1167 * underlying the VPN.</li>
1168 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1169 * similarly replaced by the VPN network state.</li>
1170 * <li>Information on current network interfaces passed to NetworkStatsService will not
1171 * include any VPN interfaces.</li>
1172 * </ul>
1173 *
1174 * @param enabled whether legacy lockdown VPN is enabled or disabled
1175 *
1176 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1177 *
1178 * @hide
1179 */
1180 @RequiresPermission(anyOf = {
1181 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1182 android.Manifest.permission.NETWORK_SETTINGS})
1183 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1184 try {
1185 mService.setLegacyLockdownVpnEnabled(enabled);
1186 } catch (RemoteException e) {
1187 throw e.rethrowFromSystemServer();
1188 }
1189 }
1190
1191 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001192 * Returns details about the currently active default data network
1193 * for a given uid. This is for internal use only to avoid spying
1194 * other apps.
1195 *
1196 * @return a {@link NetworkInfo} object for the current default network
1197 * for the given uid or {@code null} if no default network is
1198 * available for the specified uid.
1199 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001200 * {@hide}
1201 */
paulhu8e96a752019-08-12 16:25:11 +08001202 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001203 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001204 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001205 return getActiveNetworkInfoForUid(uid, false);
1206 }
1207
1208 /** {@hide} */
1209 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001210 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001211 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001212 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001213 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001214 }
1215 }
1216
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001217 /**
1218 * Returns connection status information about a particular
1219 * network type.
1220 *
1221 * @param networkType integer specifying which networkType in
1222 * which you're interested.
1223 * @return a {@link NetworkInfo} object for the requested
1224 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001225 * supported by the device. If {@code networkType} is
1226 * TYPE_VPN and a VPN is active for the calling app,
1227 * then this method will try to return one of the
1228 * underlying networks for the VPN or null if the
1229 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001230 *
Paul Jensendda8e592015-03-18 12:23:02 -04001231 * @deprecated This method does not support multiple connected networks
1232 * of the same type. Use {@link #getAllNetworks} and
1233 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001234 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001235 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001236 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001237 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001238 public NetworkInfo getNetworkInfo(int networkType) {
1239 try {
1240 return mService.getNetworkInfo(networkType);
1241 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001242 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001243 }
1244 }
1245
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001246 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001247 * Returns connection status information about a particular
1248 * Network.
1249 *
1250 * @param network {@link Network} specifying which network
1251 * in which you're interested.
1252 * @return a {@link NetworkInfo} object for the requested
1253 * network or {@code null} if the {@code Network}
1254 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001255 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001256 */
junyulai9826e7f2018-12-13 12:47:51 +08001257 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001258 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001259 @Nullable
1260 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001261 return getNetworkInfoForUid(network, Process.myUid(), false);
1262 }
1263
1264 /** {@hide} */
1265 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001266 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001267 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001268 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001269 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001270 }
1271 }
1272
1273 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001274 * Returns connection status information about all network
1275 * types supported by the device.
1276 *
1277 * @return an array of {@link NetworkInfo} objects. Check each
1278 * {@link NetworkInfo#getType} for which type each applies.
1279 *
Paul Jensendda8e592015-03-18 12:23:02 -04001280 * @deprecated This method does not support multiple connected networks
1281 * of the same type. Use {@link #getAllNetworks} and
1282 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001283 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001284 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001285 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001286 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001287 public NetworkInfo[] getAllNetworkInfo() {
1288 try {
1289 return mService.getAllNetworkInfo();
1290 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001291 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001292 }
1293 }
1294
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001295 /**
junyulaiebd15162021-03-03 12:09:05 +08001296 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1297 * connected.
1298 * @hide
1299 */
1300 @SystemApi(client = MODULE_LIBRARIES)
1301 @RequiresPermission(anyOf = {
1302 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1303 android.Manifest.permission.NETWORK_STACK,
1304 android.Manifest.permission.NETWORK_SETTINGS})
1305 @NonNull
1306 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1307 try {
1308 return mService.getAllNetworkStateSnapshot();
1309 } catch (RemoteException e) {
1310 throw e.rethrowFromSystemServer();
1311 }
1312 }
1313
1314 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001315 * Returns the {@link Network} object currently serving a given type, or
1316 * null if the given type is not connected.
1317 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001318 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001319 * @deprecated This method does not support multiple connected networks
1320 * of the same type. Use {@link #getAllNetworks} and
1321 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001322 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001323 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001324 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001325 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001326 public Network getNetworkForType(int networkType) {
1327 try {
1328 return mService.getNetworkForType(networkType);
1329 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001330 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001331 }
1332 }
1333
1334 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001335 * Returns an array of all {@link Network} currently tracked by the
1336 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001337 *
1338 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001339 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001340 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001341 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001342 public Network[] getAllNetworks() {
1343 try {
1344 return mService.getAllNetworks();
1345 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001346 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001347 }
1348 }
1349
1350 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001351 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001352 * the Networks that applications run by the given user will use by default.
1353 * @hide
1354 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001355 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001356 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1357 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001358 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001359 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001360 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001361 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001362 }
1363 }
1364
1365 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001366 * Returns the IP information for the current default network.
1367 *
1368 * @return a {@link LinkProperties} object describing the IP info
1369 * for the current default network, or {@code null} if there
1370 * is no current default network.
1371 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001372 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001373 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1374 * value of {@link #getActiveNetwork()} instead. In particular,
1375 * this method will return non-null LinkProperties even if the
1376 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001377 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001378 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001379 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001380 public LinkProperties getActiveLinkProperties() {
1381 try {
1382 return mService.getActiveLinkProperties();
1383 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001384 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001385 }
1386 }
1387
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001388 /**
1389 * Returns the IP information for a given network type.
1390 *
1391 * @param networkType the network type of interest.
1392 * @return a {@link LinkProperties} object describing the IP info
1393 * for the given networkType, or {@code null} if there is
1394 * no current default network.
1395 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001396 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001397 * @deprecated This method does not support multiple connected networks
1398 * of the same type. Use {@link #getAllNetworks},
1399 * {@link #getNetworkInfo(android.net.Network)}, and
1400 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001401 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001402 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001403 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001405 public LinkProperties getLinkProperties(int networkType) {
1406 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001407 return mService.getLinkPropertiesForType(networkType);
1408 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001409 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001410 }
1411 }
1412
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001413 /**
1414 * Get the {@link LinkProperties} for the given {@link Network}. This
1415 * will return {@code null} if the network is unknown.
1416 *
1417 * @param network The {@link Network} object identifying the network in question.
1418 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001419 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001420 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001421 @Nullable
1422 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001423 try {
1424 return mService.getLinkProperties(network);
1425 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001426 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001427 }
1428 }
1429
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001430 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001431 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001432 * will return {@code null} if the network is unknown.
1433 *
Roshan Pius951c0032020-12-22 15:10:42 -08001434 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1435 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1436 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1437 * this location sensitive information (subject to app's location permissions) will be
1438 * noted by system. To include any location sensitive data in {@link TransportInfo},
1439 * use a {@link NetworkCallback} with
1440 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1441 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001442 * @param network The {@link Network} object identifying the network in question.
Roshan Pius951c0032020-12-22 15:10:42 -08001443 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001444 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001445 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001446 @Nullable
1447 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001448 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001449 return mService.getNetworkCapabilities(
1450 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001451 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001452 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001453 }
1454 }
1455
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001456 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001457 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001458 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1459 * portal is present.
1460 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1461 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1462 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001463 * The system network validation may be using different strategies to detect captive portals,
1464 * so this method does not necessarily return a URL used by the system. It only returns a URL
1465 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001466 *
Udam Sainicd645462016-01-04 12:16:14 -08001467 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001468 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1469 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001470 */
paulhu8e96a752019-08-12 16:25:11 +08001471 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001472 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001473 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001474 public String getCaptivePortalServerUrl() {
1475 try {
1476 return mService.getCaptivePortalServerUrl();
1477 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001478 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001479 }
1480 }
1481
1482 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001483 * Tells the underlying networking system that the caller wants to
1484 * begin using the named feature. The interpretation of {@code feature}
1485 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001486 *
1487 * <p>This method requires the caller to hold either the
1488 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1489 * or the ability to modify system settings as determined by
1490 * {@link android.provider.Settings.System#canWrite}.</p>
1491 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001492 * @param networkType specifies which network the request pertains to
1493 * @param feature the name of the feature to be used
1494 * @return an integer value representing the outcome of the request.
1495 * The interpretation of this value is specific to each networking
1496 * implementation+feature combination, except that the value {@code -1}
1497 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001498 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001499 * @deprecated Deprecated in favor of the cleaner
1500 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001501 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001502 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001503 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001504 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001505 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001506 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001507 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001508 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1509 if (netCap == null) {
1510 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1511 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001512 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001513 }
1514
1515 NetworkRequest request = null;
1516 synchronized (sLegacyRequests) {
1517 LegacyRequest l = sLegacyRequests.get(netCap);
1518 if (l != null) {
1519 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1520 renewRequestLocked(l);
1521 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001522 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001523 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001524 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001525 }
1526 }
1527
1528 request = requestNetworkForFeatureLocked(netCap);
1529 }
1530 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001531 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001532 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001533 } else {
1534 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001535 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001536 }
1537 }
1538
1539 /**
1540 * Tells the underlying networking system that the caller is finished
1541 * using the named feature. The interpretation of {@code feature}
1542 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001543 *
1544 * <p>This method requires the caller to hold either the
1545 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1546 * or the ability to modify system settings as determined by
1547 * {@link android.provider.Settings.System#canWrite}.</p>
1548 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001549 * @param networkType specifies which network the request pertains to
1550 * @param feature the name of the feature that is no longer needed
1551 * @return an integer value representing the outcome of the request.
1552 * The interpretation of this value is specific to each networking
1553 * implementation+feature combination, except that the value {@code -1}
1554 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001555 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001556 * @deprecated Deprecated in favor of the cleaner
1557 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001558 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001559 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001560 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001561 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001562 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001563 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001564 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001565 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1566 if (netCap == null) {
1567 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1568 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001569 return -1;
1570 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001571
Paul Jensen49f74a32014-12-17 10:39:34 -05001572 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001573 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001574 }
1575 return 1;
1576 }
1577
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001578 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001579 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1580 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001581 switch (feature) {
1582 case "enableCBS":
1583 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1584 case "enableDUN":
1585 case "enableDUNAlways":
1586 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1587 case "enableFOTA":
1588 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1589 case "enableHIPRI":
1590 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1591 case "enableIMS":
1592 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1593 case "enableMMS":
1594 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1595 case "enableSUPL":
1596 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1597 default:
1598 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001599 }
Erik Klinece55eb12017-01-26 18:08:28 +09001600 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1601 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001602 }
1603 return null;
1604 }
1605
Robert Greenwalt802c1102014-06-02 15:32:02 -07001606 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001607 if (netCap == null) return TYPE_NONE;
1608 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1609 return TYPE_MOBILE_CBS;
1610 }
1611 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1612 return TYPE_MOBILE_IMS;
1613 }
1614 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1615 return TYPE_MOBILE_FOTA;
1616 }
1617 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1618 return TYPE_MOBILE_DUN;
1619 }
1620 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1621 return TYPE_MOBILE_SUPL;
1622 }
1623 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1624 return TYPE_MOBILE_MMS;
1625 }
1626 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1627 return TYPE_MOBILE_HIPRI;
1628 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001629 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1630 return TYPE_WIFI_P2P;
1631 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001632 return TYPE_NONE;
1633 }
1634
1635 private static class LegacyRequest {
1636 NetworkCapabilities networkCapabilities;
1637 NetworkRequest networkRequest;
1638 int expireSequenceNumber;
1639 Network currentNetwork;
1640 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001641
1642 private void clearDnsBinding() {
1643 if (currentNetwork != null) {
1644 currentNetwork = null;
1645 setProcessDefaultNetworkForHostResolution(null);
1646 }
1647 }
1648
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001649 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001650 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001651 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001652 currentNetwork = network;
1653 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001654 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001655 }
1656 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001657 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001658 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001659 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1660 }
1661 };
1662 }
1663
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001664 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001665 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1666 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001667
1668 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1669 synchronized (sLegacyRequests) {
1670 LegacyRequest l = sLegacyRequests.get(netCap);
1671 if (l != null) return l.networkRequest;
1672 }
1673 return null;
1674 }
1675
1676 private void renewRequestLocked(LegacyRequest l) {
1677 l.expireSequenceNumber++;
1678 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1679 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1680 }
1681
1682 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1683 int ourSeqNum = -1;
1684 synchronized (sLegacyRequests) {
1685 LegacyRequest l = sLegacyRequests.get(netCap);
1686 if (l == null) return;
1687 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001688 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001689 }
1690 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1691 }
1692
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001693 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001694 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1695 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001696 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001697 try {
1698 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001699 } catch (RemoteException e) {
1700 throw e.rethrowFromSystemServer();
1701 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001702 LegacyRequest l = new LegacyRequest();
1703 l.networkCapabilities = netCap;
1704 l.delay = delay;
1705 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001706 l.networkRequest = sendRequestForNetwork(
1707 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001708 if (l.networkRequest == null) return null;
1709 sLegacyRequests.put(netCap, l);
1710 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1711 return l.networkRequest;
1712 }
1713
1714 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1715 if (delay >= 0) {
1716 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001717 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001718 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1719 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001720 }
1721 }
1722
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001723 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001724 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1725 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001726 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001727 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001728 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001729 if (l == null) return false;
1730 unregisterNetworkCallback(l.networkCallback);
1731 l.clearDnsBinding();
1732 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001733 }
1734
Erik Klinece55eb12017-01-26 18:08:28 +09001735 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1736 static {
1737 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1738 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1739 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1740 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1741 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1742 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1743 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1744 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1745 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1746 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1747 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1748 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1749 }
1750
1751 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1752 static {
1753 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1754 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1755 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1756 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1757 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1758 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1759 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1760 }
1761
1762 /**
1763 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1764 * instance suitable for registering a request or callback. Throws an
1765 * IllegalArgumentException if no mapping from the legacy type to
1766 * NetworkCapabilities is known.
1767 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001768 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1769 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001770 * @hide
1771 */
1772 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1773 final NetworkCapabilities nc = new NetworkCapabilities();
1774
1775 // Map from type to transports.
1776 final int NOT_FOUND = -1;
1777 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00001778 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001779 nc.addTransportType(transport);
1780
1781 // Map from type to capabilities.
1782 nc.addCapability(sLegacyTypeToCapability.get(
1783 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1784 nc.maybeMarkCapabilitiesRestricted();
1785 return nc;
1786 }
1787
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001788 /** @hide */
1789 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001790 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001791 public PacketKeepaliveCallback() {
1792 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001793 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001794 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001795 public void onStarted() {}
1796 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001797 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001798 public void onStopped() {}
1799 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001800 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001801 public void onError(int error) {}
1802 }
1803
1804 /**
1805 * Allows applications to request that the system periodically send specific packets on their
1806 * behalf, using hardware offload to save battery power.
1807 *
1808 * To request that the system send keepalives, call one of the methods that return a
1809 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1810 * passing in a non-null callback. If the callback is successfully started, the callback's
1811 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1812 * specifying one of the {@code ERROR_*} constants in this class.
1813 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001814 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1815 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1816 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001817 *
junyulai4c95b082018-12-27 17:25:29 +08001818 * @deprecated Use {@link SocketKeepalive} instead.
1819 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001820 * @hide
1821 */
1822 public class PacketKeepalive {
1823
1824 private static final String TAG = "PacketKeepalive";
1825
1826 /** @hide */
1827 public static final int SUCCESS = 0;
1828
1829 /** @hide */
1830 public static final int NO_KEEPALIVE = -1;
1831
1832 /** @hide */
1833 public static final int BINDER_DIED = -10;
1834
1835 /** The specified {@code Network} is not connected. */
1836 public static final int ERROR_INVALID_NETWORK = -20;
1837 /** The specified IP addresses are invalid. For example, the specified source IP address is
1838 * not configured on the specified {@code Network}. */
1839 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1840 /** The requested port is invalid. */
1841 public static final int ERROR_INVALID_PORT = -22;
1842 /** The packet length is invalid (e.g., too long). */
1843 public static final int ERROR_INVALID_LENGTH = -23;
1844 /** The packet transmission interval is invalid (e.g., too short). */
1845 public static final int ERROR_INVALID_INTERVAL = -24;
1846
1847 /** The hardware does not support this request. */
1848 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001849 /** The hardware returned an error. */
1850 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001851
Nathan Harold0990bc82018-02-14 13:09:45 -08001852 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001853 public static final int NATT_PORT = 4500;
1854
Nathan Harold0990bc82018-02-14 13:09:45 -08001855 /** The minimum interval in seconds between keepalive packet transmissions */
1856 public static final int MIN_INTERVAL = 10;
1857
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001858 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001859 private final ISocketKeepaliveCallback mCallback;
1860 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001861
1862 private volatile Integer mSlot;
1863
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001864 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001865 public void stop() {
1866 try {
junyulai070f9ff2019-01-16 20:23:34 +08001867 mExecutor.execute(() -> {
1868 try {
1869 if (mSlot != null) {
1870 mService.stopKeepalive(mNetwork, mSlot);
1871 }
1872 } catch (RemoteException e) {
1873 Log.e(TAG, "Error stopping packet keepalive: ", e);
1874 throw e.rethrowFromSystemServer();
1875 }
1876 });
1877 } catch (RejectedExecutionException e) {
1878 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001879 }
1880 }
1881
1882 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00001883 Preconditions.checkNotNull(network, "network cannot be null");
1884 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001885 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001886 mExecutor = Executors.newSingleThreadExecutor();
1887 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001888 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001889 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001890 final long token = Binder.clearCallingIdentity();
1891 try {
1892 mExecutor.execute(() -> {
1893 mSlot = slot;
1894 callback.onStarted();
1895 });
1896 } finally {
1897 Binder.restoreCallingIdentity(token);
1898 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001899 }
junyulai070f9ff2019-01-16 20:23:34 +08001900
1901 @Override
1902 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001903 final long token = Binder.clearCallingIdentity();
1904 try {
1905 mExecutor.execute(() -> {
1906 mSlot = null;
1907 callback.onStopped();
1908 });
1909 } finally {
1910 Binder.restoreCallingIdentity(token);
1911 }
junyulai070f9ff2019-01-16 20:23:34 +08001912 mExecutor.shutdown();
1913 }
1914
1915 @Override
1916 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001917 final long token = Binder.clearCallingIdentity();
1918 try {
1919 mExecutor.execute(() -> {
1920 mSlot = null;
1921 callback.onError(error);
1922 });
1923 } finally {
1924 Binder.restoreCallingIdentity(token);
1925 }
junyulai070f9ff2019-01-16 20:23:34 +08001926 mExecutor.shutdown();
1927 }
1928
1929 @Override
1930 public void onDataReceived() {
1931 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1932 // this callback when data is received.
1933 }
1934 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001935 }
1936 }
1937
1938 /**
1939 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1940 *
junyulai4c95b082018-12-27 17:25:29 +08001941 * @deprecated Use {@link #createSocketKeepalive} instead.
1942 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001943 * @hide
1944 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001945 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001946 public PacketKeepalive startNattKeepalive(
1947 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1948 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1949 final PacketKeepalive k = new PacketKeepalive(network, callback);
1950 try {
junyulai070f9ff2019-01-16 20:23:34 +08001951 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001952 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1953 } catch (RemoteException e) {
1954 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001955 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001956 }
1957 return k;
1958 }
1959
Chiachang Wang619319a2021-01-15 11:06:21 +08001960 // Construct an invalid fd.
1961 private ParcelFileDescriptor createInvalidFd() {
1962 final int invalidFd = -1;
1963 return ParcelFileDescriptor.adoptFd(invalidFd);
1964 }
1965
The Android Open Source Project28527d22009-03-03 19:31:44 -08001966 /**
junyulai4c95b082018-12-27 17:25:29 +08001967 * Request that keepalives be started on a IPsec NAT-T socket.
1968 *
1969 * @param network The {@link Network} the socket is on.
1970 * @param socket The socket that needs to be kept alive.
1971 * @param source The source address of the {@link UdpEncapsulationSocket}.
1972 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1973 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1974 * must run callback sequentially, otherwise the order of callbacks cannot be
1975 * guaranteed.
1976 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1977 * changes. Must be extended by applications that use this API.
1978 *
junyulai0835a1e2019-01-08 20:04:33 +08001979 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1980 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001981 **/
junyulai7e06ad42019-03-04 22:45:36 +08001982 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001983 @NonNull UdpEncapsulationSocket socket,
1984 @NonNull InetAddress source,
1985 @NonNull InetAddress destination,
1986 @NonNull @CallbackExecutor Executor executor,
1987 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001988 ParcelFileDescriptor dup;
1989 try {
junyulai828dad12019-03-27 11:00:37 +08001990 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1991 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001992 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1993 } catch (IOException ignored) {
1994 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1995 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001996 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001997 }
1998 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1999 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002000 }
2001
2002 /**
2003 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2004 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2005 *
2006 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002007 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2008 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2009 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002010 * @param source The source address of the {@link UdpEncapsulationSocket}.
2011 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2012 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2013 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2014 * must run callback sequentially, otherwise the order of callbacks cannot be
2015 * guaranteed.
2016 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2017 * changes. Must be extended by applications that use this API.
2018 *
junyulai0835a1e2019-01-08 20:04:33 +08002019 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2020 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002021 * @hide
2022 */
2023 @SystemApi
2024 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002025 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2026 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002027 @NonNull InetAddress source,
2028 @NonNull InetAddress destination,
2029 @NonNull @CallbackExecutor Executor executor,
2030 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002031 ParcelFileDescriptor dup;
2032 try {
junyulai828dad12019-03-27 11:00:37 +08002033 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002034 dup = pfd.dup();
2035 } catch (IOException ignored) {
2036 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2037 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002038 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002039 }
2040 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANce355502021-03-11 10:56:49 +00002041 -1 /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002042 }
2043
2044 /**
junyulai0835a1e2019-01-08 20:04:33 +08002045 * Request that keepalives be started on a TCP socket.
2046 * The socket must be established.
2047 *
2048 * @param network The {@link Network} the socket is on.
2049 * @param socket The socket that needs to be kept alive.
2050 * @param executor The executor on which callback will be invoked. This implementation assumes
2051 * the provided {@link Executor} runs the callbacks in sequence with no
2052 * concurrency. Failing this, no guarantee of correctness can be made. It is
2053 * the responsibility of the caller to ensure the executor provides this
2054 * guarantee. A simple way of creating such an executor is with the standard
2055 * tool {@code Executors.newSingleThreadExecutor}.
2056 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2057 * changes. Must be extended by applications that use this API.
2058 *
2059 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2060 * given socket.
2061 * @hide
2062 */
2063 @SystemApi
2064 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002065 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002066 @NonNull Socket socket,
2067 @NonNull Executor executor,
2068 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002069 ParcelFileDescriptor dup;
2070 try {
2071 dup = ParcelFileDescriptor.fromSocket(socket);
2072 } catch (UncheckedIOException ignored) {
2073 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2074 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002075 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002076 }
2077 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002078 }
2079
2080 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002081 * Ensure that a network route exists to deliver traffic to the specified
2082 * host via the specified network interface. An attempt to add a route that
2083 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002084 *
2085 * <p>This method requires the caller to hold either the
2086 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2087 * or the ability to modify system settings as determined by
2088 * {@link android.provider.Settings.System#canWrite}.</p>
2089 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002090 * @param networkType the type of the network over which traffic to the specified
2091 * host is to be routed
2092 * @param hostAddress the IP address of the host to which the route is desired
2093 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002094 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002095 * @deprecated Deprecated in favor of the
2096 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2097 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002098 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002099 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002100 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002101 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002102 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002103 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002104 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002105 }
2106
2107 /**
2108 * Ensure that a network route exists to deliver traffic to the specified
2109 * host via the specified network interface. An attempt to add a route that
2110 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002111 *
2112 * <p>This method requires the caller to hold either the
2113 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2114 * or the ability to modify system settings as determined by
2115 * {@link android.provider.Settings.System#canWrite}.</p>
2116 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002117 * @param networkType the type of the network over which traffic to the specified
2118 * host is to be routed
2119 * @param hostAddress the IP address of the host to which the route is desired
2120 * @return {@code true} on success, {@code false} on failure
2121 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002122 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002123 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002124 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002125 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002126 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002127 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002128 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002129 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002130 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2131 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002132 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002133 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134 }
2135 }
2136
2137 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002138 * @return the context's attribution tag
2139 */
2140 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2141 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002142 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002143 }
2144
2145 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002146 * Returns the value of the setting for background data usage. If false,
2147 * applications should not use the network if the application is not in the
2148 * foreground. Developers should respect this setting, and check the value
2149 * of this before performing any background data operations.
2150 * <p>
2151 * All applications that have background services that use the network
2152 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002153 * <p>
Scott Main50589142011-10-06 18:32:43 -07002154 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002155 * background data depends on several combined factors, and this method will
2156 * always return {@code true}. Instead, when background data is unavailable,
2157 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002158 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002159 * @return Whether background data usage is allowed.
2160 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002161 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002162 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002163 // assume that background data is allowed; final authority is
2164 // NetworkInfo which may be blocked.
2165 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002166 }
2167
2168 /**
2169 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002170 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002171 * @param allowBackgroundData Whether an application should use data while
2172 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002173 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2175 * @see #getBackgroundDataSetting()
2176 * @hide
2177 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002178 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002179 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002180 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002181 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002182 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002183
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002184 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002185 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002186 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002187 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002188 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002189 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002190 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002191 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2192 if (tm != null) {
2193 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2194 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2195 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2196 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2197 + " retVal=" + retVal);
2198 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002199 }
Wink Saville689f7042014-12-05 11:10:30 -08002200 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002201 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002202 }
2203
The Android Open Source Project28527d22009-03-03 19:31:44 -08002204 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002205 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002206 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002207 */
2208 public interface OnNetworkActiveListener {
2209 /**
2210 * Called on the main thread of the process to report that the current data network
2211 * has become active, and it is now a good time to perform any pending network
2212 * operations. Note that this listener only tells you when the network becomes
2213 * active; if at any other time you want to know whether it is active (and thus okay
2214 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002215 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002216 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002217 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002218 }
2219
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002220 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002221 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002222
2223 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002224 * Start listening to reports when the system's default data network is active, meaning it is
2225 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2226 * to determine the current state of the system's default network after registering the
2227 * listener.
2228 * <p>
2229 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002230 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002231 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002232 *
2233 * @param l The listener to be told when the network is active.
2234 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002235 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002236 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2237 @Override
2238 public void onNetworkActive() throws RemoteException {
2239 l.onNetworkActive();
2240 }
2241 };
2242
2243 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002244 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002245 mNetworkActivityListeners.put(l, rl);
2246 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002247 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002248 }
2249 }
2250
2251 /**
2252 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002253 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002254 *
2255 * @param l Previously registered listener.
2256 */
Chalard Jean158702d2019-01-07 19:26:34 +09002257 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002258 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002259 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002260 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002261 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002262 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002263 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002264 }
2265 }
2266
2267 /**
2268 * Return whether the data network is currently active. An active network means that
2269 * it is currently in a high power state for performing data transmission. On some
2270 * types of networks, it may be expensive to move and stay in such a state, so it is
2271 * more power efficient to batch network traffic together when the radio is already in
2272 * this state. This method tells you whether right now is currently a good time to
2273 * initiate network traffic, as the network is already active.
2274 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002275 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002276 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002277 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002278 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002279 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002280 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002281 }
2282
2283 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002284 * {@hide}
2285 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002286 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002287 mContext = Preconditions.checkNotNull(context, "missing context");
2288 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002289 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002290 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002291 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002292
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002293 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002294 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002295 public static ConnectivityManager from(Context context) {
2296 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2297 }
2298
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002299 /** @hide */
2300 public NetworkRequest getDefaultRequest() {
2301 try {
2302 // This is not racy as the default request is final in ConnectivityService.
2303 return mService.getDefaultRequest();
2304 } catch (RemoteException e) {
2305 throw e.rethrowFromSystemServer();
2306 }
2307 }
2308
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002309 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002310 * Check if the package is a allowed to write settings. This also accounts that such an access
2311 * happened.
2312 *
2313 * @return {@code true} iff the package is allowed to write settings.
2314 */
2315 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2316 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2317 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2318 boolean throwException) {
2319 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2320 throwException);
2321 }
2322
2323 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002324 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2325 * situations where a Context pointer is unavailable.
2326 * @hide
2327 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002328 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002329 static ConnectivityManager getInstanceOrNull() {
2330 return sInstance;
2331 }
2332
2333 /**
2334 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2335 * situations where a Context pointer is unavailable.
2336 * @hide
2337 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002338 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002339 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002340 private static ConnectivityManager getInstance() {
2341 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002342 throw new IllegalStateException("No ConnectivityManager yet constructed");
2343 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002344 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002345 }
2346
2347 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002348 * Get the set of tetherable, available interfaces. This list is limited by
2349 * device configuration and current interface existence.
2350 *
2351 * @return an array of 0 or more Strings of tetherable interface names.
2352 *
markchien6ae63e52020-01-21 13:11:06 +08002353 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002354 * {@hide}
2355 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002356 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002357 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002358 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002359 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002360 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002361 }
2362
2363 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002364 * Get the set of tethered interfaces.
2365 *
2366 * @return an array of 0 or more String of currently tethered interface names.
2367 *
markchien6ae63e52020-01-21 13:11:06 +08002368 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002369 * {@hide}
2370 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002371 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002372 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002373 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002374 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002375 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002376 }
2377
2378 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002379 * Get the set of interface names which attempted to tether but
2380 * failed. Re-attempting to tether may cause them to reset to the Tethered
2381 * state. Alternatively, causing the interface to be destroyed and recreated
2382 * may cause them to reset to the available state.
2383 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2384 * information on the cause of the errors.
2385 *
2386 * @return an array of 0 or more String indicating the interface names
2387 * which failed to tether.
2388 *
markchien6ae63e52020-01-21 13:11:06 +08002389 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002390 * {@hide}
2391 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002392 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002393 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002394 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002395 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002396 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002397 }
2398
2399 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002400 * Get the set of tethered dhcp ranges.
2401 *
markchien2e6ba522020-02-14 11:55:48 +08002402 * @deprecated This method is not supported.
2403 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002404 * {@hide}
2405 */
paulhu8e96a752019-08-12 16:25:11 +08002406 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002407 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002408 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002409 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002410 }
2411
2412 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002413 * Attempt to tether the named interface. This will setup a dhcp server
2414 * on the interface, forward and NAT IP packets and forward DNS requests
2415 * to the best active upstream network interface. Note that if no upstream
2416 * IP network interface is available, dhcp will still run and traffic will be
2417 * allowed between the tethered devices and this device, though upstream net
2418 * access will of course fail until an upstream network interface becomes
2419 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002420 *
2421 * <p>This method requires the caller to hold either the
2422 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2423 * or the ability to modify system settings as determined by
2424 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002425 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002426 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2427 * and WifiStateMachine which need direct access. All other clients should use
2428 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2429 * logic.</p>
2430 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002431 * @param iface the interface name to tether.
2432 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002433 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002434 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002435 * {@hide}
2436 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002437 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002438 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002439 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002440 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002441 }
2442
2443 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002444 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002445 *
2446 * <p>This method requires the caller to hold either the
2447 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2448 * or the ability to modify system settings as determined by
2449 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002450 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002451 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2452 * and WifiStateMachine which need direct access. All other clients should use
2453 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2454 * logic.</p>
2455 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002456 * @param iface the interface name to untether.
2457 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2458 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002459 * {@hide}
2460 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002461 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002462 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002463 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002464 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002465 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002466
2467 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002468 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002469 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002470 * due to device configuration.
2471 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002472 * <p>If this app does not have permission to use this API, it will always
2473 * return false rather than throw an exception.</p>
2474 *
2475 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2476 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2477 *
2478 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2479 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2480 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002481 * @return a boolean - {@code true} indicating Tethering is supported.
2482 *
markchien6ae63e52020-01-21 13:11:06 +08002483 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002484 * {@hide}
2485 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002486 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002487 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2488 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002489 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002490 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002491 }
2492
2493 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002494 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002495 *
2496 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002497 * @hide
2498 */
2499 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002500 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002501 public static abstract class OnStartTetheringCallback {
2502 /**
2503 * Called when tethering has been successfully started.
2504 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002505 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002506
2507 /**
2508 * Called when starting tethering failed.
2509 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002510 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002511 }
2512
2513 /**
2514 * Convenient overload for
2515 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2516 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002517 *
2518 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002519 * @hide
2520 */
2521 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002522 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002523 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002524 public void startTethering(int type, boolean showProvisioningUi,
2525 final OnStartTetheringCallback callback) {
2526 startTethering(type, showProvisioningUi, callback, null);
2527 }
2528
2529 /**
2530 * Runs tether provisioning for the given type if needed and then starts tethering if
2531 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2532 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2533 * schedules tether provisioning re-checks if appropriate.
2534 *
2535 * @param type The type of tethering to start. Must be one of
2536 * {@link ConnectivityManager.TETHERING_WIFI},
2537 * {@link ConnectivityManager.TETHERING_USB}, or
2538 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2539 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2540 * is one. This should be true the first time this function is called and also any time
2541 * the user can see this UI. It gives users information from their carrier about the
2542 * check failing and how they can sign up for tethering if possible.
2543 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2544 * of the result of trying to tether.
2545 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002546 *
2547 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002548 * @hide
2549 */
2550 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002551 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002552 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002553 public void startTethering(int type, boolean showProvisioningUi,
2554 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002555 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002556
markchien91c78e52020-01-20 19:31:56 +08002557 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002558 @Override
markchien91c78e52020-01-20 19:31:56 +08002559 public void execute(Runnable command) {
2560 if (handler == null) {
2561 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002562 } else {
markchien91c78e52020-01-20 19:31:56 +08002563 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002564 }
2565 }
2566 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002567
markchien91c78e52020-01-20 19:31:56 +08002568 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2569 @Override
2570 public void onTetheringStarted() {
2571 callback.onTetheringStarted();
2572 }
2573
2574 @Override
markchienf47d8342020-03-19 13:37:43 +08002575 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002576 callback.onTetheringFailed();
2577 }
2578 };
2579
2580 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002581 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002582
Amos Bianchia9b415a2020-03-04 11:07:38 -08002583 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002584 }
2585
2586 /**
2587 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2588 * applicable.
2589 *
2590 * @param type The type of tethering to stop. Must be one of
2591 * {@link ConnectivityManager.TETHERING_WIFI},
2592 * {@link ConnectivityManager.TETHERING_USB}, or
2593 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002594 *
2595 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002596 * @hide
2597 */
2598 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002599 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002600 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002601 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002602 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002603 }
2604
2605 /**
markchien4ef53e82019-02-27 14:56:11 +08002606 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2607 * upstream status.
2608 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002609 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002610 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002611 */
2612 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002613 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002614 public abstract static class OnTetheringEventCallback {
2615
2616 /**
2617 * Called when tethering upstream changed. This can be called multiple times and can be
2618 * called any time.
2619 *
2620 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2621 * have any upstream.
2622 */
2623 public void onUpstreamChanged(@Nullable Network network) {}
2624 }
2625
markchien6ae63e52020-01-21 13:11:06 +08002626 @GuardedBy("mTetheringEventCallbacks")
2627 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2628 mTetheringEventCallbacks = new ArrayMap<>();
2629
markchien4ef53e82019-02-27 14:56:11 +08002630 /**
2631 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002632 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002633 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2634 * with a null argument. The same callback object cannot be registered twice.
2635 *
2636 * @param executor the executor on which callback will be invoked.
2637 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002638 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002639 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002640 * @hide
2641 */
2642 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002643 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002644 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2645 public void registerTetheringEventCallback(
2646 @NonNull @CallbackExecutor Executor executor,
2647 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002648 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
markchien4ef53e82019-02-27 14:56:11 +08002649
markchien6ae63e52020-01-21 13:11:06 +08002650 final TetheringEventCallback tetherCallback =
2651 new TetheringEventCallback() {
2652 @Override
2653 public void onUpstreamChanged(@Nullable Network network) {
2654 callback.onUpstreamChanged(network);
2655 }
2656 };
2657
2658 synchronized (mTetheringEventCallbacks) {
2659 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002660 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002661 }
markchien4ef53e82019-02-27 14:56:11 +08002662 }
2663
2664 /**
2665 * Remove tethering event callback previously registered with
2666 * {@link #registerTetheringEventCallback}.
2667 *
2668 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002669 *
2670 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002671 * @hide
2672 */
2673 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002674 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002675 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2676 public void unregisterTetheringEventCallback(
2677 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002678 Objects.requireNonNull(callback, "The callback must be non-null");
2679 synchronized (mTetheringEventCallbacks) {
2680 final TetheringEventCallback tetherCallback =
2681 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002682 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002683 }
markchien4ef53e82019-02-27 14:56:11 +08002684 }
2685
2686
2687 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002688 * Get the list of regular expressions that define any tetherable
2689 * USB network interfaces. If USB tethering is not supported by the
2690 * device, this list should be empty.
2691 *
2692 * @return an array of 0 or more regular expression Strings defining
2693 * what interfaces are considered tetherable usb interfaces.
2694 *
markchien6ae63e52020-01-21 13:11:06 +08002695 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002696 * {@hide}
2697 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002698 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002699 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002700 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002701 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002702 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002703 }
2704
2705 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002706 * Get the list of regular expressions that define any tetherable
2707 * Wifi network interfaces. If Wifi tethering is not supported by the
2708 * device, this list should be empty.
2709 *
2710 * @return an array of 0 or more regular expression Strings defining
2711 * what interfaces are considered tetherable wifi interfaces.
2712 *
markchien6ae63e52020-01-21 13:11:06 +08002713 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002714 * {@hide}
2715 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002716 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002717 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002718 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002719 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002720 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002721 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002722
Danica Chang96567052010-08-11 14:54:43 -07002723 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002724 * Get the list of regular expressions that define any tetherable
2725 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2726 * device, this list should be empty.
2727 *
2728 * @return an array of 0 or more regular expression Strings defining
2729 * what interfaces are considered tetherable bluetooth interfaces.
2730 *
markchien6ae63e52020-01-21 13:11:06 +08002731 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2732 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002733 * {@hide}
2734 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002735 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002736 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002737 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002738 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002739 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002740 }
2741
Mike Lockwooded4a1742011-07-19 13:04:47 -07002742 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002743 * Attempt to both alter the mode of USB and Tethering of USB. A
2744 * utility method to deal with some of the complexity of USB - will
2745 * attempt to switch to Rndis and subsequently tether the resulting
2746 * interface on {@code true} or turn off tethering and switch off
2747 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002748 *
2749 * <p>This method requires the caller to hold either the
2750 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2751 * or the ability to modify system settings as determined by
2752 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002753 *
2754 * @param enable a boolean - {@code true} to enable tethering
2755 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002756 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002757 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002758 * {@hide}
2759 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002760 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002761 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002762 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002763 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002764 }
2765
markchien6ae63e52020-01-21 13:11:06 +08002766 /**
2767 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2768 * {@hide}
2769 */
markchien0f45bb92019-01-16 17:44:13 +08002770 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002771 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002772 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002773 /**
2774 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2775 * {@hide}
2776 */
2777 @Deprecated
2778 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2779 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2780 /**
2781 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2782 * {@hide}
2783 */
2784 @Deprecated
2785 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2786 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2787 /**
2788 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2789 * {@hide}
2790 */
2791 @Deprecated
2792 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2793 /**
2794 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2795 * {@hide}
2796 */
2797 @Deprecated
2798 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2799 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2800 /**
markchienf47d8342020-03-19 13:37:43 +08002801 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002802 * {@hide}
2803 */
2804 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002805 public static final int TETHER_ERROR_MASTER_ERROR =
2806 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002807 /**
2808 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2809 * {@hide}
2810 */
2811 @Deprecated
2812 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2813 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2814 /**
2815 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2816 * {@hide}
2817 */
2818 @Deprecated
2819 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2820 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2821 /**
markchienf47d8342020-03-19 13:37:43 +08002822 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002823 * {@hide}
2824 */
2825 @Deprecated
2826 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002827 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002828 /**
markchienf47d8342020-03-19 13:37:43 +08002829 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002830 * {@hide}
2831 */
2832 @Deprecated
2833 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002834 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002835 /**
2836 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2837 * {@hide}
2838 */
2839 @Deprecated
2840 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2841 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2842 /**
markchienf47d8342020-03-19 13:37:43 +08002843 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002844 * {@hide}
2845 */
markchien0f45bb92019-01-16 17:44:13 +08002846 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002847 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002848 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002849 /**
2850 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2851 * {@hide}
2852 */
2853 @Deprecated
2854 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2855 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2856 /**
2857 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2858 * {@hide}
2859 */
markchien0f45bb92019-01-16 17:44:13 +08002860 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002861 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002862 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002863
2864 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002865 * Get a more detailed error code after a Tethering or Untethering
2866 * request asynchronously failed.
2867 *
2868 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002869 * @return error The error code of the last error tethering or untethering the named
2870 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002871 *
markchien6ae63e52020-01-21 13:11:06 +08002872 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002873 * {@hide}
2874 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002875 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002876 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002877 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002878 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002879 int error = mTetheringManager.getLastTetherError(iface);
2880 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2881 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2882 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2883 // instead.
2884 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2885 }
2886 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002887 }
2888
markchienbf5ab012019-03-06 16:25:00 +08002889 /** @hide */
2890 @Retention(RetentionPolicy.SOURCE)
2891 @IntDef(value = {
2892 TETHER_ERROR_NO_ERROR,
2893 TETHER_ERROR_PROVISION_FAILED,
2894 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2895 })
2896 public @interface EntitlementResultCode {
2897 }
2898
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002899 /**
markchienbf5ab012019-03-06 16:25:00 +08002900 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002901 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002902 *
2903 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002904 * @hide
2905 */
2906 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002907 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002908 public interface OnTetheringEntitlementResultListener {
2909 /**
2910 * Called to notify entitlement result.
2911 *
2912 * @param resultCode an int value of entitlement result. It may be one of
2913 * {@link #TETHER_ERROR_NO_ERROR},
2914 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2915 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2916 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002917 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002918 }
2919
2920 /**
markchien0f45bb92019-01-16 17:44:13 +08002921 * Get the last value of the entitlement check on this downstream. If the cached value is
2922 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2923 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2924 * guaranteed that the UI-based entitlement check will complete in any specific time period
2925 * and may in fact never complete. Any successful entitlement check the platform performs for
2926 * any reason will update the cached value.
2927 *
2928 * @param type the downstream type of tethering. Must be one of
2929 * {@link #TETHERING_WIFI},
2930 * {@link #TETHERING_USB}, or
2931 * {@link #TETHERING_BLUETOOTH}.
2932 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002933 * @param executor the executor on which callback will be invoked.
2934 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2935 * notify the caller of the result of entitlement check. The listener may be called zero
2936 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002937 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002938 * {@hide}
2939 */
2940 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002941 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002942 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002943 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2944 @NonNull @CallbackExecutor Executor executor,
2945 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002946 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchienbf5ab012019-03-06 16:25:00 +08002947 ResultReceiver wrappedListener = new ResultReceiver(null) {
2948 @Override
2949 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08002950 final long token = Binder.clearCallingIdentity();
2951 try {
2952 executor.execute(() -> {
2953 listener.onTetheringEntitlementResult(resultCode);
2954 });
2955 } finally {
2956 Binder.restoreCallingIdentity(token);
2957 }
markchienbf5ab012019-03-06 16:25:00 +08002958 }
2959 };
2960
Amos Bianchia9b415a2020-03-04 11:07:38 -08002961 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002962 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002963 }
2964
2965 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002966 * Report network connectivity status. This is currently used only
2967 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002968 * <p>This method requires the caller to hold the permission
2969 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002970 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002971 * @param networkType The type of network you want to report on
2972 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002973 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002974 * {@hide}
2975 */
2976 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002977 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002978 try {
2979 mService.reportInetCondition(networkType, percentage);
2980 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002981 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002982 }
2983 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002984
2985 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002986 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07002987 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002988 * the framework to re-evaluate network connectivity and/or switch to another
2989 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002990 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002991 * @param network The {@link Network} the application was attempting to use
2992 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04002993 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2994 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002995 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002996 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09002997 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002998 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002999 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003000 // One of these will be ignored because it matches system's current state.
3001 // The other will trigger the necessary reevaluation.
3002 mService.reportNetworkConnectivity(network, true);
3003 mService.reportNetworkConnectivity(network, false);
3004 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003005 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003006 }
3007 }
3008
3009 /**
3010 * Report to the framework whether a network has working connectivity.
3011 * This provides a hint to the system that a particular network is providing
3012 * working connectivity or not. In response the framework may re-evaluate
3013 * the network's connectivity and might take further action thereafter.
3014 *
3015 * @param network The {@link Network} the application was attempting to use
3016 * or {@code null} to indicate the current default network.
3017 * @param hasConnectivity {@code true} if the application was able to successfully access the
3018 * Internet using {@code network} or {@code false} if not.
3019 */
Chalard Jean158702d2019-01-07 19:26:34 +09003020 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003021 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003022 try {
3023 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003024 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003025 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003026 }
3027 }
3028
3029 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003030 * Set a network-independent global http proxy. This is not normally what you want
3031 * for typical HTTP proxies - they are general network dependent. However if you're
3032 * doing something unusual like general internal filtering this may be useful. On
3033 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003034 *
3035 * @param p A {@link ProxyInfo} object defining the new global
3036 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003037 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003038 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003039 @SystemApi(client = MODULE_LIBRARIES)
paulhu8e96a752019-08-12 16:25:11 +08003040 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang4d513572021-03-18 09:44:34 +08003041 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003042 try {
3043 mService.setGlobalProxy(p);
3044 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003045 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003046 }
3047 }
3048
3049 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003050 * Retrieve any network-independent global HTTP proxy.
3051 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003052 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003053 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003054 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003055 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003056 @SystemApi(client = MODULE_LIBRARIES)
3057 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04003058 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003059 try {
3060 return mService.getGlobalProxy();
3061 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003062 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003063 }
3064 }
3065
3066 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003067 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3068 * network-specific HTTP proxy. If {@code network} is null, the
3069 * network-specific proxy returned is the proxy of the default active
3070 * network.
3071 *
3072 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3073 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3074 * or when {@code network} is {@code null},
3075 * the {@code ProxyInfo} for the default active network. Returns
3076 * {@code null} when no proxy applies or the caller doesn't have
3077 * permission to use {@code network}.
3078 * @hide
3079 */
3080 public ProxyInfo getProxyForNetwork(Network network) {
3081 try {
3082 return mService.getProxyForNetwork(network);
3083 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003084 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003085 }
3086 }
3087
3088 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003089 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3090 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003091 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003092 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003093 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003094 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003095 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003096 */
Chalard Jean158702d2019-01-07 19:26:34 +09003097 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003098 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003099 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003100 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003101
3102 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003103 * Returns true if the hardware supports the given network type
3104 * else it returns false. This doesn't indicate we have coverage
3105 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003106 * hardware supports it. For example a GSM phone without a SIM
3107 * should still return {@code true} for mobile data, but a wifi only
3108 * tablet would return {@code false}.
3109 *
3110 * @param networkType The network type we'd like to check
3111 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003112 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003113 * @hide
3114 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003115 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003116 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003117 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003118 public boolean isNetworkSupported(int networkType) {
3119 try {
3120 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003121 } catch (RemoteException e) {
3122 throw e.rethrowFromSystemServer();
3123 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003124 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003125
3126 /**
3127 * Returns if the currently active data network is metered. A network is
3128 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003129 * that connection due to monetary costs, data limitations or
3130 * battery/performance issues. You should check this before doing large
3131 * data transfers, and warn the user or delay the operation until another
3132 * network is available.
3133 *
3134 * @return {@code true} if large transfers should be avoided, otherwise
3135 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003136 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003137 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003138 public boolean isActiveNetworkMetered() {
3139 try {
3140 return mService.isActiveNetworkMetered();
3141 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003142 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003143 }
3144 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003145
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003146 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003147 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003148 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003149 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003150 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003151 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003152 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003153 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003154 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003155 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003156 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003157 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003158 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003159 }
3160 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003161
3162 /**
3163 * Set the value for enabling/disabling airplane mode
3164 *
3165 * @param enable whether to enable airplane mode or not
3166 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003167 * @hide
3168 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003169 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003170 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003171 android.Manifest.permission.NETWORK_SETTINGS,
3172 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3173 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003174 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003175 public void setAirplaneMode(boolean enable) {
3176 try {
3177 mService.setAirplaneMode(enable);
3178 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003179 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003180 }
3181 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003182
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003183 /**
3184 * Registers the specified {@link NetworkProvider}.
3185 * Each listener must only be registered once. The listener can be unregistered with
3186 * {@link #unregisterNetworkProvider}.
3187 *
3188 * @param provider the provider to register
3189 * @return the ID of the provider. This ID must be used by the provider when registering
3190 * {@link android.net.NetworkAgent}s.
3191 * @hide
3192 */
3193 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003194 @RequiresPermission(anyOf = {
3195 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3196 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003197 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3198 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003199 throw new IllegalStateException("NetworkProviders can only be registered once");
3200 }
3201
3202 try {
3203 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3204 provider.getName());
3205 provider.setProviderId(providerId);
3206 } catch (RemoteException e) {
3207 throw e.rethrowFromSystemServer();
3208 }
3209 return provider.getProviderId();
3210 }
3211
3212 /**
3213 * Unregisters the specified NetworkProvider.
3214 *
3215 * @param provider the provider to unregister
3216 * @hide
3217 */
3218 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003219 @RequiresPermission(anyOf = {
3220 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3221 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003222 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3223 try {
3224 mService.unregisterNetworkProvider(provider.getMessenger());
3225 } catch (RemoteException e) {
3226 throw e.rethrowFromSystemServer();
3227 }
3228 provider.setProviderId(NetworkProvider.ID_NONE);
3229 }
3230
3231
3232 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003233 @RequiresPermission(anyOf = {
3234 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3235 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003236 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3237 try {
3238 mService.declareNetworkRequestUnfulfillable(request);
3239 } catch (RemoteException e) {
3240 throw e.rethrowFromSystemServer();
3241 }
3242 }
3243
Paul Jensen1f567382015-02-13 14:18:39 -05003244 /**
3245 * @hide
3246 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003247 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003248 */
paulhub6ba8e82020-03-04 09:43:41 +08003249 @RequiresPermission(anyOf = {
3250 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3251 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003252 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jean28018572020-12-21 18:36:52 +09003253 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3254 int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003255 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003256 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003257 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003258 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003259 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003260 }
3261
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003262 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003263 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3264 * changes. Should be extended by applications wanting notifications.
3265 *
3266 * A {@code NetworkCallback} is registered by calling
3267 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3268 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003269 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003270 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3271 * A {@code NetworkCallback} should be registered at most once at any time.
3272 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003273 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003274 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003275 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003276 * No flags associated with this callback.
3277 * @hide
3278 */
3279 public static final int FLAG_NONE = 0;
3280 /**
3281 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3282 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3283 * <p>
3284 * These include:
3285 * <li> Some transport info instances (retrieved via
3286 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3287 * contain location sensitive information.
3288 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3289 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3290 * </p>
3291 * <p>
3292 * Note:
3293 * <li> Retrieving this location sensitive information (subject to app's location
3294 * permissions) will be noted by system. </li>
3295 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3296 * not include location sensitive info.
3297 * </p>
3298 */
3299 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3300
3301 /** @hide */
3302 @Retention(RetentionPolicy.SOURCE)
3303 @IntDef(flag = true, prefix = "FLAG_", value = {
3304 FLAG_NONE,
3305 FLAG_INCLUDE_LOCATION_INFO
3306 })
3307 public @interface Flag { }
3308
3309 /**
3310 * All the valid flags for error checking.
3311 */
3312 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3313
3314 public NetworkCallback() {
3315 this(FLAG_NONE);
3316 }
3317
3318 public NetworkCallback(@Flag int flags) {
3319 Preconditions.checkArgument((flags & VALID_FLAGS) == flags);
3320 mFlags = flags;
3321 }
3322
3323 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003324 * Called when the framework connects to a new network to evaluate whether it satisfies this
3325 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3326 * callback. There is no guarantee that this new network will satisfy any requests, or that
3327 * the network will stay connected for longer than the time necessary to evaluate it.
3328 * <p>
3329 * Most applications <b>should not</b> act on this callback, and should instead use
3330 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3331 * the framework in properly evaluating the network &mdash; for example, an application that
3332 * can automatically log in to a captive portal without user intervention.
3333 *
3334 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003335 *
3336 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003337 */
paulhu1a407652019-03-22 16:35:06 +08003338 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003339
3340 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003341 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003342 * This callback may be called more than once if the {@link Network} that is
3343 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003344 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003345 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003346 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3347 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003348 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003349 * @hide
3350 */
paulhu1a407652019-03-22 16:35:06 +08003351 public void onAvailable(@NonNull Network network,
3352 @NonNull NetworkCapabilities networkCapabilities,
3353 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003354 // Internally only this method is called when a new network is available, and
3355 // it calls the callback in the same way and order that older versions used
3356 // to call so as not to change the behavior.
3357 onAvailable(network);
3358 if (!networkCapabilities.hasCapability(
3359 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3360 onNetworkSuspended(network);
3361 }
3362 onCapabilitiesChanged(network, networkCapabilities);
3363 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003364 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003365 }
3366
3367 /**
3368 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003369 *
3370 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3371 * be available at the same time, and onAvailable will be called for each of these as they
3372 * appear.
3373 *
3374 * <p>For callbacks registered with {@link #requestNetwork} and
3375 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3376 * is the new best network for this request and is now tracked by this callback ; this
3377 * callback will no longer receive method calls about other networks that may have been
3378 * passed to this method previously. The previously-best network may have disconnected, or
3379 * it may still be around and the newly-best network may simply be better.
3380 *
3381 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3382 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3383 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3384 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3385 *
3386 * <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 (there is no guarantee the objects
3389 * returned by these methods will be current). Instead, wait for a call to
3390 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3391 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3392 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003393 *
3394 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003395 */
paulhu1a407652019-03-22 16:35:06 +08003396 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003397
3398 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003399 * Called when the network is about to be lost, typically because there are no outstanding
3400 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3401 * with the new replacement network for graceful handover. This method is not guaranteed
3402 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3403 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003404 *
Chalard Jean01378b62019-08-30 16:27:28 +09003405 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3406 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3407 * this callback as this is prone to race conditions ; calling these methods while in a
3408 * callback may return an outdated or even a null object.
3409 *
3410 * @param network The {@link Network} that is about to be lost.
3411 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3412 * connected for graceful handover; note that the network may still
3413 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003414 */
paulhu1a407652019-03-22 16:35:06 +08003415 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003416
3417 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003418 * Called when a network disconnects or otherwise no longer satisfies this request or
3419 * callback.
3420 *
3421 * <p>If the callback was registered with requestNetwork() or
3422 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3423 * returned by onAvailable() when that network is lost and no other network satisfies
3424 * the criteria of the request.
3425 *
3426 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3427 * each network which no longer satisfies the criteria of the callback.
3428 *
3429 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3430 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3431 * this callback as this is prone to race conditions ; calling these methods while in a
3432 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003433 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003434 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003435 */
paulhu1a407652019-03-22 16:35:06 +08003436 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003437
3438 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003439 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003440 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3441 * requested network request cannot be fulfilled (whether or not a timeout was
3442 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003443 * {@link NetworkRequest} will have already been removed and released, as if
3444 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003445 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003446 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003447
3448 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003449 * Called when the network corresponding to this request changes capabilities but still
3450 * satisfies the requested criteria.
3451 *
3452 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3453 * to be called immediately after {@link #onAvailable}.
3454 *
3455 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3456 * ConnectivityManager methods in this callback as this is prone to race conditions :
3457 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003458 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003459 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius951c0032020-12-22 15:10:42 -08003460 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003461 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003462 */
paulhu1a407652019-03-22 16:35:06 +08003463 public void onCapabilitiesChanged(@NonNull Network network,
3464 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003465
3466 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003467 * Called when the network corresponding to this request changes {@link LinkProperties}.
3468 *
3469 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3470 * to be called immediately after {@link #onAvailable}.
3471 *
3472 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3473 * ConnectivityManager methods in this callback as this is prone to race conditions :
3474 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003475 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003476 * @param network The {@link Network} whose link properties have changed.
3477 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003478 */
paulhu1a407652019-03-22 16:35:06 +08003479 public void onLinkPropertiesChanged(@NonNull Network network,
3480 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003481
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003482 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003483 * Called when the network the framework connected to for this request suspends data
3484 * transmission temporarily.
3485 *
3486 * <p>This generally means that while the TCP connections are still live temporarily
3487 * network data fails to transfer. To give a specific example, this is used on cellular
3488 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3489 * means read operations on sockets on this network will block once the buffers are
3490 * drained, and write operations will block once the buffers are full.
3491 *
3492 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3493 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3494 * this callback as this is prone to race conditions (there is no guarantee the objects
3495 * returned by these methods will be current).
3496 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003497 * @hide
3498 */
paulhu1a407652019-03-22 16:35:06 +08003499 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003500
3501 /**
3502 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003503 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3504 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003505
3506 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3507 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3508 * this callback as this is prone to race conditions : calling these methods while in a
3509 * callback may return an outdated or even a null object.
3510 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003511 * @hide
3512 */
paulhu1a407652019-03-22 16:35:06 +08003513 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003514
junyulaif2c67e42018-08-07 19:50:45 +08003515 /**
3516 * Called when access to the specified network is blocked or unblocked.
3517 *
Chalard Jean01378b62019-08-30 16:27:28 +09003518 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3519 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3520 * this callback as this is prone to race conditions : calling these methods while in a
3521 * callback may return an outdated or even a null object.
3522 *
junyulaif2c67e42018-08-07 19:50:45 +08003523 * @param network The {@link Network} whose blocked status has changed.
3524 * @param blocked The blocked status of this {@link Network}.
3525 */
junyulai7e06ad42019-03-04 22:45:36 +08003526 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003527
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003528 private NetworkRequest networkRequest;
Roshan Pius951c0032020-12-22 15:10:42 -08003529 private final int mFlags;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003530 }
3531
Hugo Benichia590ab82017-05-11 13:16:17 +09003532 /**
3533 * Constant error codes used by ConnectivityService to communicate about failures and errors
3534 * across a Binder boundary.
3535 * @hide
3536 */
3537 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003538 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003539 }
3540
3541 /** @hide */
3542 public static class TooManyRequestsException extends RuntimeException {}
3543
3544 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3545 switch (e.errorCode) {
3546 case Errors.TOO_MANY_REQUESTS:
3547 return new TooManyRequestsException();
3548 default:
3549 Log.w(TAG, "Unknown service error code " + e.errorCode);
3550 return new RuntimeException(e);
3551 }
3552 }
3553
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003554 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003555 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003556 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003557 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003558 /** @hide arg1 = TTL */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003559 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003560 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003561 public static final int CALLBACK_LOST = 4;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003562 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003563 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003564 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003565 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003566 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003567 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003568 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003569 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003570 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003571 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003572 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003573 public static final int CALLBACK_RESUMED = 10;
junyulaif2c67e42018-08-07 19:50:45 +08003574 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003575 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003576
Erik Kline155a59a2015-11-25 12:49:38 +09003577 /** @hide */
3578 public static String getCallbackName(int whichCallback) {
3579 switch (whichCallback) {
3580 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3581 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3582 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3583 case CALLBACK_LOST: return "CALLBACK_LOST";
3584 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3585 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3586 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003587 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3588 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3589 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003590 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003591 default:
3592 return Integer.toString(whichCallback);
3593 }
3594 }
3595
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003596 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003597 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003598 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003599
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003600 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003601 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003602 }
3603
Hugo Benichifd44e912017-02-02 17:02:36 +09003604 CallbackHandler(Handler handler) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00003605 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003606 }
3607
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003608 @Override
3609 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003610 if (message.what == EXPIRE_LEGACY_REQUEST) {
3611 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3612 return;
3613 }
3614
3615 final NetworkRequest request = getObject(message, NetworkRequest.class);
3616 final Network network = getObject(message, Network.class);
3617 final NetworkCallback callback;
3618 synchronized (sCallbacks) {
3619 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003620 if (callback == null) {
3621 Log.w(TAG,
3622 "callback not found for " + getCallbackName(message.what) + " message");
3623 return;
3624 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003625 if (message.what == CALLBACK_UNAVAIL) {
3626 sCallbacks.remove(request);
3627 callback.networkRequest = ALREADY_UNREGISTERED;
3628 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003629 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003630 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003631 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003632 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003633
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003634 switch (message.what) {
3635 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003636 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003637 break;
3638 }
3639 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003640 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3641 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003642 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003643 break;
3644 }
3645 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003646 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003647 break;
3648 }
3649 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003650 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003651 break;
3652 }
3653 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003654 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003655 break;
3656 }
3657 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003658 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3659 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003660 break;
3661 }
3662 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003663 LinkProperties lp = getObject(message, LinkProperties.class);
3664 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003665 break;
3666 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003667 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003668 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003669 break;
3670 }
3671 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003672 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003673 break;
3674 }
junyulaif2c67e42018-08-07 19:50:45 +08003675 case CALLBACK_BLK_CHANGED: {
3676 boolean blocked = message.arg1 != 0;
3677 callback.onBlockedStatusChanged(network, blocked);
3678 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003679 }
3680 }
3681
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003682 private <T> T getObject(Message msg, Class<T> c) {
3683 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003684 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003685 }
3686
Hugo Benichifd44e912017-02-02 17:02:36 +09003687 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003688 synchronized (sCallbacks) {
3689 if (sCallbackHandler == null) {
3690 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003691 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003692 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003693 }
3694 }
3695
Hugo Benichibc4ac972017-02-03 14:18:44 +09003696 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3697 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003698
Hugo Benichibc4ac972017-02-03 14:18:44 +09003699 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003700 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003701 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003702 checkCallbackNotNull(callback);
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00003703 Preconditions.checkArgument(
3704 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3705 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003706 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003707 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003708 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003709 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003710 if (callback.networkRequest != null
3711 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003712 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3713 // and requests (http://b/20701525).
3714 Log.e(TAG, "NetworkCallback was already registered");
3715 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003716 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003717 Binder binder = new Binder();
Roshan Pius951c0032020-12-22 15:10:42 -08003718 final int callbackFlags = callback.mFlags;
junyulaiad010792021-01-11 16:53:38 +08003719 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003720 request = mService.listenForNetwork(
Roshan Pius951c0032020-12-22 15:10:42 -08003721 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003722 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003723 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003724 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003725 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
Roshan Pius951c0032020-12-22 15:10:42 -08003726 callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003727 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003728 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003729 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003730 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003731 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003732 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003733 } catch (RemoteException e) {
3734 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003735 } catch (ServiceSpecificException e) {
3736 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003737 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003738 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003739 }
3740
3741 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003742 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003743 *
markchienfac84a22020-03-18 21:16:15 +08003744 * This API is only for use in internal system code that requests networks with legacy type and
3745 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003746 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003747 *
markchiend6eeffd2020-01-14 00:55:21 +08003748 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003749 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3750 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3751 * be a positive value (i.e. >0).
3752 * @param legacyType to specify the network type(#TYPE_*).
3753 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003754 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3755 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003756 *
3757 * @hide
3758 */
markchiend6eeffd2020-01-14 00:55:21 +08003759 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003760 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003761 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003762 int timeoutMs, int legacyType, @NonNull Handler handler,
3763 @NonNull NetworkCallback networkCallback) {
3764 if (legacyType == TYPE_NONE) {
3765 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3766 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003767 CallbackHandler cbHandler = new CallbackHandler(handler);
3768 NetworkCapabilities nc = request.networkCapabilities;
3769 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003770 }
3771
3772 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003773 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003774 *
Chalard Jean01378b62019-08-30 16:27:28 +09003775 * <p>This method will attempt to find the best network that matches the passed
3776 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3777 * criteria. The platform will evaluate which network is the best at its own discretion.
3778 * Throughput, latency, cost per byte, policy, user preference and other considerations
3779 * may be factored in the decision of what is considered the best network.
3780 *
3781 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3782 * matching this request, while always attempting to match the request to a better network if
3783 * possible. If a better match is found, the platform will switch this request to the now-best
3784 * network and inform the app of the newly best network by invoking
3785 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3786 * will not try to maintain any other network than the best one currently matching the request:
3787 * a network not matching any network request may be disconnected at any time.
3788 *
3789 * <p>For example, an application could use this method to obtain a connected cellular network
3790 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3791 * radio to consume additional power. Or, an application could inform the system that it wants
3792 * a network supporting sending MMSes and have the system let it know about the currently best
3793 * MMS-supporting network through the provided {@link NetworkCallback}.
3794 *
3795 * <p>The status of the request can be followed by listening to the various callbacks described
3796 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3797 * used to direct traffic to the network (although accessing some networks may be subject to
3798 * holding specific permissions). Callers will learn about the specific characteristics of the
3799 * network through
3800 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3801 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3802 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3803 * matching the request at any given time; therefore when a better network matching the request
3804 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3805 * with the new network after which no further updates are given about the previously-best
3806 * network, unless it becomes the best again at some later time. All callbacks are invoked
3807 * in order on the same thread, which by default is a thread created by the framework running
3808 * in the app.
3809 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3810 * callbacks are invoked.
3811 *
3812 * <p>This{@link NetworkRequest} will live until released via
3813 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3814 * which point the system may let go of the network at any time.
3815 *
3816 * <p>A version of this method which takes a timeout is
3817 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3818 * wait for a limited amount of time for the network to become unavailable.
3819 *
Paul Jensenee52d232015-06-16 15:11:58 -04003820 * <p>It is presently unsupported to request a network with mutable
3821 * {@link NetworkCapabilities} such as
3822 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3823 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3824 * as these {@code NetworkCapabilities} represent states that a particular
3825 * network may never attain, and whether a network will attain these states
3826 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003827 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003828 *
3829 * <p>This method requires the caller to hold either the
3830 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3831 * or the ability to modify system settings as determined by
3832 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003833 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003834 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3835 * number of outstanding requests to 100 per app (identified by their UID), shared with
3836 * all variants of this method, of {@link #registerNetworkCallback} as well as
3837 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3838 * Requesting a network with this method will count toward this limit. If this limit is
3839 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3840 * make sure to unregister the callbacks with
3841 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3842 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003843 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003844 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3845 * the callback must not be shared - it uniquely specifies this request.
3846 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003847 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3848 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003849 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003850 */
Chalard Jean158702d2019-01-07 19:26:34 +09003851 public void requestNetwork(@NonNull NetworkRequest request,
3852 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003853 requestNetwork(request, networkCallback, getDefaultHandler());
3854 }
3855
3856 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003857 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichifd44e912017-02-02 17:02:36 +09003858 *
Chalard Jean01378b62019-08-30 16:27:28 +09003859 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3860 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003861 *
Chalard Jean01378b62019-08-30 16:27:28 +09003862 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003863 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3864 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003865 *
3866 * @param request {@link NetworkRequest} describing this request.
3867 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3868 * the callback must not be shared - it uniquely specifies this request.
3869 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003870 */
Chalard Jean158702d2019-01-07 19:26:34 +09003871 public void requestNetwork(@NonNull NetworkRequest request,
3872 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003873 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003874 NetworkCapabilities nc = request.networkCapabilities;
3875 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003876 }
3877
3878 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003879 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohenf67bde92017-03-01 12:47:28 -08003880 * by a timeout.
3881 *
3882 * This function behaves identically to the non-timed-out version
3883 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3884 * is not found within the given time (in milliseconds) the
3885 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3886 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3887 * not have to be released if timed-out (it is automatically released). Unregistering a
3888 * request that timed out is not an error.
3889 *
3890 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3891 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3892 * for that purpose. Calling this method will attempt to bring up the requested network.
3893 *
Chalard Jean01378b62019-08-30 16:27:28 +09003894 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003895 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3896 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003897 *
3898 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003899 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3900 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003901 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3902 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3903 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003904 */
Chalard Jean158702d2019-01-07 19:26:34 +09003905 public void requestNetwork(@NonNull NetworkRequest request,
3906 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003907 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003908 NetworkCapabilities nc = request.networkCapabilities;
3909 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3910 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003911 }
3912
Hugo Benichifd44e912017-02-02 17:02:36 +09003913 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003914 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichifd44e912017-02-02 17:02:36 +09003915 * by a timeout.
3916 *
Chalard Jean01378b62019-08-30 16:27:28 +09003917 * This method behaves identically to
3918 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3919 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003920 *
Chalard Jean01378b62019-08-30 16:27:28 +09003921 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003922 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3923 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003924 *
3925 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003926 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3927 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003928 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003929 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3930 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003931 */
Chalard Jean158702d2019-01-07 19:26:34 +09003932 public void requestNetwork(@NonNull NetworkRequest request,
3933 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003934 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003935 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003936 NetworkCapabilities nc = request.networkCapabilities;
3937 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003938 }
3939
3940 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003941 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003942 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003943 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003944 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003945 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3946 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003947 */
Erik Kline8a826212014-11-19 12:12:24 +09003948 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003949
3950 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003951 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003952 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003953 * {@link android.content.Intent#getParcelableExtra(String)}.
3954 */
Erik Kline8a826212014-11-19 12:12:24 +09003955 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003956
3957
3958 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003959 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003960 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003961 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003962 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003963 * the request may outlive the calling application and get called back when a suitable
3964 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003965 * <p>
3966 * The operation is an Intent broadcast that goes to a broadcast receiver that
3967 * you registered with {@link Context#registerReceiver} or through the
3968 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3969 * <p>
3970 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003971 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3972 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003973 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003974 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003975 * Intent to reserve the network or it will be released shortly after the Intent
3976 * is processed.
3977 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003978 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003979 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003980 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003981 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003982 * The request may be released normally by calling
3983 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003984 * <p>It is presently unsupported to request a network with either
3985 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3986 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3987 * as these {@code NetworkCapabilities} represent states that a particular
3988 * network may never attain, and whether a network will attain these states
3989 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003990 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003991 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003992 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3993 * number of outstanding requests to 100 per app (identified by their UID), shared with
3994 * all variants of this method, of {@link #registerNetworkCallback} as well as
3995 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3996 * Requesting a network with this method will count toward this limit. If this limit is
3997 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3998 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3999 * or {@link #releaseNetworkRequest(PendingIntent)}.
4000 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004001 * <p>This method requires the caller to hold either the
4002 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4003 * or the ability to modify system settings as determined by
4004 * {@link android.provider.Settings.System#canWrite}.</p>
4005 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004006 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004007 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004008 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004009 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004010 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4011 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004012 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004013 */
Chalard Jean158702d2019-01-07 19:26:34 +09004014 public void requestNetwork(@NonNull NetworkRequest request,
4015 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004016 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004017 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004018 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004019 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004020 request.networkCapabilities, operation, mContext.getOpPackageName(),
4021 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004022 } catch (RemoteException e) {
4023 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004024 } catch (ServiceSpecificException e) {
4025 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004026 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004027 }
4028
4029 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004030 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4031 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004032 * This method has the same behavior as
4033 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004034 * releasing network resources and disconnecting.
4035 *
4036 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4037 * PendingIntent passed to
4038 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4039 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4040 */
Chalard Jean158702d2019-01-07 19:26:34 +09004041 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004042 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004043 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004044 try {
4045 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004046 } catch (RemoteException e) {
4047 throw e.rethrowFromSystemServer();
4048 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004049 }
4050
Hugo Benichibc1104b2017-05-09 15:19:01 +09004051 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004052 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004053 }
4054
4055 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004056 Preconditions.checkNotNull(callback, "null NetworkCallback");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004057 }
4058
4059 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004060 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004061 }
4062
4063 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004064 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004065 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004066 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4067 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004068 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004069 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4070 * number of outstanding requests to 100 per app (identified by their UID), shared with
4071 * all variants of this method, of {@link #requestNetwork} as well as
4072 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4073 * Requesting a network with this method will count toward this limit. If this limit is
4074 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4075 * make sure to unregister the callbacks with
4076 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4077 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004078 * @param request {@link NetworkRequest} describing this request.
4079 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4080 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004081 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004082 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004083 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004084 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004085 public void registerNetworkCallback(@NonNull NetworkRequest request,
4086 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004087 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4088 }
4089
4090 /**
4091 * Registers to receive notifications about all networks which satisfy the given
4092 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004093 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4094 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004095 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004096 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4097 * number of outstanding requests to 100 per app (identified by their UID), shared with
4098 * all variants of this method, of {@link #requestNetwork} as well as
4099 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4100 * Requesting a network with this method will count toward this limit. If this limit is
4101 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4102 * make sure to unregister the callbacks with
4103 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4104 *
4105 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004106 * @param request {@link NetworkRequest} describing this request.
4107 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4108 * networks change state.
4109 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004110 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004111 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004112 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004113 public void registerNetworkCallback(@NonNull NetworkRequest request,
4114 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004115 CallbackHandler cbHandler = new CallbackHandler(handler);
4116 NetworkCapabilities nc = request.networkCapabilities;
4117 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004118 }
4119
4120 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004121 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4122 * {@link NetworkRequest}.
4123 *
4124 * This function behaves identically to the version that takes a NetworkCallback, but instead
4125 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4126 * the request may outlive the calling application and get called back when a suitable
4127 * network is found.
4128 * <p>
4129 * The operation is an Intent broadcast that goes to a broadcast receiver that
4130 * you registered with {@link Context#registerReceiver} or through the
4131 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4132 * <p>
4133 * The operation Intent is delivered with two extras, a {@link Network} typed
4134 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4135 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4136 * the original requests parameters.
4137 * <p>
4138 * If there is already a request for this Intent registered (with the equality of
4139 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4140 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4141 * <p>
4142 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004143 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004144 *
4145 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4146 * number of outstanding requests to 100 per app (identified by their UID), shared with
4147 * all variants of this method, of {@link #requestNetwork} as well as
4148 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4149 * Requesting a network with this method will count toward this limit. If this limit is
4150 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4151 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4152 * or {@link #releaseNetworkRequest(PendingIntent)}.
4153 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004154 * @param request {@link NetworkRequest} describing this request.
4155 * @param operation Action to perform when the network is available (corresponds
4156 * to the {@link NetworkCallback#onAvailable} call. Typically
4157 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004158 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004159 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004160 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004161 public void registerNetworkCallback(@NonNull NetworkRequest request,
4162 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004163 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004164 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004165 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004166 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004167 request.networkCapabilities, operation, mContext.getOpPackageName(),
4168 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004169 } catch (RemoteException e) {
4170 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004171 } catch (ServiceSpecificException e) {
4172 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004173 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004174 }
4175
4176 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004177 * Registers to receive notifications about changes in the application's default network. This
4178 * may be a physical network or a virtual network, such as a VPN that applies to the
4179 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004180 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004181 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004182 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4183 * number of outstanding requests to 100 per app (identified by their UID), shared with
4184 * all variants of this method, of {@link #requestNetwork} as well as
4185 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4186 * Requesting a network with this method will count toward this limit. If this limit is
4187 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4188 * make sure to unregister the callbacks with
4189 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4190 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004191 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004192 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004193 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004194 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004195 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004196 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004197 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004198 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4199 }
4200
4201 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004202 * Registers to receive notifications about changes in the application's default network. This
4203 * may be a physical network or a virtual network, such as a VPN that applies to the
4204 * application. The callbacks will continue to be called until either the application exits or
4205 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4206 *
4207 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4208 * number of outstanding requests to 100 per app (identified by their UID), shared with
4209 * all variants of this method, of {@link #requestNetwork} as well as
4210 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4211 * Requesting a network with this method will count toward this limit. If this limit is
4212 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4213 * make sure to unregister the callbacks with
4214 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4215 *
4216 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4217 * application's default network changes.
4218 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4219 * @throws RuntimeException if the app already has too many callbacks registered.
4220 */
4221 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4222 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4223 @NonNull Handler handler) {
4224 CallbackHandler cbHandler = new CallbackHandler(handler);
4225 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4226 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4227 }
4228
4229 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004230 * Registers to receive notifications about changes in the system default network. The callbacks
4231 * will continue to be called until either the application exits or
4232 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004233 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004234 * This method should not be used to determine networking state seen by applications, because in
4235 * many cases, most or even all application traffic may not use the default network directly,
4236 * and traffic from different applications may go on different networks by default. As an
4237 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4238 * and not onto the system default network. Applications or system components desiring to do
4239 * determine network state as seen by applications should use other methods such as
4240 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4241 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004242 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4243 * number of outstanding requests to 100 per app (identified by their UID), shared with
4244 * all variants of this method, of {@link #requestNetwork} as well as
4245 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4246 * Requesting a network with this method will count toward this limit. If this limit is
4247 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4248 * make sure to unregister the callbacks with
4249 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4250 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004251 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4252 * system default network changes.
4253 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004254 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004255 *
4256 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004257 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004258 @SystemApi(client = MODULE_LIBRARIES)
4259 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4260 @RequiresPermission(anyOf = {
4261 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4262 android.Manifest.permission.NETWORK_SETTINGS})
4263 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004264 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004265 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004266 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004267 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004268 }
4269
4270 /**
junyulai8eb13a22021-03-15 11:48:48 +08004271 * Registers to receive notifications about the best matching network which satisfy the given
4272 * {@link NetworkRequest}. The callbacks will continue to be called until
4273 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4274 * called.
4275 *
4276 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4277 * number of outstanding requests to 100 per app (identified by their UID), shared with
4278 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4279 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4280 * Requesting a network with this method will count toward this limit. If this limit is
4281 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4282 * make sure to unregister the callbacks with
4283 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4284 *
4285 *
4286 * @param request {@link NetworkRequest} describing this request.
4287 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4288 * networks change state.
4289 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4290 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai7514e312021-03-05 15:51:17 +08004291 */
junyulai7514e312021-03-05 15:51:17 +08004292 @SuppressLint("ExecutorRegistration")
4293 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4294 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4295 final NetworkCapabilities nc = request.networkCapabilities;
4296 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai1b1c8742021-03-12 20:05:08 +08004297 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai7514e312021-03-05 15:51:17 +08004298 }
4299
4300 /**
fenglub00f4882015-04-21 17:12:05 -07004301 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4302 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4303 * network connection for updated bandwidth information. The caller will be notified via
4304 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004305 * method assumes that the caller has previously called
4306 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4307 * changes.
fenglu3f357402015-03-20 11:29:56 -07004308 *
fengluea2d9282015-04-27 14:28:04 -07004309 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004310 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004311 */
Chalard Jean158702d2019-01-07 19:26:34 +09004312 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004313 try {
fenglub00f4882015-04-21 17:12:05 -07004314 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004315 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004316 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004317 }
4318 }
4319
4320 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004321 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004322 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4323 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4324 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004325 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4326 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004327 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004328 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4329 * triggering it as soon as this call returns.
4330 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004331 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004332 */
Chalard Jean158702d2019-01-07 19:26:34 +09004333 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004334 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004335 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004336 final List<NetworkRequest> reqs = new ArrayList<>();
4337 // Find all requests associated to this callback and stop callback triggers immediately.
4338 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4339 synchronized (sCallbacks) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004340 Preconditions.checkArgument(networkCallback.networkRequest != null,
4341 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004342 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4343 Log.d(TAG, "NetworkCallback was already unregistered");
4344 return;
4345 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004346 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4347 if (e.getValue() == networkCallback) {
4348 reqs.add(e.getKey());
4349 }
4350 }
4351 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4352 for (NetworkRequest r : reqs) {
4353 try {
4354 mService.releaseNetworkRequest(r);
4355 } catch (RemoteException e) {
4356 throw e.rethrowFromSystemServer();
4357 }
4358 // Only remove mapping if rpc was successful.
4359 sCallbacks.remove(r);
4360 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004361 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004362 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004363 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004364
4365 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004366 * Unregisters a callback previously registered via
4367 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4368 *
4369 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4370 * PendingIntent passed to
4371 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4372 * Cannot be null.
4373 */
Chalard Jean158702d2019-01-07 19:26:34 +09004374 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004375 releaseNetworkRequest(operation);
4376 }
4377
4378 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004379 * Informs the system whether it should switch to {@code network} regardless of whether it is
4380 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4381 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4382 * the system default network regardless of any other network that's currently connected. If
4383 * {@code always} is true, then the choice is remembered, so that the next time the user
4384 * connects to this network, the system will switch to it.
4385 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004386 * @param network The network to accept.
4387 * @param accept Whether to accept the network even if unvalidated.
4388 * @param always Whether to remember this choice in the future.
4389 *
4390 * @hide
4391 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004392 @SystemApi(client = MODULE_LIBRARIES)
4393 @RequiresPermission(anyOf = {
4394 android.Manifest.permission.NETWORK_SETTINGS,
4395 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4396 android.Manifest.permission.NETWORK_STACK,
4397 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4398 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004399 try {
4400 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004401 } catch (RemoteException e) {
4402 throw e.rethrowFromSystemServer();
4403 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004404 }
4405
4406 /**
lucaslin2240ef62019-03-12 13:08:03 +08004407 * Informs the system whether it should consider the network as validated even if it only has
4408 * partial connectivity. If {@code accept} is true, then the network will be considered as
4409 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4410 * is remembered, so that the next time the user connects to this network, the system will
4411 * switch to it.
4412 *
4413 * @param network The network to accept.
4414 * @param accept Whether to consider the network as validated even if it has partial
4415 * connectivity.
4416 * @param always Whether to remember this choice in the future.
4417 *
4418 * @hide
4419 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004420 @SystemApi(client = MODULE_LIBRARIES)
4421 @RequiresPermission(anyOf = {
4422 android.Manifest.permission.NETWORK_SETTINGS,
4423 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4424 android.Manifest.permission.NETWORK_STACK,
4425 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4426 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4427 boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004428 try {
4429 mService.setAcceptPartialConnectivity(network, accept, always);
4430 } catch (RemoteException e) {
4431 throw e.rethrowFromSystemServer();
4432 }
4433 }
4434
4435 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004436 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4437 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4438 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4439 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4440 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004441 * @param network The network to accept.
4442 *
4443 * @hide
4444 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004445 @SystemApi(client = MODULE_LIBRARIES)
4446 @RequiresPermission(anyOf = {
4447 android.Manifest.permission.NETWORK_SETTINGS,
4448 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4449 android.Manifest.permission.NETWORK_STACK,
4450 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4451 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004452 try {
4453 mService.setAvoidUnvalidated(network);
4454 } catch (RemoteException e) {
4455 throw e.rethrowFromSystemServer();
4456 }
4457 }
4458
4459 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004460 * Requests that the system open the captive portal app on the specified network.
4461 *
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004462 * <p>This is to be used on networks where a captive portal was detected, as per
4463 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4464 *
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004465 * @param network The network to log into.
4466 *
4467 * @hide
4468 */
Remi NGUYEN VAN4cf96ab2021-03-16 18:06:06 +09004469 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4470 @RequiresPermission(anyOf = {
4471 android.Manifest.permission.NETWORK_SETTINGS,
4472 android.Manifest.permission.NETWORK_STACK,
4473 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4474 })
4475 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004476 try {
4477 mService.startCaptivePortalApp(network);
4478 } catch (RemoteException e) {
4479 throw e.rethrowFromSystemServer();
4480 }
4481 }
4482
4483 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004484 * Requests that the system open the captive portal app with the specified extras.
4485 *
4486 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4487 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004488 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004489 * @param appExtras Extras to include in the app start intent.
4490 * @hide
4491 */
4492 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004493 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004494 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004495 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004496 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004497 } catch (RemoteException e) {
4498 throw e.rethrowFromSystemServer();
4499 }
4500 }
4501
4502 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004503 * Determine whether the device is configured to avoid bad wifi.
4504 * @hide
4505 */
4506 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004507 @RequiresPermission(anyOf = {
4508 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4509 android.Manifest.permission.NETWORK_STACK})
4510 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004511 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004512 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004513 } catch (RemoteException e) {
4514 throw e.rethrowFromSystemServer();
4515 }
4516 }
4517
4518 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004519 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4520 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004521 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4522 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004523 *
4524 * An example of such an operation might be a time-sensitive foreground activity, such as a
4525 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4526 */
4527 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4528
4529 /**
4530 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4531 * a backup channel for traffic that is primarily going over another network.
4532 *
4533 * An example might be maintaining backup connections to peers or servers for the purpose of
4534 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4535 * on backup paths should be negligible compared to the traffic on the main path.
4536 */
4537 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4538
4539 /**
4540 * It is acceptable to use metered data to improve network latency and performance.
4541 */
4542 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4543
4544 /**
4545 * Return value to use for unmetered networks. On such networks we currently set all the flags
4546 * to true.
4547 * @hide
4548 */
4549 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4550 MULTIPATH_PREFERENCE_HANDOVER |
4551 MULTIPATH_PREFERENCE_RELIABILITY |
4552 MULTIPATH_PREFERENCE_PERFORMANCE;
4553
4554 /** @hide */
4555 @Retention(RetentionPolicy.SOURCE)
4556 @IntDef(flag = true, value = {
4557 MULTIPATH_PREFERENCE_HANDOVER,
4558 MULTIPATH_PREFERENCE_RELIABILITY,
4559 MULTIPATH_PREFERENCE_PERFORMANCE,
4560 })
4561 public @interface MultipathPreference {
4562 }
4563
4564 /**
4565 * Provides a hint to the calling application on whether it is desirable to use the
4566 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4567 * for multipath data transfer on this network when it is not the system default network.
4568 * Applications desiring to use multipath network protocols should call this method before
4569 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004570 *
4571 * @param network The network on which the application desires to use multipath data.
4572 * If {@code null}, this method will return the a preference that will generally
4573 * apply to metered networks.
4574 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4575 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004576 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004577 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004578 try {
4579 return mService.getMultipathPreference(network);
4580 } catch (RemoteException e) {
4581 throw e.rethrowFromSystemServer();
4582 }
4583 }
4584
4585 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004586 * Resets all connectivity manager settings back to factory defaults.
4587 * @hide
4588 */
Chiachang Wang4d513572021-03-18 09:44:34 +08004589 @SystemApi(client = MODULE_LIBRARIES)
4590 @RequiresPermission(anyOf = {
4591 android.Manifest.permission.NETWORK_SETTINGS,
4592 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scott0f835ac2015-03-30 13:17:11 -07004593 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004594 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004595 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004596 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004597 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004598 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004599 }
4600 }
4601
4602 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004603 * Binds the current process to {@code network}. All Sockets created in the future
4604 * (and not explicitly bound via a bound SocketFactory from
4605 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4606 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4607 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4608 * work and all host name resolutions will fail. This is by design so an application doesn't
4609 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4610 * To clear binding pass {@code null} for {@code network}. Using individually bound
4611 * Sockets created by Network.getSocketFactory().createSocket() and
4612 * performing network-specific host name resolutions via
4613 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004614 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004615 *
4616 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4617 * the current binding.
4618 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4619 */
Chalard Jean158702d2019-01-07 19:26:34 +09004620 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004621 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004622 // instantiated.
4623 return setProcessDefaultNetwork(network);
4624 }
4625
4626 /**
4627 * Binds the current process to {@code network}. All Sockets created in the future
4628 * (and not explicitly bound via a bound SocketFactory from
4629 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4630 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4631 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4632 * work and all host name resolutions will fail. This is by design so an application doesn't
4633 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4634 * To clear binding pass {@code null} for {@code network}. Using individually bound
4635 * Sockets created by Network.getSocketFactory().createSocket() and
4636 * performing network-specific host name resolutions via
4637 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4638 * {@code setProcessDefaultNetwork}.
4639 *
4640 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4641 * the current binding.
4642 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4643 * @deprecated This function can throw {@link IllegalStateException}. Use
4644 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4645 * is a direct replacement.
4646 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004647 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004648 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004649 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004650 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4651
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004652 if (netId != NETID_UNSET) {
4653 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004654 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004655
4656 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4657 return false;
4658 }
4659
4660 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004661 // Set HTTP proxy system properties to match network.
4662 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004663 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004664 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004665 } catch (SecurityException e) {
4666 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4667 Log.e(TAG, "Can't set proxy properties", e);
4668 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004669 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANe1b04f62021-03-18 23:27:19 +09004670 InetAddressCompat.clearDnsCache();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004671 // Must flush socket pool as idle sockets will be bound to previous network and may
4672 // cause subsequent fetches to be performed on old network.
4673 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004674 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004675
4676 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004677 }
4678
4679 /**
4680 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004681 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004682 *
4683 * @return {@code Network} to which this process is bound, or {@code null}.
4684 */
Chalard Jean158702d2019-01-07 19:26:34 +09004685 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004686 public Network getBoundNetworkForProcess() {
4687 // Forcing callers to call thru non-static function ensures ConnectivityManager
4688 // instantiated.
4689 return getProcessDefaultNetwork();
4690 }
4691
4692 /**
4693 * Returns the {@link Network} currently bound to this process via
4694 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4695 *
4696 * @return {@code Network} to which this process is bound, or {@code null}.
4697 * @deprecated Using this function can lead to other functions throwing
4698 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4699 * {@code getBoundNetworkForProcess} is a direct replacement.
4700 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004701 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004702 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004703 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004704 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004705 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004706 return new Network(netId);
4707 }
4708
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004709 private void unsupportedStartingFrom(int version) {
4710 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004711 // The getApplicationInfo() call we make below is not supported in system context. Let
4712 // the call through here, and rely on the fact that ConnectivityService will refuse to
4713 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004714 return;
4715 }
4716
4717 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4718 throw new UnsupportedOperationException(
4719 "This method is not supported in target SDK version " + version + " and above");
4720 }
4721 }
4722
4723 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4724 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004725 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004726 // remove these exemptions. Note that this check is not secure, and apps can still access these
4727 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4728 // so is unsupported and may break in the future. http://b/22728205
4729 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004730 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004731 }
4732
Paul Jensen8cdda642014-05-29 10:12:39 -04004733 /**
4734 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004735 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004736 *
4737 * @param network The {@link Network} to bind host resolutions from the current process to, or
4738 * {@code null} to clear the current binding.
4739 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4740 * @hide
4741 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4742 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004743 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004744 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004745 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004746 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004747 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004748 }
Felipe Leme30511352016-01-22 09:44:57 -08004749
4750 /**
4751 * Device is not restricting metered network activity while application is running on
4752 * background.
4753 */
4754 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4755
4756 /**
4757 * Device is restricting metered network activity while application is running on background,
4758 * but application is allowed to bypass it.
4759 * <p>
4760 * In this state, application should take action to mitigate metered network access.
4761 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4762 */
4763 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4764
4765 /**
4766 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004767 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004768 * In this state, application should not try to use the network while running on background,
4769 * because it would be denied.
4770 */
4771 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4772
Felipe Lemed34c9af2016-01-27 14:46:39 -08004773 /**
4774 * A change in the background metered network activity restriction has occurred.
4775 * <p>
4776 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4777 * applies to them.
4778 * <p>
4779 * This is only sent to registered receivers, not manifest receivers.
4780 */
4781 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4782 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4783 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4784
Felipe Leme7e4c1852016-01-25 11:48:04 -08004785 /** @hide */
4786 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004787 @IntDef(flag = false, value = {
4788 RESTRICT_BACKGROUND_STATUS_DISABLED,
4789 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4790 RESTRICT_BACKGROUND_STATUS_ENABLED,
4791 })
Felipe Leme30511352016-01-22 09:44:57 -08004792 public @interface RestrictBackgroundStatus {
4793 }
4794
Felipe Leme30511352016-01-22 09:44:57 -08004795 /**
4796 * Determines if the calling application is subject to metered network restrictions while
4797 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004798 *
4799 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4800 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4801 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004802 */
4803 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4804 try {
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004805 return mService.getRestrictBackgroundStatusByCaller();
Felipe Leme30511352016-01-22 09:44:57 -08004806 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004807 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004808 }
4809 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004810
4811 /**
4812 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004813 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4814 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004815 *
4816 * @return Hash of network watchlist config file. Null if config does not exist.
4817 */
Chalard Jean158702d2019-01-07 19:26:34 +09004818 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004819 public byte[] getNetworkWatchlistConfigHash() {
4820 try {
4821 return mService.getNetworkWatchlistConfigHash();
4822 } catch (RemoteException e) {
4823 Log.e(TAG, "Unable to get watchlist config hash");
4824 throw e.rethrowFromSystemServer();
4825 }
4826 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004827
4828 /**
4829 * Returns the {@code uid} of the owner of a network connection.
4830 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004831 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4832 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004833 * @param local The local {@link InetSocketAddress} of a connection.
4834 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004835 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004836 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4837 * android.os.Process#INVALID_UID} if the connection is not found.
4838 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4839 * user.
4840 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004841 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004842 public int getConnectionOwnerUid(
4843 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004844 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4845 try {
4846 return mService.getConnectionOwnerUid(connectionInfo);
4847 } catch (RemoteException e) {
4848 throw e.rethrowFromSystemServer();
4849 }
4850 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004851
4852 private void printStackTrace() {
4853 if (DEBUG) {
4854 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4855 final StringBuffer sb = new StringBuffer();
4856 for (int i = 3; i < callStack.length; i++) {
4857 final String stackTrace = callStack[i].toString();
4858 if (stackTrace == null || stackTrace.contains("android.os")) {
4859 break;
4860 }
4861 sb.append(" [").append(stackTrace).append("]");
4862 }
4863 Log.d(TAG, "StackLog:" + sb.toString());
4864 }
4865 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004866
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004867 /** @hide */
4868 public TestNetworkManager startOrGetTestNetworkManager() {
4869 final IBinder tnBinder;
4870 try {
4871 tnBinder = mService.startOrGetTestNetworkService();
4872 } catch (RemoteException e) {
4873 throw e.rethrowFromSystemServer();
4874 }
4875
4876 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4877 }
4878
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004879 /** @hide */
4880 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4881 return new ConnectivityDiagnosticsManager(mContext, mService);
4882 }
4883
Cody Kestingf53a0752020-04-15 12:33:28 -07004884 /**
4885 * Simulates a Data Stall for the specified Network.
4886 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004887 * <p>This method should only be used for tests.
4888 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004889 * <p>The caller must be the owner of the specified Network.
4890 *
4891 * @param detectionMethod The detection method used to identify the Data Stall.
4892 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4893 * @param network The Network for which a Data Stall is being simluated.
4894 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4895 * @throws SecurityException if the caller is not the owner of the given network.
4896 * @hide
4897 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004898 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004899 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4900 android.Manifest.permission.NETWORK_STACK})
4901 public void simulateDataStall(int detectionMethod, long timestampMillis,
4902 @NonNull Network network, @NonNull PersistableBundle extras) {
4903 try {
4904 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4905 } catch (RemoteException e) {
4906 e.rethrowFromSystemServer();
4907 }
4908 }
James Mattis356a8792020-10-28 21:48:54 -07004909
Daniel Brightf9e945b2020-06-15 16:10:01 -07004910 @NonNull
4911 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4912
4913 /**
4914 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4915 * receive available QoS events related to the {@link Network} and local ip + port
4916 * specified within socketInfo.
4917 * <p/>
4918 * The same {@link QosCallback} must be unregistered before being registered a second time,
4919 * otherwise {@link QosCallbackRegistrationException} is thrown.
4920 * <p/>
4921 * This API does not, in itself, require any permission if called with a network that is not
4922 * restricted. However, the underlying implementation currently only supports the IMS network,
4923 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4924 * useful, because they'd never be called back on networks that they would have access to.
4925 *
4926 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4927 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4928 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4929 * @throws RuntimeException if the app already has too many callbacks registered.
4930 *
4931 * Exceptions after the time of registration is passed through
4932 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4933 *
4934 * @param socketInfo the socket information used to match QoS events
4935 * @param callback receives qos events that satisfy socketInfo
4936 * @param executor The executor on which the callback will be invoked. The provided
4937 * {@link Executor} must run callback sequentially, otherwise the order of
4938 * callbacks cannot be guaranteed.
4939 *
4940 * @hide
4941 */
4942 @SystemApi
4943 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4944 @NonNull final QosCallback callback,
4945 @CallbackExecutor @NonNull final Executor executor) {
4946 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4947 Objects.requireNonNull(callback, "callback must be non-null");
4948 Objects.requireNonNull(executor, "executor must be non-null");
4949
4950 try {
4951 synchronized (mQosCallbackConnections) {
4952 if (getQosCallbackConnection(callback) == null) {
4953 final QosCallbackConnection connection =
4954 new QosCallbackConnection(this, callback, executor);
4955 mQosCallbackConnections.add(connection);
4956 mService.registerQosSocketCallback(socketInfo, connection);
4957 } else {
4958 Log.e(TAG, "registerQosCallback: Callback already registered");
4959 throw new QosCallbackRegistrationException();
4960 }
4961 }
4962 } catch (final RemoteException e) {
4963 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4964
4965 // The same unregister method method is called for consistency even though nothing
4966 // will be sent to the ConnectivityService since the callback was never successfully
4967 // registered.
4968 unregisterQosCallback(callback);
4969 e.rethrowFromSystemServer();
4970 } catch (final ServiceSpecificException e) {
4971 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4972 unregisterQosCallback(callback);
4973 throw convertServiceException(e);
4974 }
4975 }
4976
4977 /**
4978 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4979 * events once unregistered and can be registered a second time.
4980 * <p/>
4981 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4982 *
4983 * @param callback the callback being unregistered
4984 *
4985 * @hide
4986 */
4987 @SystemApi
4988 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4989 Objects.requireNonNull(callback, "The callback must be non-null");
4990 try {
4991 synchronized (mQosCallbackConnections) {
4992 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4993 if (connection != null) {
4994 connection.stopReceivingMessages();
4995 mService.unregisterQosCallback(connection);
4996 mQosCallbackConnections.remove(connection);
4997 } else {
4998 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4999 }
5000 }
5001 } catch (final RemoteException e) {
5002 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5003 e.rethrowFromSystemServer();
5004 }
5005 }
5006
5007 /**
5008 * Gets the connection related to the callback.
5009 *
5010 * @param callback the callback to look up
5011 * @return the related connection
5012 */
5013 @Nullable
5014 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5015 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5016 // Checking by reference here is intentional
5017 if (connection.getCallback() == callback) {
5018 return connection;
5019 }
5020 }
5021 return null;
5022 }
Junyu Laia62493f2021-01-19 11:10:56 +00005023
5024 /**
Roshan Pius951c0032020-12-22 15:10:42 -08005025 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Laia62493f2021-01-19 11:10:56 +00005026 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5027 * be used to request that the system provide a network without causing the network to be
5028 * in the foreground.
5029 *
5030 * <p>This method will attempt to find the best network that matches the passed
5031 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5032 * criteria. The platform will evaluate which network is the best at its own discretion.
5033 * Throughput, latency, cost per byte, policy, user preference and other considerations
5034 * may be factored in the decision of what is considered the best network.
5035 *
5036 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5037 * matching this request, while always attempting to match the request to a better network if
5038 * possible. If a better match is found, the platform will switch this request to the now-best
5039 * network and inform the app of the newly best network by invoking
5040 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5041 * will not try to maintain any other network than the best one currently matching the request:
5042 * a network not matching any network request may be disconnected at any time.
5043 *
5044 * <p>For example, an application could use this method to obtain a connected cellular network
5045 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5046 * radio to consume additional power. Or, an application could inform the system that it wants
5047 * a network supporting sending MMSes and have the system let it know about the currently best
5048 * MMS-supporting network through the provided {@link NetworkCallback}.
5049 *
5050 * <p>The status of the request can be followed by listening to the various callbacks described
5051 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5052 * used to direct traffic to the network (although accessing some networks may be subject to
5053 * holding specific permissions). Callers will learn about the specific characteristics of the
5054 * network through
5055 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5056 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5057 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5058 * matching the request at any given time; therefore when a better network matching the request
5059 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5060 * with the new network after which no further updates are given about the previously-best
5061 * network, unless it becomes the best again at some later time. All callbacks are invoked
5062 * in order on the same thread, which by default is a thread created by the framework running
5063 * in the app.
5064 *
5065 * <p>This{@link NetworkRequest} will live until released via
5066 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5067 * which point the system may let go of the network at any time.
5068 *
5069 * <p>It is presently unsupported to request a network with mutable
5070 * {@link NetworkCapabilities} such as
5071 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5072 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5073 * as these {@code NetworkCapabilities} represent states that a particular
5074 * network may never attain, and whether a network will attain these states
5075 * is unknown prior to bringing up the network so the framework does not
5076 * know how to go about satisfying a request with these capabilities.
5077 *
5078 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5079 * number of outstanding requests to 100 per app (identified by their UID), shared with
5080 * all variants of this method, of {@link #registerNetworkCallback} as well as
5081 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5082 * Requesting a network with this method will count toward this limit. If this limit is
5083 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5084 * make sure to unregister the callbacks with
5085 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5086 *
5087 * @param request {@link NetworkRequest} describing this request.
5088 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5089 * If null, the callback is invoked on the default internal Handler.
5090 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5091 * the callback must not be shared - it uniquely specifies this request.
5092 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5093 * @throws SecurityException if missing the appropriate permissions.
5094 * @throws RuntimeException if the app already has too many callbacks registered.
5095 *
5096 * @hide
5097 */
5098 @SystemApi(client = MODULE_LIBRARIES)
5099 @SuppressLint("ExecutorRegistration")
5100 @RequiresPermission(anyOf = {
5101 android.Manifest.permission.NETWORK_SETTINGS,
5102 android.Manifest.permission.NETWORK_STACK,
5103 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5104 })
5105 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai962bdb82021-03-09 20:49:48 +08005106 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Laia62493f2021-01-19 11:10:56 +00005107 final NetworkCapabilities nc = request.networkCapabilities;
5108 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulai962bdb82021-03-09 20:49:48 +08005109 TYPE_NONE, new CallbackHandler(handler));
Junyu Laia62493f2021-01-19 11:10:56 +00005110 }
James Mattis45d81842021-01-10 14:24:24 -08005111
5112 /**
James Mattis45d81842021-01-10 14:24:24 -08005113 * Used by automotive devices to set the network preferences used to direct traffic at an
5114 * application level as per the given OemNetworkPreferences. An example use-case would be an
5115 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5116 * vehicle via a particular network.
5117 *
5118 * Calling this will overwrite the existing preference.
5119 *
5120 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5121 * @param executor the executor on which listener will be invoked.
5122 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5123 * communicate completion of setOemNetworkPreference(). This will only be
5124 * called once upon successful completion of setOemNetworkPreference().
5125 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5126 * @throws SecurityException if missing the appropriate permissions.
5127 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005128 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005129 */
James Mattisda32cfe2021-01-26 16:23:52 -08005130 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005131 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005132 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005133 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean6010c002021-03-03 16:37:13 +09005134 @Nullable final Runnable listener) {
James Mattis45d81842021-01-10 14:24:24 -08005135 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5136 if (null != listener) {
5137 Objects.requireNonNull(executor, "Executor must be non-null");
5138 }
Chalard Jean6010c002021-03-03 16:37:13 +09005139 final IOnCompleteListener listenerInternal = listener == null ? null :
5140 new IOnCompleteListener.Stub() {
James Mattis45d81842021-01-10 14:24:24 -08005141 @Override
5142 public void onComplete() {
Chalard Jean6010c002021-03-03 16:37:13 +09005143 executor.execute(listener::run);
James Mattis45d81842021-01-10 14:24:24 -08005144 }
5145 };
5146
5147 try {
5148 mService.setOemNetworkPreference(preference, listenerInternal);
5149 } catch (RemoteException e) {
5150 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5151 throw e.rethrowFromSystemServer();
5152 }
5153 }
lucaslin30e70a82021-03-12 00:46:33 +08005154
Chalard Jeanfa45a682021-02-25 17:23:40 +09005155 /**
5156 * Request that a user profile is put by default on a network matching a given preference.
5157 *
5158 * See the documentation for the individual preferences for a description of the supported
5159 * behaviors.
5160 *
5161 * @param profile the profile concerned.
5162 * @param preference the preference for this profile.
5163 * @param executor an executor to execute the listener on. Optional if listener is null.
5164 * @param listener an optional listener to listen for completion of the operation.
5165 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5166 * @throws SecurityException if missing the appropriate permissions.
5167 * @hide
5168 */
Chalard Jean6010c002021-03-03 16:37:13 +09005169 // This function is for establishing per-profile default networking and can only be called by
5170 // the device policy manager, running as the system server. It would make no sense to call it
5171 // on a context for a user because it does not establish a setting on behalf of a user, rather
5172 // it establishes a setting for a user on behalf of the DPM.
5173 @SuppressLint({"UserHandle"})
5174 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09005175 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5176 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5177 @ProfileNetworkPreference final int preference,
5178 @Nullable @CallbackExecutor final Executor executor,
5179 @Nullable final Runnable listener) {
5180 if (null != listener) {
5181 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5182 }
5183 final IOnCompleteListener proxy;
5184 if (null == listener) {
5185 proxy = null;
5186 } else {
5187 proxy = new IOnCompleteListener.Stub() {
5188 @Override
5189 public void onComplete() {
5190 executor.execute(listener::run);
5191 }
5192 };
5193 }
5194 try {
5195 mService.setProfileNetworkPreference(profile, preference, proxy);
5196 } catch (RemoteException e) {
5197 throw e.rethrowFromSystemServer();
5198 }
5199 }
5200
lucaslin30e70a82021-03-12 00:46:33 +08005201 // The first network ID of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005202 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin30e70a82021-03-12 00:46:33 +08005203 // The network ID range of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005204 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin30e70a82021-03-12 00:46:33 +08005205
5206 /**
5207 * Get the network ID range reserved for IPSec tunnel interfaces.
5208 *
5209 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5210 * @hide
5211 */
5212 @SystemApi(client = MODULE_LIBRARIES)
5213 @NonNull
5214 public static Range<Integer> getIpSecNetIdRange() {
5215 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5216 }
lucaslin705c3332021-03-12 17:56:09 +08005217
5218 /**
5219 * Get private DNS mode from settings.
5220 *
lucaslin7abe7e02021-03-17 14:53:35 +08005221 * @param context The Context to query the private DNS mode from settings.
lucaslin705c3332021-03-12 17:56:09 +08005222 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5223 *
5224 * @hide
5225 */
5226 @SystemApi(client = MODULE_LIBRARIES)
5227 @NonNull
5228 @PrivateDnsMode
lucaslin20f04882021-03-16 17:11:14 +08005229 public static String getPrivateDnsMode(@NonNull Context context) {
5230 final ContentResolver cr = context.getContentResolver();
lucaslin705c3332021-03-12 17:56:09 +08005231 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5232 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5233 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5234 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5235 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5236 return mode;
5237 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005238}