blob: 164b984bcdc1432e9be585f053f8c33b7b775070 [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 Lai23568a42021-01-19 11:10:56 +000018import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
paulhu79260c22021-03-17 20:30:33 +080019import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_DEFAULT_MODE;
20import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE;
Junyu Lai23568a42021-01-19 11:10:56 +000021import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaid1a78162021-01-11 16:53:38 +080022import static android.net.NetworkRequest.Type.LISTEN;
junyulai8cae3c72021-03-12 20:05:08 +080023import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
junyulaid1a78162021-01-11 16:53:38 +080024import static android.net.NetworkRequest.Type.REQUEST;
25import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +090026import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Bright60f02ed2020-06-15 16:10:01 -070027import static android.net.QosCallback.QosCallbackRegistrationException;
junyulai48a59382019-01-15 11:32:44 +080028
junyulaia86defc2018-12-27 17:25:29 +080029import android.annotation.CallbackExecutor;
Felipe Lemed16384b2016-01-22 09:44:57 -080030import android.annotation.IntDef;
Chalard Jean42a9c292019-01-07 19:26:34 +090031import android.annotation.NonNull;
Robin Lee33c73e22016-01-05 18:03:46 +000032import android.annotation.Nullable;
Jeff Sharkey2ac62992017-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;
lucaslin50205af2021-03-12 16:11:27 +080036import android.annotation.StringDef;
Junyu Lai23568a42021-01-19 11:10:56 +000037import android.annotation.SuppressLint;
Udam Saini53b71ee2016-01-04 12:16:14 -080038import android.annotation.SystemApi;
Jeff Sharkeyb8c73032017-06-02 17:36:26 -060039import android.annotation.SystemService;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070040import android.app.PendingIntent;
Lorenzo Colitti60104f52021-03-18 00:54:57 +090041import android.app.admin.DevicePolicyManager;
Artur Satayevb9ea02f2019-12-10 17:47:52 +000042import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti60104f52021-03-18 00:54:57 +090043import android.content.ComponentName;
lucaslin50205af2021-03-12 16:11:27 +080044import android.content.ContentResolver;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070045import android.content.Context;
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -070046import android.content.Intent;
Remi NGUYEN VAN5738b862021-04-08 16:26:20 +090047import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
junyulaia86defc2018-12-27 17:25:29 +080048import android.net.IpSecManager.UdpEncapsulationSocket;
49import android.net.SocketKeepalive.Callback;
markchien10ddd022020-01-20 19:31:56 +080050import android.net.TetheringManager.StartTetheringCallback;
markchien75721e42020-01-21 13:11:06 +080051import android.net.TetheringManager.TetheringEventCallback;
markchien10ddd022020-01-20 19:31:56 +080052import android.net.TetheringManager.TetheringRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -080053import android.net.wifi.WifiNetworkSuggestion;
Robert Greenwalt2034b912009-08-12 16:08:25 -070054import android.os.Binder;
Mathew Inwoodac5968e2018-12-20 15:30:45 +000055import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070056import android.os.Build.VERSION_CODES;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080057import android.os.Bundle;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070058import android.os.Handler;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080059import android.os.IBinder;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070060import android.os.Looper;
61import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070062import android.os.Messenger;
junyulai61143782019-03-04 22:45:36 +080063import android.os.ParcelFileDescriptor;
Cody Kestingb5c7abd2020-04-15 12:33:28 -070064import android.os.PersistableBundle;
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +090065import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080066import android.os.RemoteException;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080067import android.os.ResultReceiver;
Hugo Benichi145e3792017-05-11 13:16:17 +090068import android.os.ServiceSpecificException;
Chalard Jean03433052021-02-25 17:23:40 +090069import android.os.UserHandle;
Jeff Sharkey971cd162011-08-29 16:02:57 -070070import android.provider.Settings;
Wink Saville02eb35c2014-12-05 11:10:30 -080071import android.telephony.SubscriptionManager;
Meng Wang91311c02019-11-18 17:10:00 -080072import android.telephony.TelephonyManager;
lucaslin50205af2021-03-12 16:11:27 +080073import android.text.TextUtils;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080074import android.util.ArrayMap;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070075import android.util.Log;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090076import android.util.Range;
Erik Kline50068e52017-01-26 18:08:28 +090077import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080078
markchien75721e42020-01-21 13:11:06 +080079import com.android.internal.annotations.GuardedBy;
Robert Greenwalt3d6c9582014-05-21 20:04:36 -070080
Paul Jensen99c36662014-08-27 12:38:45 -040081import libcore.net.event.NetworkEventDispatcher;
82
junyulai61143782019-03-04 22:45:36 +080083import java.io.IOException;
84import java.io.UncheckedIOException;
Felipe Lemed16384b2016-01-22 09:44:57 -080085import java.lang.annotation.Retention;
86import java.lang.annotation.RetentionPolicy;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090087import java.net.DatagramSocket;
Jeremy Klein04863332015-12-28 15:11:58 -080088import java.net.InetAddress;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -070089import java.net.InetSocketAddress;
junyulaic7ea1242019-01-08 20:04:33 +080090import java.net.Socket;
Hugo Benichi45a49542017-03-06 09:17:06 +090091import java.util.ArrayList;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090092import java.util.Collection;
Jeremy Klein04863332015-12-28 15:11:58 -080093import java.util.HashMap;
Hugo Benichi45a49542017-03-06 09:17:06 +090094import java.util.List;
95import java.util.Map;
markchien75721e42020-01-21 13:11:06 +080096import java.util.Objects;
junyulaia86defc2018-12-27 17:25:29 +080097import java.util.concurrent.Executor;
junyulai9f872232019-01-16 20:23:34 +080098import java.util.concurrent.ExecutorService;
99import java.util.concurrent.Executors;
100import java.util.concurrent.RejectedExecutionException;
Jeremy Klein04863332015-12-28 15:11:58 -0800101
The Android Open Source Project28527d22009-03-03 19:31:44 -0800102/**
103 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600104 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800105 * <p>
106 * The primary responsibilities of this class are to:
107 * <ol>
108 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
109 * <li>Send broadcast intents when network connectivity changes</li>
110 * <li>Attempt to "fail over" to another network when connectivity to a network
111 * is lost</li>
112 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
113 * state of the available networks</li>
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700114 * <li>Provide an API that allows applications to request and select networks for their data
115 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800116 * </ol>
117 */
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600118@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700119public class ConnectivityManager {
120 private static final String TAG = "ConnectivityManager";
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +0900121 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700122
The Android Open Source Project28527d22009-03-03 19:31:44 -0800123 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700124 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800125 * been established or lost. The NetworkInfo for the affected network is
126 * sent as an extra; it should be consulted to see what kind of
127 * connectivity event occurred.
128 * <p/>
Mark Lue1682a02016-12-05 10:57:55 -0800129 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
130 * broadcast if they declare the broadcast receiver in their manifest. Apps
131 * will still receive broadcasts if they register their
132 * {@link android.content.BroadcastReceiver} with
133 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
134 * and that context is still valid.
135 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800136 * If this is a connection that was the result of failing over from a
137 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
138 * set to true.
139 * <p/>
140 * For a loss of connectivity, if the connectivity manager is attempting
141 * to connect (or has already connected) to another network, the
142 * NetworkInfo for the new network is also passed as an extra. This lets
143 * any receivers of the broadcast know that they should not necessarily
144 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt26744a52013-02-15 10:56:35 -0800145 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800146 * the failover attempt succeeded (and so there is still overall data
147 * connectivity), or that the failover attempt failed, meaning that all
148 * connectivity has been lost.
149 * <p/>
150 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
151 * is set to {@code true} if there are no connected networks at all.
Chalard Jeanae2424a2018-02-10 05:33:50 +0900152 *
153 * @deprecated apps should use the more versatile {@link #requestNetwork},
154 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
155 * functions instead for faster and more detailed updates about the network
156 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800158 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jeanae2424a2018-02-10 05:33:50 +0900159 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800160 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700161
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162 /**
Paul Jensened4d55c2015-02-27 22:55:47 -0500163 * The device has connected to a network that has presented a captive
164 * portal, which is blocking Internet connectivity. The user was presented
165 * with a notification that network sign in is required,
166 * and the user invoked the notification's action indicating they
Paul Jensen4173cce2015-05-22 10:50:39 -0400167 * desire to sign in to the network. Apps handling this activity should
Paul Jensened4d55c2015-02-27 22:55:47 -0500168 * facilitate signing in to the network. This action includes a
169 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
170 * the network presenting the captive portal; all communication with the
171 * captive portal must be done using this {@code Network} object.
172 * <p/>
Paul Jensen4173cce2015-05-22 10:50:39 -0400173 * This activity includes a {@link CaptivePortal} extra named
174 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
175 * outcomes of the captive portal sign in to the system:
176 * <ul>
177 * <li> When the app handling this action believes the user has signed in to
178 * the network and the captive portal has been dismissed, the app should
179 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
180 * reevaluate the network. If reevaluation finds the network no longer
181 * subject to a captive portal, the network may become the default active
Chalard Jean73d9db72018-06-04 16:52:49 +0900182 * data network.</li>
Paul Jensen4173cce2015-05-22 10:50:39 -0400183 * <li> When the app handling this action believes the user explicitly wants
Paul Jensened4d55c2015-02-27 22:55:47 -0500184 * to ignore the captive portal and the network, the app should call
Paul Jensen4173cce2015-05-22 10:50:39 -0400185 * {@link CaptivePortal#ignoreNetwork}. </li>
186 * </ul>
Paul Jensened4d55c2015-02-27 22:55:47 -0500187 */
188 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
189 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
190
191 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800192 * The lookup key for a {@link NetworkInfo} object. Retrieve with
193 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700194 *
Chalard Jeancc47b522019-01-11 16:47:53 +0900195 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
196 * can't accurately represent modern network characteristics.
197 * Please obtain information about networks from the {@link NetworkCapabilities}
198 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800199 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700200 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800201 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700202
The Android Open Source Project28527d22009-03-03 19:31:44 -0800203 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700204 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700205 *
206 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeancc47b522019-01-11 16:47:53 +0900207 * @deprecated The network type is not rich enough to represent the characteristics
208 * of modern networks. Please use {@link NetworkCapabilities} instead,
209 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700210 */
Chalard Jeancc47b522019-01-11 16:47:53 +0900211 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700212 public static final String EXTRA_NETWORK_TYPE = "networkType";
213
214 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800215 * The lookup key for a boolean that indicates whether a connect event
216 * is for a network to which the connectivity manager was failing over
217 * following a disconnect on another network.
218 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai5c2f6262018-12-13 12:47:51 +0800219 *
220 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800221 */
junyulai5c2f6262018-12-13 12:47:51 +0800222 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800223 public static final String EXTRA_IS_FAILOVER = "isFailover";
224 /**
225 * The lookup key for a {@link NetworkInfo} object. This is supplied when
226 * there is another network that it may be possible to connect to. Retrieve with
227 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800228 *
229 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230 */
junyulai5c2f6262018-12-13 12:47:51 +0800231 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
233 /**
234 * The lookup key for a boolean that indicates whether there is a
235 * complete lack of connectivity, i.e., no network is available.
236 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
237 */
238 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
239 /**
240 * The lookup key for a string that indicates why an attempt to connect
241 * to a network failed. The string has no particular structure. It is
242 * intended to be used in notifications presented to users. Retrieve
243 * it with {@link android.content.Intent#getStringExtra(String)}.
244 */
245 public static final String EXTRA_REASON = "reason";
246 /**
247 * The lookup key for a string that provides optionally supplied
248 * extra information about the network state. The information
249 * may be passed up from the lower networking layers, and its
250 * meaning may be specific to a particular network type. Retrieve
251 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800252 *
253 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800254 */
junyulai5c2f6262018-12-13 12:47:51 +0800255 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800256 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700257 /**
258 * The lookup key for an int that provides information about
259 * our connection to the internet at large. 0 indicates no connection,
260 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700261 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700262 * {@hide}
263 */
264 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800265 /**
Paul Jensen4173cce2015-05-22 10:50:39 -0400266 * The lookup key for a {@link CaptivePortal} object included with the
267 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
268 * object can be used to either indicate to the system that the captive
269 * portal has been dismissed or that the user does not want to pursue
270 * signing in to captive portal. Retrieve it with
271 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensened4d55c2015-02-27 22:55:47 -0500272 */
Paul Jensen4173cce2015-05-22 10:50:39 -0400273 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist0f3b4442015-09-22 15:54:32 -0700274
275 /**
276 * Key for passing a URL to the captive portal login activity.
277 */
278 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
279
Paul Jensened4d55c2015-02-27 22:55:47 -0500280 /**
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900281 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
282 * portal login activity.
283 * {@hide}
284 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900285 @SystemApi
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900286 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
287 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
288
289 /**
Hugo Benichidce21c52016-12-14 08:23:40 +0900290 * Key for passing a user agent string to the captive portal login activity.
291 * {@hide}
292 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900293 @SystemApi
Hugo Benichidce21c52016-12-14 08:23:40 +0900294 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
295 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
296
297 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700298 * Broadcast action to indicate the change of data activity status
299 * (idle or active) on a network in a recent period.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800300 * The network becomes active when data transmission is started, or
301 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700302 * {@hide}
303 */
304 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean73d9db72018-06-04 16:52:49 +0900305 public static final String ACTION_DATA_ACTIVITY_CHANGE =
306 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700307 /**
308 * The lookup key for an enum that indicates the network device type on which this data activity
309 * change happens.
310 * {@hide}
311 */
312 public static final String EXTRA_DEVICE_TYPE = "deviceType";
313 /**
314 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
315 * it is actively sending or receiving data and {@code false} means it is idle.
316 * {@hide}
317 */
318 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma601fba92014-03-12 18:42:23 -0700319 /**
320 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
321 * {@hide}
322 */
323 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700324
325 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800326 * Broadcast Action: The setting for background data usage has changed
327 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
328 * <p>
329 * If an application uses the network in the background, it should listen
330 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700331 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800332 * <p>
333 *
334 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
335 * of background data depends on several combined factors, and
336 * this broadcast is no longer sent. Instead, when background
337 * data is unavailable, {@link #getActiveNetworkInfo()} will now
338 * appear disconnected. During first boot after a platform
339 * upgrade, this broadcast will be sent once if
340 * {@link #getBackgroundDataSetting()} was {@code false} before
341 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800342 */
343 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800344 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800345 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
346 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
347
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700348 /**
349 * Broadcast Action: The network connection may not be good
350 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
351 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
352 * the network and it's condition.
353 * @hide
354 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800355 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100356 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700357 public static final String INET_CONDITION_ACTION =
358 "android.net.conn.INET_CONDITION_ACTION";
359
Robert Greenwalt2034b912009-08-12 16:08:25 -0700360 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800361 * Broadcast Action: A tetherable connection has come or gone.
362 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline449ccfe2017-04-17 16:47:23 +0900363 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
364 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt26744a52013-02-15 10:56:35 -0800365 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
366 * the current state of tethering. Each include a list of
367 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800368 * @hide
369 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800370 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000371 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800372 public static final String ACTION_TETHER_STATE_CHANGED =
markchien1f523702019-12-25 19:40:32 +0800373 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800374
375 /**
376 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800377 * gives a String[] listing all the interfaces configured for
378 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800379 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000380 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800381 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800382
383 /**
384 * @hide
Erik Kline449ccfe2017-04-17 16:47:23 +0900385 * gives a String[] listing all the interfaces currently in local-only
386 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800387 */
markchien1f523702019-12-25 19:40:32 +0800388 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline449ccfe2017-04-17 16:47:23 +0900389
390 /**
391 * @hide
392 * gives a String[] listing all the interfaces currently tethered
393 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
394 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000395 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800396 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800397
398 /**
399 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800400 * gives a String[] listing all the interfaces we tried to tether and
401 * failed. Use {@link #getLastTetherError} to find the error code
402 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800403 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800405 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800406
407 /**
Russell Brenner4774b022013-02-12 10:03:14 -0800408 * Broadcast Action: The captive portal tracker has finished its test.
409 * Sent only while running Setup Wizard, in lieu of showing a user
410 * notification.
411 * @hide
412 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800413 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner4774b022013-02-12 10:03:14 -0800414 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
415 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
416 /**
417 * The lookup key for a boolean that indicates whether a captive portal was detected.
418 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
419 * @hide
420 */
421 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
422
423 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900424 * Action used to display a dialog that asks the user whether to connect to a network that is
425 * not validated. This intent is used to start the dialog in settings via startActivity.
426 *
lucaslin8a8cb5d2021-04-21 10:43:15 +0800427 * This action includes a {@link Network} typed extra which is called
428 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
429 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900430 * @hide
431 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800432 @SystemApi(client = MODULE_LIBRARIES)
433 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900434
435 /**
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900436 * Action used to display a dialog that asks the user whether to avoid a network that is no
437 * longer validated. This intent is used to start the dialog in settings via startActivity.
438 *
lucaslin8a8cb5d2021-04-21 10:43:15 +0800439 * This action includes a {@link Network} typed extra which is called
440 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
441 * validated.
442 *
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900443 * @hide
444 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800445 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900446 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslin1a0ca5f2021-03-04 17:09:51 +0800447 "android.net.action.PROMPT_LOST_VALIDATION";
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900448
449 /**
lucaslin25a50472019-03-12 13:08:03 +0800450 * Action used to display a dialog that asks the user whether to stay connected to a network
451 * that has not validated. This intent is used to start the dialog in settings via
452 * startActivity.
453 *
lucaslin8a8cb5d2021-04-21 10:43:15 +0800454 * This action includes a {@link Network} typed extra which is called
455 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
456 * connectivity.
457 *
lucaslin25a50472019-03-12 13:08:03 +0800458 * @hide
459 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800460 @SystemApi(client = MODULE_LIBRARIES)
lucaslin25a50472019-03-12 13:08:03 +0800461 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslin1a0ca5f2021-03-04 17:09:51 +0800462 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
lucaslin25a50472019-03-12 13:08:03 +0800463
464 /**
paulhu164c97d2021-04-07 16:18:13 +0800465 * Clear DNS Cache Action: This is broadcast when networks have changed and old
466 * DNS entries should be cleared.
467 * @hide
468 */
469 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
470 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
471 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
472
473 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800474 * Invalid tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900475 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800476 * @hide
477 */
markchien1f523702019-12-25 19:40:32 +0800478 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800479
480 /**
481 * Wifi tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900482 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800483 * @hide
484 */
485 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900486 public static final int TETHERING_WIFI = 0;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800487
488 /**
489 * USB tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900490 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800491 * @hide
492 */
493 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900494 public static final int TETHERING_USB = 1;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800495
496 /**
497 * Bluetooth tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900498 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800499 * @hide
500 */
501 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900502 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800503
504 /**
Jimmy Chen87db1542019-07-15 18:03:23 +0800505 * Wifi P2p tethering type.
506 * Wifi P2p tethering is set through events automatically, and don't
507 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
508 * @hide
509 */
markchien1f523702019-12-25 19:40:32 +0800510 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chen87db1542019-07-15 18:03:23 +0800511
512 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800513 * Extra used for communicating with the TetherService. Includes the type of tethering to
514 * enable if any.
515 * @hide
516 */
markchien75721e42020-01-21 13:11:06 +0800517 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800518
519 /**
520 * Extra used for communicating with the TetherService. Includes the type of tethering for
521 * which to cancel provisioning.
522 * @hide
523 */
markchien75721e42020-01-21 13:11:06 +0800524 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800525
526 /**
527 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
528 * provisioning.
529 * @hide
530 */
markchien75721e42020-01-21 13:11:06 +0800531 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800532
533 /**
534 * Tells the TetherService to run a provision check now.
535 * @hide
536 */
markchien75721e42020-01-21 13:11:06 +0800537 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800538
539 /**
540 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
541 * which will receive provisioning results. Can be left empty.
542 * @hide
543 */
markchien75721e42020-01-21 13:11:06 +0800544 public static final String EXTRA_PROVISION_CALLBACK =
545 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800546
547 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800548 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700549 * @hide
550 */
paulhu62af6122020-01-13 16:46:45 +0800551 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700552 public static final int TYPE_NONE = -1;
553
554 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900555 * A Mobile data connection. Devices may support more than one.
556 *
557 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
558 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
559 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700560 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900561 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562 public static final int TYPE_MOBILE = 0;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900563
Robert Greenwalt2034b912009-08-12 16:08:25 -0700564 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900565 * A WIFI data connection. Devices may support more than one.
566 *
567 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
568 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
569 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700570 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900571 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700572 public static final int TYPE_WIFI = 1;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900573
Robert Greenwalt2034b912009-08-12 16:08:25 -0700574 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800575 * An MMS-specific Mobile data connection. This network type may use the
576 * same network interface as {@link #TYPE_MOBILE} or it may use a different
577 * one. This is used by applications needing to talk to the carrier's
578 * Multimedia Messaging Service servers.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900579 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900580 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900581 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900582 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700583 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700584 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700585 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900586
Robert Greenwalt2034b912009-08-12 16:08:25 -0700587 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800588 * A SUPL-specific Mobile data connection. This network type may use the
589 * same network interface as {@link #TYPE_MOBILE} or it may use a different
590 * one. This is used by applications needing to talk to the carrier's
591 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900592 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900593 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900594 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900595 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700596 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700597 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700598 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900599
Robert Greenwalt2034b912009-08-12 16:08:25 -0700600 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800601 * A DUN-specific Mobile data connection. This network type may use the
602 * same network interface as {@link #TYPE_MOBILE} or it may use a different
603 * one. This is sometimes by the system when setting up an upstream connection
604 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900605 *
606 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
607 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
608 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700609 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900610 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700611 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900612
Robert Greenwalt2034b912009-08-12 16:08:25 -0700613 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800614 * A High Priority Mobile data connection. This network type uses the
615 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900616 * is different.
617 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900618 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
619 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
620 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700621 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700622 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700623 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900624
jshbfa81722010-03-11 15:04:43 -0800625 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900626 * A WiMAX data connection.
627 *
628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
630 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800631 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900632 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800633 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800634
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800635 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900636 * A Bluetooth data connection.
637 *
638 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
639 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
640 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800641 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900642 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800643 public static final int TYPE_BLUETOOTH = 7;
644
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700645 /**
Chiachang Wang7d5f3782020-07-28 13:53:09 +0800646 * Fake data connection. This should not be used on shipping devices.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900647 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700648 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900649 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800650 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800651
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700652 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900653 * An Ethernet data connection.
654 *
655 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
656 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
657 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700658 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900659 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800660 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700661
Wink Savilleb7c92c72011-03-12 14:52:01 -0800662 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800663 * Over the air Administration.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900664 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800665 * {@hide}
666 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900667 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900668 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800669 public static final int TYPE_MOBILE_FOTA = 10;
670
671 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800672 * IP Multimedia Subsystem.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900673 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800674 * {@hide}
675 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900676 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100677 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800678 public static final int TYPE_MOBILE_IMS = 11;
679
680 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800681 * Carrier Branded Services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900682 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800683 * {@hide}
684 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900685 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900686 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800687 public static final int TYPE_MOBILE_CBS = 12;
688
repo syncf5de5572011-07-29 23:55:49 -0700689 /**
690 * A Wi-Fi p2p connection. Only requesting processes will have access to
691 * the peers connected.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900692 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700693 * {@hide}
694 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900695 @Deprecated
paulhu028732e2020-01-15 15:38:23 +0800696 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700697 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800698
Wink Saville70dbdcc2013-07-29 15:00:57 -0700699 /**
700 * The network to use for initially attaching to the network
Chalard Jean5acb7b72018-03-08 13:54:53 +0900701 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville70dbdcc2013-07-29 15:00:57 -0700702 * {@hide}
703 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900704 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100705 @UnsupportedAppUsage
Wink Saville70dbdcc2013-07-29 15:00:57 -0700706 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700707
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900708 /**
Robert Greenwalt9db5f3c2015-07-09 14:49:35 -0700709 * Emergency PDN connection for emergency services. This
710 * may include IMS and MMS in emergency situations.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900711 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram201d45f2014-06-26 11:03:44 -0700712 * {@hide}
713 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900714 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900715 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram201d45f2014-06-26 11:03:44 -0700716 public static final int TYPE_MOBILE_EMERGENCY = 15;
717
Hui Lu07f29332014-01-15 11:05:36 -0500718 /**
719 * The network that uses proxy to achieve connectivity.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900720 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu07f29332014-01-15 11:05:36 -0500721 * {@hide}
722 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900723 @Deprecated
Remi NGUYEN VANdaeafee2020-11-30 19:23:45 +0900724 @SystemApi
Hui Lu07f29332014-01-15 11:05:36 -0500725 public static final int TYPE_PROXY = 16;
Wink Saville70dbdcc2013-07-29 15:00:57 -0700726
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700727 /**
728 * A virtual network using one or more native bearers.
729 * It may or may not be providing security services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900730 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700731 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900732 @Deprecated
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700733 public static final int TYPE_VPN = 17;
Hui Lu07f29332014-01-15 11:05:36 -0500734
Benedict Wong80156022018-11-14 17:40:55 -0800735 /**
736 * A network that is exclusively meant to be used for testing
737 *
738 * @deprecated Use {@link NetworkCapabilities} instead.
739 * @hide
740 */
741 @Deprecated
742 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700743
Chalard Jean74fe1c72020-03-25 01:24:04 +0900744 /**
745 * @deprecated Use {@link NetworkCapabilities} instead.
746 * @hide
747 */
748 @Deprecated
749 @Retention(RetentionPolicy.SOURCE)
750 @IntDef(prefix = { "TYPE_" }, value = {
751 TYPE_NONE,
752 TYPE_MOBILE,
753 TYPE_WIFI,
754 TYPE_MOBILE_MMS,
755 TYPE_MOBILE_SUPL,
756 TYPE_MOBILE_DUN,
757 TYPE_MOBILE_HIPRI,
758 TYPE_WIMAX,
759 TYPE_BLUETOOTH,
760 TYPE_DUMMY,
761 TYPE_ETHERNET,
762 TYPE_MOBILE_FOTA,
763 TYPE_MOBILE_IMS,
764 TYPE_MOBILE_CBS,
765 TYPE_WIFI_P2P,
766 TYPE_MOBILE_IA,
767 TYPE_MOBILE_EMERGENCY,
768 TYPE_PROXY,
769 TYPE_VPN,
770 TYPE_TEST
771 })
772 public @interface LegacyNetworkType {}
773
Chalard Jean1f42df12019-11-21 14:48:00 +0900774 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
775 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
776 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
777 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
778 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
779
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700780 /** {@hide} */
Benedict Wong80156022018-11-14 17:40:55 -0800781 public static final int MAX_RADIO_TYPE = TYPE_TEST;
782
783 /** {@hide} */
784 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800785
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900786 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
787
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800788 /**
789 * If you want to set the default network preference,you can directly
790 * change the networkAttributes array in framework's config.xml.
791 *
792 * @deprecated Since we support so many more networks now, the single
793 * network default network preference can't really express
Robert Greenwalt26744a52013-02-15 10:56:35 -0800794 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800795 * networkAttributes in config.xml. You can determine
Robert Greenwalt1ee3d2c2012-12-07 09:56:50 -0800796 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800797 * from an App.
798 */
799 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800800 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
801
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700802 /**
Robert Greenwalta1402df2014-03-19 17:56:12 -0700803 * @hide
804 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900805 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltc34f83b2014-06-08 16:42:59 -0700806
Paul Jensen0478ace2014-07-11 12:28:19 -0400807 /**
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900808 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
809 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean73d9db72018-06-04 16:52:49 +0900810 * registered from those that were already unregistered.
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900811 * @hide
812 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900813 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900814 new NetworkRequest.Builder().clearCapabilities().build();
815
816 /**
Paul Jensen0478ace2014-07-11 12:28:19 -0400817 * A NetID indicating no Network is selected.
818 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
819 * @hide
820 */
821 public static final int NETID_UNSET = 0;
822
Erik Kline1ecdd962017-10-30 15:29:44 +0900823 /**
824 * Private DNS Mode values.
825 *
826 * The "private_dns_mode" global setting stores a String value which is
827 * expected to be one of the following.
828 */
829
830 /**
831 * @hide
832 */
lucaslin50205af2021-03-12 16:11:27 +0800833 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900834 public static final String PRIVATE_DNS_MODE_OFF = "off";
835 /**
836 * @hide
837 */
lucaslin50205af2021-03-12 16:11:27 +0800838 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900839 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
840 /**
841 * @hide
842 */
lucaslin50205af2021-03-12 16:11:27 +0800843 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900844 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin50205af2021-03-12 16:11:27 +0800845
846 /** @hide */
847 @Retention(RetentionPolicy.SOURCE)
848 @StringDef(value = {
849 PRIVATE_DNS_MODE_OFF,
850 PRIVATE_DNS_MODE_OPPORTUNISTIC,
851 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
852 })
853 public @interface PrivateDnsMode {}
Erik Kline1ecdd962017-10-30 15:29:44 +0900854
Sudheer Shanka457dfd52021-03-23 08:12:28 +0000855 /**
856 * Flag to indicate that an app is not subject to any restrictions that could result in its
857 * network access blocked.
858 *
859 * @hide
860 */
861 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
862 public static final int BLOCKED_REASON_NONE = 0;
863
864 /**
865 * Flag to indicate that an app is subject to Battery saver restrictions that would
866 * result in its network access being blocked.
867 *
868 * @hide
869 */
870 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
871 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
872
873 /**
874 * Flag to indicate that an app is subject to Doze restrictions that would
875 * result in its network access being blocked.
876 *
877 * @hide
878 */
879 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
880 public static final int BLOCKED_REASON_DOZE = 1 << 1;
881
882 /**
883 * Flag to indicate that an app is subject to App Standby restrictions that would
884 * result in its network access being blocked.
885 *
886 * @hide
887 */
888 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
889 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
890
891 /**
892 * Flag to indicate that an app is subject to Restricted mode restrictions that would
893 * result in its network access being blocked.
894 *
895 * @hide
896 */
897 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
898 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
899
900 /**
Lorenzo Colitti60104f52021-03-18 00:54:57 +0900901 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
902 * is not currently connected.
903 *
904 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
905 *
906 * @hide
907 */
908 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
909 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
910
911 /**
Sudheer Shanka457dfd52021-03-23 08:12:28 +0000912 * Flag to indicate that an app is subject to Data saver restrictions that would
913 * result in its metered network access being blocked.
914 *
915 * @hide
916 */
917 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
918 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
919
920 /**
921 * Flag to indicate that an app is subject to user restrictions that would
922 * result in its metered network access being blocked.
923 *
924 * @hide
925 */
926 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
927 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
928
929 /**
930 * Flag to indicate that an app is subject to Device admin restrictions that would
931 * result in its metered network access being blocked.
932 *
933 * @hide
934 */
935 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
936 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
937
938 /**
939 * @hide
940 */
941 @Retention(RetentionPolicy.SOURCE)
942 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
943 BLOCKED_REASON_NONE,
944 BLOCKED_REASON_BATTERY_SAVER,
945 BLOCKED_REASON_DOZE,
946 BLOCKED_REASON_APP_STANDBY,
947 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia37eaff2021-03-25 23:17:36 +0900948 BLOCKED_REASON_LOCKDOWN_VPN,
Sudheer Shanka457dfd52021-03-23 08:12:28 +0000949 BLOCKED_METERED_REASON_DATA_SAVER,
950 BLOCKED_METERED_REASON_USER_RESTRICTED,
951 BLOCKED_METERED_REASON_ADMIN_DISABLED,
952 })
953 public @interface BlockedReason {}
954
Lorenzo Colitti60104f52021-03-18 00:54:57 +0900955 /**
956 * Set of blocked reasons that are only applicable on metered networks.
957 *
958 * @hide
959 */
960 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
961 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
962
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900963 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700964 private final IConnectivityManager mService;
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +0900965
Paul Jensen12131352014-12-10 15:12:18 -0500966 /**
967 * A kludge to facilitate static access where a Context pointer isn't available, like in the
968 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
969 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
970 * methods that take a Context argument.
971 */
972 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800973
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +0900974 private final Context mContext;
975
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +0000976 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800977
Robert Greenwalt26744a52013-02-15 10:56:35 -0800978 /**
979 * Tests if a given integer represents a valid network type.
980 * @param networkType the type to be tested
981 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen1c9f2e42015-05-06 10:42:25 -0400982 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
983 * validate a network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800984 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700985 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700986 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900987 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800988 }
989
Robert Greenwalt26744a52013-02-15 10:56:35 -0800990 /**
991 * Returns a non-localized string representing a given network type.
992 * ONLY used for debugging output.
993 * @param type the type needing naming
994 * @return a String for the given type, or a string version of the type ("87")
995 * if no name is known.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900996 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800997 * {@hide}
998 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900999 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001000 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001001 public static String getNetworkTypeName(int type) {
1002 switch (type) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +09001003 case TYPE_NONE:
1004 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -07001005 case TYPE_MOBILE:
1006 return "MOBILE";
1007 case TYPE_WIFI:
1008 return "WIFI";
1009 case TYPE_MOBILE_MMS:
1010 return "MOBILE_MMS";
1011 case TYPE_MOBILE_SUPL:
1012 return "MOBILE_SUPL";
1013 case TYPE_MOBILE_DUN:
1014 return "MOBILE_DUN";
1015 case TYPE_MOBILE_HIPRI:
1016 return "MOBILE_HIPRI";
1017 case TYPE_WIMAX:
1018 return "WIMAX";
1019 case TYPE_BLUETOOTH:
1020 return "BLUETOOTH";
1021 case TYPE_DUMMY:
1022 return "DUMMY";
1023 case TYPE_ETHERNET:
1024 return "ETHERNET";
1025 case TYPE_MOBILE_FOTA:
1026 return "MOBILE_FOTA";
1027 case TYPE_MOBILE_IMS:
1028 return "MOBILE_IMS";
1029 case TYPE_MOBILE_CBS:
1030 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -07001031 case TYPE_WIFI_P2P:
1032 return "WIFI_P2P";
Wink Saville70dbdcc2013-07-29 15:00:57 -07001033 case TYPE_MOBILE_IA:
1034 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -07001035 case TYPE_MOBILE_EMERGENCY:
1036 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -05001037 case TYPE_PROXY:
1038 return "PROXY";
Erik Klineb1ff7002014-11-19 17:23:41 +09001039 case TYPE_VPN:
1040 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -07001041 default:
1042 return Integer.toString(type);
1043 }
1044 }
1045
Robert Greenwalt26744a52013-02-15 10:56:35 -08001046 /**
Aaron Huangdfba5d12020-06-27 07:18:23 +08001047 * @hide
Aaron Huangdfba5d12020-06-27 07:18:23 +08001048 */
lucaslin8c121bf2021-03-17 14:16:01 +08001049 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huangdfba5d12020-06-27 07:18:23 +08001050 public void systemReady() {
1051 try {
1052 mService.systemReady();
1053 } catch (RemoteException e) {
1054 throw e.rethrowFromSystemServer();
1055 }
1056 }
1057
1058 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001059 * Checks if a given type uses the cellular data connection.
1060 * This should be replaced in the future by a network property.
1061 * @param networkType the type to check
1062 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09001063 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001064 * {@hide}
1065 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09001066 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001067 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001068 public static boolean isNetworkTypeMobile(int networkType) {
1069 switch (networkType) {
1070 case TYPE_MOBILE:
1071 case TYPE_MOBILE_MMS:
1072 case TYPE_MOBILE_SUPL:
1073 case TYPE_MOBILE_DUN:
1074 case TYPE_MOBILE_HIPRI:
1075 case TYPE_MOBILE_FOTA:
1076 case TYPE_MOBILE_IMS:
1077 case TYPE_MOBILE_CBS:
Wink Saville70dbdcc2013-07-29 15:00:57 -07001078 case TYPE_MOBILE_IA:
Ram201d45f2014-06-26 11:03:44 -07001079 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -07001080 return true;
1081 default:
1082 return false;
1083 }
1084 }
1085
Robert Greenwalt26744a52013-02-15 10:56:35 -08001086 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001087 * Checks if the given network type is backed by a Wi-Fi radio.
1088 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001089 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001090 * @hide
1091 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09001092 @Deprecated
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001093 public static boolean isNetworkTypeWifi(int networkType) {
1094 switch (networkType) {
1095 case TYPE_WIFI:
1096 case TYPE_WIFI_P2P:
1097 return true;
1098 default:
1099 return false;
1100 }
1101 }
1102
1103 /**
Chalard Jean03433052021-02-25 17:23:40 +09001104 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1105 * Specify that the traffic for this user should by follow the default rules.
1106 * @hide
1107 */
Chalard Jean560d4032021-03-17 14:33:24 +09001108 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09001109 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1110
1111 /**
1112 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1113 * Specify that the traffic for this user should by default go on a network with
1114 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1115 * if no such network is available.
1116 * @hide
1117 */
Chalard Jean560d4032021-03-17 14:33:24 +09001118 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09001119 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1120
1121 /** @hide */
1122 @Retention(RetentionPolicy.SOURCE)
1123 @IntDef(value = {
1124 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1125 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1126 })
1127 public @interface ProfileNetworkPreference {
1128 }
1129
1130 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001131 * Specifies the preferred network type. When the device has more
1132 * than one type available the preferred network type will be used.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001133 *
1134 * @param preference the network type to prefer over all others. It is
1135 * unspecified what happens to the old preferred network in the
1136 * overall ordering.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001137 * @deprecated Functionality has been removed as it no longer makes sense,
1138 * with many more than two networks - we'd need an array to express
1139 * preference. Instead we use dynamic network properties of
1140 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001141 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001142 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001143 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001144 }
1145
Robert Greenwalt26744a52013-02-15 10:56:35 -08001146 /**
1147 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001148 *
1149 * @return an integer representing the preferred network type
1150 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001151 * @deprecated Functionality has been removed as it no longer makes sense,
1152 * with many more than two networks - we'd need an array to express
1153 * preference. Instead we use dynamic network properties of
1154 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001155 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001156 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001157 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001158 public int getNetworkPreference() {
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001159 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001160 }
1161
Scott Mainf58b7d82011-10-06 19:02:28 -07001162 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001163 * Returns details about the currently active default data network. When
1164 * connected, this network is the default route for outgoing connections.
1165 * You should always check {@link NetworkInfo#isConnected()} before initiating
1166 * network traffic. This may return {@code null} when there is no default
1167 * network.
Chalard Jean7c85ba42018-03-29 17:45:24 +09001168 * Note that if the default network is a VPN, this method will return the
1169 * NetworkInfo for one of its underlying networks instead, or null if the
1170 * VPN agent did not specify any. Apps interested in learning about VPNs
1171 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001172 *
1173 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001174 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001175 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001176 */
junyulai5c2f6262018-12-13 12:47:51 +08001177 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001178 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001179 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001180 public NetworkInfo getActiveNetworkInfo() {
1181 try {
1182 return mService.getActiveNetworkInfo();
1183 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001184 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001185 }
1186 }
1187
Robert Greenwalt26744a52013-02-15 10:56:35 -08001188 /**
Paul Jensenc2569432015-02-13 14:18:39 -05001189 * Returns a {@link Network} object corresponding to the currently active
1190 * default data network. In the event that the current active default data
1191 * network disconnects, the returned {@code Network} object will no longer
1192 * be usable. This will return {@code null} when there is no default
1193 * network.
1194 *
1195 * @return a {@link Network} object for the current default network or
1196 * {@code null} if no default network is currently active
Paul Jensenc2569432015-02-13 14:18:39 -05001197 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001198 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001199 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001200 public Network getActiveNetwork() {
1201 try {
1202 return mService.getActiveNetwork();
1203 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001204 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001205 }
1206 }
1207
1208 /**
Robin Leeda4d2e22016-03-24 12:07:00 +00001209 * Returns a {@link Network} object corresponding to the currently active
1210 * default data network for a specific UID. In the event that the default data
1211 * network disconnects, the returned {@code Network} object will no longer
1212 * be usable. This will return {@code null} when there is no default
1213 * network for the UID.
Robin Leeda4d2e22016-03-24 12:07:00 +00001214 *
1215 * @return a {@link Network} object for the current default network for the
1216 * given UID or {@code null} if no default network is currently active
lifr5f1c1102021-03-30 21:04:53 +08001217 *
1218 * @hide
Robin Leeda4d2e22016-03-24 12:07:00 +00001219 */
paulhuec0a9632019-08-12 16:25:11 +08001220 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001221 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001222 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001223 return getActiveNetworkForUid(uid, false);
1224 }
1225
1226 /** {@hide} */
1227 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001228 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001229 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001230 } catch (RemoteException e) {
1231 throw e.rethrowFromSystemServer();
1232 }
1233 }
1234
1235 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001236 * Adds or removes a requirement for given UID ranges to use the VPN.
1237 *
1238 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1239 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1240 * otherwise have permission to bypass the VPN (e.g., because they have the
1241 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1242 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1243 * set to {@code false}, a previously-added restriction is removed.
1244 * <p>
1245 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1246 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1247 * remove a previously-added range, the exact range must be removed as is.
1248 * <p>
1249 * The changes are applied asynchronously and may not have been applied by the time the method
1250 * returns. Apps will be notified about any changes that apply to them via
1251 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1252 * effect.
1253 * <p>
1254 * This method should be called only by the VPN code.
1255 *
1256 * @param ranges the UID ranges to restrict
1257 * @param requireVpn whether the specified UID ranges must use a VPN
1258 *
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001259 * @hide
1260 */
1261 @RequiresPermission(anyOf = {
1262 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001263 android.Manifest.permission.NETWORK_STACK,
1264 android.Manifest.permission.NETWORK_SETTINGS})
1265 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001266 public void setRequireVpnForUids(boolean requireVpn,
1267 @NonNull Collection<Range<Integer>> ranges) {
1268 Objects.requireNonNull(ranges);
1269 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1270 // This method is not necessarily expected to be used outside the system server, so
1271 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1272 // stack process, or by tests.
1273 UidRange[] rangesArray = new UidRange[ranges.size()];
1274 int index = 0;
1275 for (Range<Integer> range : ranges) {
1276 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1277 }
1278 try {
1279 mService.setRequireVpnForUids(requireVpn, rangesArray);
1280 } catch (RemoteException e) {
1281 throw e.rethrowFromSystemServer();
1282 }
1283 }
1284
1285 /**
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001286 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1287 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1288 * but is still supported for backwards compatibility.
1289 * <p>
1290 * This type of VPN is assumed always to use the system default network, and must always declare
1291 * exactly one underlying network, which is the network that was the default when the VPN
1292 * connected.
1293 * <p>
1294 * Calling this method with {@code true} enables legacy behaviour, specifically:
1295 * <ul>
1296 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1297 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1298 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1299 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1300 * underlying the VPN.</li>
1301 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1302 * similarly replaced by the VPN network state.</li>
1303 * <li>Information on current network interfaces passed to NetworkStatsService will not
1304 * include any VPN interfaces.</li>
1305 * </ul>
1306 *
1307 * @param enabled whether legacy lockdown VPN is enabled or disabled
1308 *
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001309 * @hide
1310 */
1311 @RequiresPermission(anyOf = {
1312 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001313 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001314 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin5140e482021-03-22 11:51:27 +08001315 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001316 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1317 try {
1318 mService.setLegacyLockdownVpnEnabled(enabled);
1319 } catch (RemoteException e) {
1320 throw e.rethrowFromSystemServer();
1321 }
1322 }
1323
1324 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001325 * Returns details about the currently active default data network
1326 * for a given uid. This is for internal use only to avoid spying
1327 * other apps.
1328 *
1329 * @return a {@link NetworkInfo} object for the current default network
1330 * for the given uid or {@code null} if no default network is
1331 * available for the specified uid.
1332 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001333 * {@hide}
1334 */
paulhuec0a9632019-08-12 16:25:11 +08001335 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001336 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001337 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001338 return getActiveNetworkInfoForUid(uid, false);
1339 }
1340
1341 /** {@hide} */
1342 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001343 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001344 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001345 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001346 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001347 }
1348 }
1349
Robert Greenwalt26744a52013-02-15 10:56:35 -08001350 /**
1351 * Returns connection status information about a particular
1352 * network type.
1353 *
1354 * @param networkType integer specifying which networkType in
1355 * which you're interested.
1356 * @return a {@link NetworkInfo} object for the requested
1357 * network type or {@code null} if the type is not
Chalard Jean7c85ba42018-03-29 17:45:24 +09001358 * supported by the device. If {@code networkType} is
1359 * TYPE_VPN and a VPN is active for the calling app,
1360 * then this method will try to return one of the
1361 * underlying networks for the VPN or null if the
1362 * VPN agent didn't specify any.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001363 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001364 * @deprecated This method does not support multiple connected networks
1365 * of the same type. Use {@link #getAllNetworks} and
1366 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001367 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001368 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001369 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001370 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001371 public NetworkInfo getNetworkInfo(int networkType) {
1372 try {
1373 return mService.getNetworkInfo(networkType);
1374 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001375 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001376 }
1377 }
1378
Robert Greenwalt26744a52013-02-15 10:56:35 -08001379 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001380 * Returns connection status information about a particular
1381 * Network.
1382 *
1383 * @param network {@link Network} specifying which network
1384 * in which you're interested.
1385 * @return a {@link NetworkInfo} object for the requested
1386 * network or {@code null} if the {@code Network}
1387 * is not valid.
junyulai5c2f6262018-12-13 12:47:51 +08001388 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001389 */
junyulai5c2f6262018-12-13 12:47:51 +08001390 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001391 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001392 @Nullable
1393 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001394 return getNetworkInfoForUid(network, Process.myUid(), false);
1395 }
1396
1397 /** {@hide} */
1398 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001399 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001400 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001401 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001402 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001403 }
1404 }
1405
1406 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001407 * Returns connection status information about all network
1408 * types supported by the device.
1409 *
1410 * @return an array of {@link NetworkInfo} objects. Check each
1411 * {@link NetworkInfo#getType} for which type each applies.
1412 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001413 * @deprecated This method does not support multiple connected networks
1414 * of the same type. Use {@link #getAllNetworks} and
1415 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001416 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001417 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001418 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001419 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001420 public NetworkInfo[] getAllNetworkInfo() {
1421 try {
1422 return mService.getAllNetworkInfo();
1423 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001424 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001425 }
1426 }
1427
Robert Greenwalt26744a52013-02-15 10:56:35 -08001428 /**
junyulai57840802021-03-03 12:09:05 +08001429 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1430 * connected.
1431 * @hide
1432 */
1433 @SystemApi(client = MODULE_LIBRARIES)
1434 @RequiresPermission(anyOf = {
1435 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1436 android.Manifest.permission.NETWORK_STACK,
1437 android.Manifest.permission.NETWORK_SETTINGS})
1438 @NonNull
Aaron Huang20605e52021-04-17 13:46:25 +08001439 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulai57840802021-03-03 12:09:05 +08001440 try {
Aaron Huang20605e52021-04-17 13:46:25 +08001441 return mService.getAllNetworkStateSnapshots();
junyulai57840802021-03-03 12:09:05 +08001442 } catch (RemoteException e) {
1443 throw e.rethrowFromSystemServer();
1444 }
1445 }
1446
1447 /**
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001448 * Returns the {@link Network} object currently serving a given type, or
1449 * null if the given type is not connected.
1450 *
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001451 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04001452 * @deprecated This method does not support multiple connected networks
1453 * of the same type. Use {@link #getAllNetworks} and
1454 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001455 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001456 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001457 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001458 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001459 public Network getNetworkForType(int networkType) {
1460 try {
1461 return mService.getNetworkForType(networkType);
1462 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001463 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001464 }
1465 }
1466
1467 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001468 * Returns an array of all {@link Network} currently tracked by the
1469 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001470 *
1471 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001472 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001473 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001474 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001475 public Network[] getAllNetworks() {
1476 try {
1477 return mService.getAllNetworks();
1478 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001479 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001480 }
1481 }
1482
1483 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001484 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001485 * the Networks that applications run by the given user will use by default.
1486 * @hide
1487 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001488 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001489 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1490 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001491 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001492 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001493 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001494 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001495 }
1496 }
1497
1498 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001499 * Returns the IP information for the current default network.
1500 *
1501 * @return a {@link LinkProperties} object describing the IP info
1502 * for the current default network, or {@code null} if there
1503 * is no current default network.
1504 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001505 * {@hide}
Chalard Jeancc47b522019-01-11 16:47:53 +09001506 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1507 * value of {@link #getActiveNetwork()} instead. In particular,
1508 * this method will return non-null LinkProperties even if the
1509 * app is blocked by policy from using this network.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001510 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001511 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-01-11 16:47:53 +09001512 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001513 public LinkProperties getActiveLinkProperties() {
1514 try {
1515 return mService.getActiveLinkProperties();
1516 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001517 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001518 }
1519 }
1520
Robert Greenwalt26744a52013-02-15 10:56:35 -08001521 /**
1522 * Returns the IP information for a given network type.
1523 *
1524 * @param networkType the network type of interest.
1525 * @return a {@link LinkProperties} object describing the IP info
1526 * for the given networkType, or {@code null} if there is
1527 * no current default network.
1528 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001529 * {@hide}
Paul Jensena8e6dc62015-03-18 12:23:02 -04001530 * @deprecated This method does not support multiple connected networks
1531 * of the same type. Use {@link #getAllNetworks},
1532 * {@link #getNetworkInfo(android.net.Network)}, and
1533 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001534 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001535 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001536 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001537 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001538 public LinkProperties getLinkProperties(int networkType) {
1539 try {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001540 return mService.getLinkPropertiesForType(networkType);
1541 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001542 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001543 }
1544 }
1545
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001546 /**
1547 * Get the {@link LinkProperties} for the given {@link Network}. This
1548 * will return {@code null} if the network is unknown.
1549 *
1550 * @param network The {@link Network} object identifying the network in question.
1551 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001552 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001553 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001554 @Nullable
1555 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001556 try {
1557 return mService.getLinkProperties(network);
1558 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001559 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001560 }
1561 }
1562
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001563 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001564 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001565 * will return {@code null} if the network is unknown.
1566 *
Roshan Pius7992afd2020-12-22 15:10:42 -08001567 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1568 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1569 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1570 * this location sensitive information (subject to app's location permissions) will be
1571 * noted by system. To include any location sensitive data in {@link TransportInfo},
1572 * use a {@link NetworkCallback} with
1573 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1574 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001575 * @param network The {@link Network} object identifying the network in question.
Roshan Pius7992afd2020-12-22 15:10:42 -08001576 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001577 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001578 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001579 @Nullable
1580 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001581 try {
Roshan Piusc97d8062020-12-17 14:53:09 -08001582 return mService.getNetworkCapabilities(
1583 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001584 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001585 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001586 }
1587 }
1588
Robert Greenwalt26744a52013-02-15 10:56:35 -08001589 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001590 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001591 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1592 * portal is present.
1593 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1594 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1595 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001596 * The system network validation may be using different strategies to detect captive portals,
1597 * so this method does not necessarily return a URL used by the system. It only returns a URL
1598 * that may be relevant for other components trying to detect captive portals.
paulhuec0a9632019-08-12 16:25:11 +08001599 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001600 * @hide
paulhuec0a9632019-08-12 16:25:11 +08001601 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1602 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001603 */
paulhuec0a9632019-08-12 16:25:11 +08001604 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001605 @SystemApi
paulhuec0a9632019-08-12 16:25:11 +08001606 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001607 public String getCaptivePortalServerUrl() {
1608 try {
1609 return mService.getCaptivePortalServerUrl();
1610 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001611 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001612 }
1613 }
1614
1615 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001616 * Tells the underlying networking system that the caller wants to
1617 * begin using the named feature. The interpretation of {@code feature}
1618 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001619 *
1620 * <p>This method requires the caller to hold either the
1621 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1622 * or the ability to modify system settings as determined by
1623 * {@link android.provider.Settings.System#canWrite}.</p>
1624 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001625 * @param networkType specifies which network the request pertains to
1626 * @param feature the name of the feature to be used
1627 * @return an integer value representing the outcome of the request.
1628 * The interpretation of this value is specific to each networking
1629 * implementation+feature combination, except that the value {@code -1}
1630 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001631 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001632 * @deprecated Deprecated in favor of the cleaner
1633 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001634 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001635 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001636 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001637 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001638 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001639 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001640 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001641 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1642 if (netCap == null) {
1643 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1644 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001645 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001646 }
1647
1648 NetworkRequest request = null;
1649 synchronized (sLegacyRequests) {
1650 LegacyRequest l = sLegacyRequests.get(netCap);
1651 if (l != null) {
1652 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1653 renewRequestLocked(l);
1654 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001655 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001656 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001657 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001658 }
1659 }
1660
1661 request = requestNetworkForFeatureLocked(netCap);
1662 }
1663 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001664 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001665 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001666 } else {
1667 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001668 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001669 }
1670 }
1671
1672 /**
1673 * Tells the underlying networking system that the caller is finished
1674 * using the named feature. The interpretation of {@code feature}
1675 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001676 *
1677 * <p>This method requires the caller to hold either the
1678 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1679 * or the ability to modify system settings as determined by
1680 * {@link android.provider.Settings.System#canWrite}.</p>
1681 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001682 * @param networkType specifies which network the request pertains to
1683 * @param feature the name of the feature that is no longer needed
1684 * @return an integer value representing the outcome of the request.
1685 * The interpretation of this value is specific to each networking
1686 * implementation+feature combination, except that the value {@code -1}
1687 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001688 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001689 * @deprecated Deprecated in favor of the cleaner
1690 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001691 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001692 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001693 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001694 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001695 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001696 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001697 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001698 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1699 if (netCap == null) {
1700 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1701 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001702 return -1;
1703 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001704
Paul Jensen034dea32014-12-17 10:39:34 -05001705 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001706 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001707 }
1708 return 1;
1709 }
1710
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001711 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001712 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1713 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001714 switch (feature) {
1715 case "enableCBS":
1716 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1717 case "enableDUN":
1718 case "enableDUNAlways":
1719 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1720 case "enableFOTA":
1721 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1722 case "enableHIPRI":
1723 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1724 case "enableIMS":
1725 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1726 case "enableMMS":
1727 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1728 case "enableSUPL":
1729 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1730 default:
1731 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001732 }
Erik Kline50068e52017-01-26 18:08:28 +09001733 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1734 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001735 }
1736 return null;
1737 }
1738
Robert Greenwalt5a367872014-06-02 15:32:02 -07001739 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001740 if (netCap == null) return TYPE_NONE;
1741 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1742 return TYPE_MOBILE_CBS;
1743 }
1744 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1745 return TYPE_MOBILE_IMS;
1746 }
1747 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1748 return TYPE_MOBILE_FOTA;
1749 }
1750 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1751 return TYPE_MOBILE_DUN;
1752 }
1753 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1754 return TYPE_MOBILE_SUPL;
1755 }
1756 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1757 return TYPE_MOBILE_MMS;
1758 }
1759 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1760 return TYPE_MOBILE_HIPRI;
1761 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001762 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1763 return TYPE_WIFI_P2P;
1764 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001765 return TYPE_NONE;
1766 }
1767
1768 private static class LegacyRequest {
1769 NetworkCapabilities networkCapabilities;
1770 NetworkRequest networkRequest;
1771 int expireSequenceNumber;
1772 Network currentNetwork;
1773 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001774
1775 private void clearDnsBinding() {
1776 if (currentNetwork != null) {
1777 currentNetwork = null;
1778 setProcessDefaultNetworkForHostResolution(null);
1779 }
1780 }
1781
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001782 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001783 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001784 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001785 currentNetwork = network;
1786 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001787 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001788 }
1789 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001790 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001791 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001792 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1793 }
1794 };
1795 }
1796
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001797 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001798 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1799 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001800
1801 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1802 synchronized (sLegacyRequests) {
1803 LegacyRequest l = sLegacyRequests.get(netCap);
1804 if (l != null) return l.networkRequest;
1805 }
1806 return null;
1807 }
1808
1809 private void renewRequestLocked(LegacyRequest l) {
1810 l.expireSequenceNumber++;
1811 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1812 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1813 }
1814
1815 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1816 int ourSeqNum = -1;
1817 synchronized (sLegacyRequests) {
1818 LegacyRequest l = sLegacyRequests.get(netCap);
1819 if (l == null) return;
1820 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001821 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001822 }
1823 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1824 }
1825
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001826 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001827 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1828 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001829 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001830 try {
1831 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001832 } catch (RemoteException e) {
1833 throw e.rethrowFromSystemServer();
1834 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001835 LegacyRequest l = new LegacyRequest();
1836 l.networkCapabilities = netCap;
1837 l.delay = delay;
1838 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001839 l.networkRequest = sendRequestForNetwork(
1840 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001841 if (l.networkRequest == null) return null;
1842 sLegacyRequests.put(netCap, l);
1843 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1844 return l.networkRequest;
1845 }
1846
1847 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1848 if (delay >= 0) {
1849 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001850 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001851 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1852 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001853 }
1854 }
1855
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001856 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001857 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1858 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001859 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001860 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001861 }
Paul Jensen034dea32014-12-17 10:39:34 -05001862 if (l == null) return false;
1863 unregisterNetworkCallback(l.networkCallback);
1864 l.clearDnsBinding();
1865 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001866 }
1867
Erik Kline50068e52017-01-26 18:08:28 +09001868 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1869 static {
1870 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1871 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1872 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1873 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1874 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1875 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1876 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1877 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1878 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1879 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1880 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1881 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1882 }
1883
1884 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1885 static {
1886 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1887 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1888 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1889 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1890 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1891 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1892 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1893 }
1894
1895 /**
1896 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1897 * instance suitable for registering a request or callback. Throws an
1898 * IllegalArgumentException if no mapping from the legacy type to
1899 * NetworkCapabilities is known.
1900 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001901 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1902 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001903 * @hide
1904 */
1905 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1906 final NetworkCapabilities nc = new NetworkCapabilities();
1907
1908 // Map from type to transports.
1909 final int NOT_FOUND = -1;
1910 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001911 if (transport == NOT_FOUND) {
1912 throw new IllegalArgumentException("unknown legacy type: " + type);
1913 }
Erik Kline50068e52017-01-26 18:08:28 +09001914 nc.addTransportType(transport);
1915
1916 // Map from type to capabilities.
1917 nc.addCapability(sLegacyTypeToCapability.get(
1918 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1919 nc.maybeMarkCapabilitiesRestricted();
1920 return nc;
1921 }
1922
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001923 /** @hide */
1924 public static class PacketKeepaliveCallback {
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001925 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayevfc03a992019-11-15 19:12:49 +00001926 public PacketKeepaliveCallback() {
1927 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001928 /** The requested keepalive was successfully started. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001929 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001930 public void onStarted() {}
1931 /** The keepalive was successfully stopped. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001932 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001933 public void onStopped() {}
1934 /** An error occurred. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001935 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001936 public void onError(int error) {}
1937 }
1938
1939 /**
1940 * Allows applications to request that the system periodically send specific packets on their
1941 * behalf, using hardware offload to save battery power.
1942 *
1943 * To request that the system send keepalives, call one of the methods that return a
1944 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1945 * passing in a non-null callback. If the callback is successfully started, the callback's
1946 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1947 * specifying one of the {@code ERROR_*} constants in this class.
1948 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001949 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1950 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1951 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001952 *
junyulaia86defc2018-12-27 17:25:29 +08001953 * @deprecated Use {@link SocketKeepalive} instead.
1954 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001955 * @hide
1956 */
1957 public class PacketKeepalive {
1958
1959 private static final String TAG = "PacketKeepalive";
1960
1961 /** @hide */
1962 public static final int SUCCESS = 0;
1963
1964 /** @hide */
1965 public static final int NO_KEEPALIVE = -1;
1966
1967 /** @hide */
1968 public static final int BINDER_DIED = -10;
1969
1970 /** The specified {@code Network} is not connected. */
1971 public static final int ERROR_INVALID_NETWORK = -20;
1972 /** The specified IP addresses are invalid. For example, the specified source IP address is
1973 * not configured on the specified {@code Network}. */
1974 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1975 /** The requested port is invalid. */
1976 public static final int ERROR_INVALID_PORT = -22;
1977 /** The packet length is invalid (e.g., too long). */
1978 public static final int ERROR_INVALID_LENGTH = -23;
1979 /** The packet transmission interval is invalid (e.g., too short). */
1980 public static final int ERROR_INVALID_INTERVAL = -24;
1981
1982 /** The hardware does not support this request. */
1983 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001984 /** The hardware returned an error. */
1985 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001986
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001987 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001988 public static final int NATT_PORT = 4500;
1989
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001990 /** The minimum interval in seconds between keepalive packet transmissions */
1991 public static final int MIN_INTERVAL = 10;
1992
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001993 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001994 private final ISocketKeepaliveCallback mCallback;
1995 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001996
1997 private volatile Integer mSlot;
1998
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001999 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002000 public void stop() {
2001 try {
junyulai9f872232019-01-16 20:23:34 +08002002 mExecutor.execute(() -> {
2003 try {
2004 if (mSlot != null) {
2005 mService.stopKeepalive(mNetwork, mSlot);
2006 }
2007 } catch (RemoteException e) {
2008 Log.e(TAG, "Error stopping packet keepalive: ", e);
2009 throw e.rethrowFromSystemServer();
2010 }
2011 });
2012 } catch (RejectedExecutionException e) {
2013 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002014 }
2015 }
2016
2017 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002018 Objects.requireNonNull(network, "network cannot be null");
2019 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002020 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08002021 mExecutor = Executors.newSingleThreadExecutor();
2022 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002023 @Override
junyulai9f872232019-01-16 20:23:34 +08002024 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08002025 final long token = Binder.clearCallingIdentity();
2026 try {
2027 mExecutor.execute(() -> {
2028 mSlot = slot;
2029 callback.onStarted();
2030 });
2031 } finally {
2032 Binder.restoreCallingIdentity(token);
2033 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002034 }
junyulai9f872232019-01-16 20:23:34 +08002035
2036 @Override
2037 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08002038 final long token = Binder.clearCallingIdentity();
2039 try {
2040 mExecutor.execute(() -> {
2041 mSlot = null;
2042 callback.onStopped();
2043 });
2044 } finally {
2045 Binder.restoreCallingIdentity(token);
2046 }
junyulai9f872232019-01-16 20:23:34 +08002047 mExecutor.shutdown();
2048 }
2049
2050 @Override
2051 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08002052 final long token = Binder.clearCallingIdentity();
2053 try {
2054 mExecutor.execute(() -> {
2055 mSlot = null;
2056 callback.onError(error);
2057 });
2058 } finally {
2059 Binder.restoreCallingIdentity(token);
2060 }
junyulai9f872232019-01-16 20:23:34 +08002061 mExecutor.shutdown();
2062 }
2063
2064 @Override
2065 public void onDataReceived() {
2066 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2067 // this callback when data is received.
2068 }
2069 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002070 }
2071 }
2072
2073 /**
2074 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2075 *
junyulaia86defc2018-12-27 17:25:29 +08002076 * @deprecated Use {@link #createSocketKeepalive} instead.
2077 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002078 * @hide
2079 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002080 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002081 public PacketKeepalive startNattKeepalive(
2082 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2083 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2084 final PacketKeepalive k = new PacketKeepalive(network, callback);
2085 try {
junyulai9f872232019-01-16 20:23:34 +08002086 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002087 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2088 } catch (RemoteException e) {
2089 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08002090 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002091 }
2092 return k;
2093 }
2094
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002095 // Construct an invalid fd.
2096 private ParcelFileDescriptor createInvalidFd() {
2097 final int invalidFd = -1;
2098 return ParcelFileDescriptor.adoptFd(invalidFd);
2099 }
2100
The Android Open Source Project28527d22009-03-03 19:31:44 -08002101 /**
junyulaia86defc2018-12-27 17:25:29 +08002102 * Request that keepalives be started on a IPsec NAT-T socket.
2103 *
2104 * @param network The {@link Network} the socket is on.
2105 * @param socket The socket that needs to be kept alive.
2106 * @param source The source address of the {@link UdpEncapsulationSocket}.
2107 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2108 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2109 * must run callback sequentially, otherwise the order of callbacks cannot be
2110 * guaranteed.
2111 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2112 * changes. Must be extended by applications that use this API.
2113 *
junyulaic7ea1242019-01-08 20:04:33 +08002114 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2115 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08002116 **/
junyulai61143782019-03-04 22:45:36 +08002117 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08002118 @NonNull UdpEncapsulationSocket socket,
2119 @NonNull InetAddress source,
2120 @NonNull InetAddress destination,
2121 @NonNull @CallbackExecutor Executor executor,
2122 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002123 ParcelFileDescriptor dup;
2124 try {
junyulaic4fb2482019-03-27 11:00:37 +08002125 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2126 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08002127 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2128 } catch (IOException ignored) {
2129 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2130 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002131 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002132 }
2133 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2134 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08002135 }
2136
2137 /**
2138 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2139 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2140 *
2141 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08002142 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2143 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2144 * from that port.
junyulai48a59382019-01-15 11:32:44 +08002145 * @param source The source address of the {@link UdpEncapsulationSocket}.
2146 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2147 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2148 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2149 * must run callback sequentially, otherwise the order of callbacks cannot be
2150 * guaranteed.
2151 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2152 * changes. Must be extended by applications that use this API.
2153 *
junyulaic7ea1242019-01-08 20:04:33 +08002154 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2155 * given socket.
junyulai48a59382019-01-15 11:32:44 +08002156 * @hide
2157 */
2158 @SystemApi
2159 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002160 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2161 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08002162 @NonNull InetAddress source,
2163 @NonNull InetAddress destination,
2164 @NonNull @CallbackExecutor Executor executor,
2165 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002166 ParcelFileDescriptor dup;
2167 try {
junyulaic4fb2482019-03-27 11:00:37 +08002168 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08002169 dup = pfd.dup();
2170 } catch (IOException ignored) {
2171 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2172 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002173 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002174 }
2175 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VAN642d6ab2021-03-11 10:56:49 +00002176 -1 /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08002177 }
2178
2179 /**
junyulaic7ea1242019-01-08 20:04:33 +08002180 * Request that keepalives be started on a TCP socket.
2181 * The socket must be established.
2182 *
2183 * @param network The {@link Network} the socket is on.
2184 * @param socket The socket that needs to be kept alive.
2185 * @param executor The executor on which callback will be invoked. This implementation assumes
2186 * the provided {@link Executor} runs the callbacks in sequence with no
2187 * concurrency. Failing this, no guarantee of correctness can be made. It is
2188 * the responsibility of the caller to ensure the executor provides this
2189 * guarantee. A simple way of creating such an executor is with the standard
2190 * tool {@code Executors.newSingleThreadExecutor}.
2191 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2192 * changes. Must be extended by applications that use this API.
2193 *
2194 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2195 * given socket.
2196 * @hide
2197 */
2198 @SystemApi
2199 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002200 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002201 @NonNull Socket socket,
2202 @NonNull Executor executor,
2203 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002204 ParcelFileDescriptor dup;
2205 try {
2206 dup = ParcelFileDescriptor.fromSocket(socket);
2207 } catch (UncheckedIOException ignored) {
2208 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2209 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002210 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002211 }
2212 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002213 }
2214
2215 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002216 * Ensure that a network route exists to deliver traffic to the specified
2217 * host via the specified network interface. An attempt to add a route that
2218 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002219 *
2220 * <p>This method requires the caller to hold either the
2221 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2222 * or the ability to modify system settings as determined by
2223 * {@link android.provider.Settings.System#canWrite}.</p>
2224 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002225 * @param networkType the type of the network over which traffic to the specified
2226 * host is to be routed
2227 * @param hostAddress the IP address of the host to which the route is desired
2228 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002229 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002230 * @deprecated Deprecated in favor of the
2231 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2232 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002233 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002234 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002235 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002236 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002237 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002238 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002239 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002240 }
2241
2242 /**
2243 * Ensure that a network route exists to deliver traffic to the specified
2244 * host via the specified network interface. An attempt to add a route that
2245 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002246 *
2247 * <p>This method requires the caller to hold either the
2248 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2249 * or the ability to modify system settings as determined by
2250 * {@link android.provider.Settings.System#canWrite}.</p>
2251 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002252 * @param networkType the type of the network over which traffic to the specified
2253 * host is to be routed
2254 * @param hostAddress the IP address of the host to which the route is desired
2255 * @return {@code true} on success, {@code false} on failure
2256 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002257 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002258 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002259 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002260 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002261 @UnsupportedAppUsage
lucaslin5140e482021-03-22 11:51:27 +08002262 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002263 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002264 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002265 try {
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002266 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2267 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002268 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002269 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002270 }
2271 }
2272
2273 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002274 * @return the context's attribution tag
2275 */
2276 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2277 private @Nullable String getAttributionTag() {
2278 return mContext.getAttributionTag();
2279 }
2280
2281 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002282 * Returns the value of the setting for background data usage. If false,
2283 * applications should not use the network if the application is not in the
2284 * foreground. Developers should respect this setting, and check the value
2285 * of this before performing any background data operations.
2286 * <p>
2287 * All applications that have background services that use the network
2288 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002289 * <p>
Scott Main50589142011-10-06 18:32:43 -07002290 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002291 * background data depends on several combined factors, and this method will
2292 * always return {@code true}. Instead, when background data is unavailable,
2293 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002294 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002295 * @return Whether background data usage is allowed.
2296 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002297 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002298 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002299 // assume that background data is allowed; final authority is
2300 // NetworkInfo which may be blocked.
2301 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002302 }
2303
2304 /**
2305 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002306 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002307 * @param allowBackgroundData Whether an application should use data while
2308 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002309 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002310 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2311 * @see #getBackgroundDataSetting()
2312 * @hide
2313 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002314 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002315 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002316 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002317 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002318 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002319
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002320 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002321 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002322 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002323 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002324 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002325 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002326 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002327 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2328 if (tm != null) {
2329 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2330 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2331 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2332 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2333 + " retVal=" + retVal);
2334 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002335 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002336 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002337 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002338 }
2339
The Android Open Source Project28527d22009-03-03 19:31:44 -08002340 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002341 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002342 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002343 */
2344 public interface OnNetworkActiveListener {
2345 /**
2346 * Called on the main thread of the process to report that the current data network
2347 * has become active, and it is now a good time to perform any pending network
2348 * operations. Note that this listener only tells you when the network becomes
2349 * active; if at any other time you want to know whether it is active (and thus okay
2350 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002351 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002352 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002353 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002354 }
2355
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002356 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002357 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002358
2359 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002360 * Start listening to reports when the system's default data network is active, meaning it is
2361 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2362 * to determine the current state of the system's default network after registering the
2363 * listener.
2364 * <p>
2365 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002366 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002367 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002368 *
2369 * @param l The listener to be told when the network is active.
2370 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002371 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002372 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2373 @Override
2374 public void onNetworkActive() throws RemoteException {
2375 l.onNetworkActive();
2376 }
2377 };
2378
2379 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002380 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002381 mNetworkActivityListeners.put(l, rl);
2382 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002383 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002384 }
2385 }
2386
2387 /**
2388 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002389 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002390 *
2391 * @param l Previously registered listener.
2392 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002393 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002394 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002395 if (rl == null) {
2396 throw new IllegalArgumentException("Listener was not registered.");
2397 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002398 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002399 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002400 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002401 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002402 }
2403 }
2404
2405 /**
2406 * Return whether the data network is currently active. An active network means that
2407 * it is currently in a high power state for performing data transmission. On some
2408 * types of networks, it may be expensive to move and stay in such a state, so it is
2409 * more power efficient to batch network traffic together when the radio is already in
2410 * this state. This method tells you whether right now is currently a good time to
2411 * initiate network traffic, as the network is already active.
2412 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002413 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002414 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002415 return mService.isDefaultNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002416 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002417 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002418 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002419 }
2420
2421 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002422 * {@hide}
2423 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002424 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002425 mContext = Objects.requireNonNull(context, "missing context");
2426 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002427 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002428 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002429 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002430
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002431 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002432 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002433 public static ConnectivityManager from(Context context) {
2434 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2435 }
2436
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002437 /** @hide */
2438 public NetworkRequest getDefaultRequest() {
2439 try {
2440 // This is not racy as the default request is final in ConnectivityService.
2441 return mService.getDefaultRequest();
2442 } catch (RemoteException e) {
2443 throw e.rethrowFromSystemServer();
2444 }
2445 }
2446
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002447 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002448 * Check if the package is a allowed to write settings. This also accounts that such an access
2449 * happened.
2450 *
2451 * @return {@code true} iff the package is allowed to write settings.
2452 */
2453 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2454 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2455 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2456 boolean throwException) {
2457 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2458 callingAttributionTag, throwException);
2459 }
2460
2461 /**
Paul Jensen12131352014-12-10 15:12:18 -05002462 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2463 * situations where a Context pointer is unavailable.
2464 * @hide
2465 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002466 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002467 static ConnectivityManager getInstanceOrNull() {
2468 return sInstance;
2469 }
2470
2471 /**
2472 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2473 * situations where a Context pointer is unavailable.
2474 * @hide
2475 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002476 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002477 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002478 private static ConnectivityManager getInstance() {
2479 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002480 throw new IllegalStateException("No ConnectivityManager yet constructed");
2481 }
Paul Jensen895c3942015-03-10 10:54:12 -04002482 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002483 }
2484
2485 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002486 * Get the set of tetherable, available interfaces. This list is limited by
2487 * device configuration and current interface existence.
2488 *
2489 * @return an array of 0 or more Strings of tetherable interface names.
2490 *
markchien75721e42020-01-21 13:11:06 +08002491 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002492 * {@hide}
2493 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002494 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002495 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002496 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002497 public String[] getTetherableIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002498 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002499 }
2500
2501 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002502 * Get the set of tethered interfaces.
2503 *
2504 * @return an array of 0 or more String of currently tethered interface names.
2505 *
markchien75721e42020-01-21 13:11:06 +08002506 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002507 * {@hide}
2508 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002509 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002510 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002511 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002512 public String[] getTetheredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002513 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002514 }
2515
2516 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002517 * Get the set of interface names which attempted to tether but
2518 * failed. Re-attempting to tether may cause them to reset to the Tethered
2519 * state. Alternatively, causing the interface to be destroyed and recreated
2520 * may cause them to reset to the available state.
2521 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2522 * information on the cause of the errors.
2523 *
2524 * @return an array of 0 or more String indicating the interface names
2525 * which failed to tether.
2526 *
markchien75721e42020-01-21 13:11:06 +08002527 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002528 * {@hide}
2529 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002530 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002531 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002532 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002533 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002534 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002535 }
2536
2537 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002538 * Get the set of tethered dhcp ranges.
2539 *
markchien9e046242020-02-06 19:23:26 +08002540 * @deprecated This method is not supported.
2541 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002542 * {@hide}
2543 */
paulhuec0a9632019-08-12 16:25:11 +08002544 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien75721e42020-01-21 13:11:06 +08002545 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002546 public String[] getTetheredDhcpRanges() {
markchien9e046242020-02-06 19:23:26 +08002547 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002548 }
2549
2550 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002551 * Attempt to tether the named interface. This will setup a dhcp server
2552 * on the interface, forward and NAT IP packets and forward DNS requests
2553 * to the best active upstream network interface. Note that if no upstream
2554 * IP network interface is available, dhcp will still run and traffic will be
2555 * allowed between the tethered devices and this device, though upstream net
2556 * access will of course fail until an upstream network interface becomes
2557 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002558 *
2559 * <p>This method requires the caller to hold either the
2560 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2561 * or the ability to modify system settings as determined by
2562 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002563 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002564 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2565 * and WifiStateMachine which need direct access. All other clients should use
2566 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2567 * logic.</p>
2568 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002569 * @param iface the interface name to tether.
2570 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002571 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002572 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002573 * {@hide}
2574 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002575 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien10ddd022020-01-20 19:31:56 +08002576 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002577 public int tether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002578 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002579 }
2580
2581 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002582 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002583 *
2584 * <p>This method requires the caller to hold either the
2585 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2586 * or the ability to modify system settings as determined by
2587 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002588 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002589 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2590 * and WifiStateMachine which need direct access. All other clients should use
2591 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2592 * logic.</p>
2593 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002594 * @param iface the interface name to untether.
2595 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2596 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002597 * {@hide}
2598 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002599 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002600 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002601 public int untether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002602 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002603 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002604
2605 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002606 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002607 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002608 * due to device configuration.
2609 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002610 * <p>If this app does not have permission to use this API, it will always
2611 * return false rather than throw an exception.</p>
2612 *
2613 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2614 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2615 *
2616 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2617 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2618 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002619 * @return a boolean - {@code true} indicating Tethering is supported.
2620 *
markchien75721e42020-01-21 13:11:06 +08002621 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002622 * {@hide}
2623 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002624 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002625 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2626 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002627 public boolean isTetheringSupported() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002628 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002629 }
2630
2631 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002632 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien10ddd022020-01-20 19:31:56 +08002633 *
2634 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002635 * @hide
2636 */
2637 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002638 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002639 public static abstract class OnStartTetheringCallback {
2640 /**
2641 * Called when tethering has been successfully started.
2642 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002643 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002644
2645 /**
2646 * Called when starting tethering failed.
2647 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002648 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002649 }
2650
2651 /**
2652 * Convenient overload for
2653 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2654 * handler to run on the current thread's {@link Looper}.
markchien10ddd022020-01-20 19:31:56 +08002655 *
2656 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002657 * @hide
2658 */
2659 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002660 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002661 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002662 public void startTethering(int type, boolean showProvisioningUi,
2663 final OnStartTetheringCallback callback) {
2664 startTethering(type, showProvisioningUi, callback, null);
2665 }
2666
2667 /**
2668 * Runs tether provisioning for the given type if needed and then starts tethering if
2669 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2670 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2671 * schedules tether provisioning re-checks if appropriate.
2672 *
2673 * @param type The type of tethering to start. Must be one of
2674 * {@link ConnectivityManager.TETHERING_WIFI},
2675 * {@link ConnectivityManager.TETHERING_USB}, or
2676 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2677 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2678 * is one. This should be true the first time this function is called and also any time
2679 * the user can see this UI. It gives users information from their carrier about the
2680 * check failing and how they can sign up for tethering if possible.
2681 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2682 * of the result of trying to tether.
2683 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien10ddd022020-01-20 19:31:56 +08002684 *
2685 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002686 * @hide
2687 */
2688 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002689 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002690 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002691 public void startTethering(int type, boolean showProvisioningUi,
2692 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002693 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002694
markchien10ddd022020-01-20 19:31:56 +08002695 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002696 @Override
markchien10ddd022020-01-20 19:31:56 +08002697 public void execute(Runnable command) {
2698 if (handler == null) {
2699 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002700 } else {
markchien10ddd022020-01-20 19:31:56 +08002701 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002702 }
2703 }
2704 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002705
markchien10ddd022020-01-20 19:31:56 +08002706 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2707 @Override
2708 public void onTetheringStarted() {
2709 callback.onTetheringStarted();
2710 }
2711
2712 @Override
markchien68b67842020-03-19 13:37:43 +08002713 public void onTetheringFailed(final int error) {
markchien10ddd022020-01-20 19:31:56 +08002714 callback.onTetheringFailed();
2715 }
2716 };
2717
2718 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien68b67842020-03-19 13:37:43 +08002719 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien10ddd022020-01-20 19:31:56 +08002720
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002721 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002722 }
2723
2724 /**
2725 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2726 * applicable.
2727 *
2728 * @param type The type of tethering to stop. Must be one of
2729 * {@link ConnectivityManager.TETHERING_WIFI},
2730 * {@link ConnectivityManager.TETHERING_USB}, or
2731 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien75721e42020-01-21 13:11:06 +08002732 *
2733 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002734 * @hide
2735 */
2736 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002737 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002738 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002739 public void stopTethering(int type) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002740 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002741 }
2742
2743 /**
markchiena005c992019-02-27 14:56:11 +08002744 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2745 * upstream status.
2746 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002747 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien75721e42020-01-21 13:11:06 +08002748 * @hide
markchiena005c992019-02-27 14:56:11 +08002749 */
2750 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002751 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002752 public abstract static class OnTetheringEventCallback {
2753
2754 /**
2755 * Called when tethering upstream changed. This can be called multiple times and can be
2756 * called any time.
2757 *
2758 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2759 * have any upstream.
2760 */
2761 public void onUpstreamChanged(@Nullable Network network) {}
2762 }
2763
markchien75721e42020-01-21 13:11:06 +08002764 @GuardedBy("mTetheringEventCallbacks")
2765 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2766 mTetheringEventCallbacks = new ArrayMap<>();
2767
markchiena005c992019-02-27 14:56:11 +08002768 /**
2769 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002770 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002771 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2772 * with a null argument. The same callback object cannot be registered twice.
2773 *
2774 * @param executor the executor on which callback will be invoked.
2775 * @param callback the callback to be called when tethering has change events.
markchien75721e42020-01-21 13:11:06 +08002776 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002777 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002778 * @hide
2779 */
2780 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002781 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002782 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2783 public void registerTetheringEventCallback(
2784 @NonNull @CallbackExecutor Executor executor,
2785 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002786 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchiena005c992019-02-27 14:56:11 +08002787
markchien75721e42020-01-21 13:11:06 +08002788 final TetheringEventCallback tetherCallback =
2789 new TetheringEventCallback() {
2790 @Override
2791 public void onUpstreamChanged(@Nullable Network network) {
2792 callback.onUpstreamChanged(network);
2793 }
2794 };
2795
2796 synchronized (mTetheringEventCallbacks) {
2797 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002798 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002799 }
markchiena005c992019-02-27 14:56:11 +08002800 }
2801
2802 /**
2803 * Remove tethering event callback previously registered with
2804 * {@link #registerTetheringEventCallback}.
2805 *
2806 * @param callback previously registered callback.
markchien75721e42020-01-21 13:11:06 +08002807 *
2808 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002809 * @hide
2810 */
2811 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002812 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002813 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2814 public void unregisterTetheringEventCallback(
2815 @NonNull final OnTetheringEventCallback callback) {
markchien75721e42020-01-21 13:11:06 +08002816 Objects.requireNonNull(callback, "The callback must be non-null");
2817 synchronized (mTetheringEventCallbacks) {
2818 final TetheringEventCallback tetherCallback =
2819 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002820 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002821 }
markchiena005c992019-02-27 14:56:11 +08002822 }
2823
2824
2825 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002826 * Get the list of regular expressions that define any tetherable
2827 * USB network interfaces. If USB tethering is not supported by the
2828 * device, this list should be empty.
2829 *
2830 * @return an array of 0 or more regular expression Strings defining
2831 * what interfaces are considered tetherable usb interfaces.
2832 *
markchien75721e42020-01-21 13:11:06 +08002833 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002834 * {@hide}
2835 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002836 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002837 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002838 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002839 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002840 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002841 }
2842
2843 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002844 * Get the list of regular expressions that define any tetherable
2845 * Wifi network interfaces. If Wifi tethering is not supported by the
2846 * device, this list should be empty.
2847 *
2848 * @return an array of 0 or more regular expression Strings defining
2849 * what interfaces are considered tetherable wifi interfaces.
2850 *
markchien75721e42020-01-21 13:11:06 +08002851 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002852 * {@hide}
2853 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002854 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002855 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002856 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002857 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002858 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002859 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002860
Danica Chang96567052010-08-11 14:54:43 -07002861 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002862 * Get the list of regular expressions that define any tetherable
2863 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2864 * device, this list should be empty.
2865 *
2866 * @return an array of 0 or more regular expression Strings defining
2867 * what interfaces are considered tetherable bluetooth interfaces.
2868 *
markchien75721e42020-01-21 13:11:06 +08002869 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2870 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002871 * {@hide}
2872 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002873 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002874 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002875 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002876 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002877 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002878 }
2879
Mike Lockwooded4a1742011-07-19 13:04:47 -07002880 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002881 * Attempt to both alter the mode of USB and Tethering of USB. A
2882 * utility method to deal with some of the complexity of USB - will
2883 * attempt to switch to Rndis and subsequently tether the resulting
2884 * interface on {@code true} or turn off tethering and switch off
2885 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002886 *
2887 * <p>This method requires the caller to hold either the
2888 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2889 * or the ability to modify system settings as determined by
2890 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002891 *
2892 * @param enable a boolean - {@code true} to enable tethering
2893 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002894 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002895 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002896 * {@hide}
2897 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002898 @UnsupportedAppUsage
markchien10ddd022020-01-20 19:31:56 +08002899 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002900 public int setUsbTethering(boolean enable) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002901 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002902 }
2903
markchien75721e42020-01-21 13:11:06 +08002904 /**
2905 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2906 * {@hide}
2907 */
markchien5bd499c2019-01-16 17:44:13 +08002908 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002909 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002910 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien75721e42020-01-21 13:11:06 +08002911 /**
2912 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2913 * {@hide}
2914 */
2915 @Deprecated
2916 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2917 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2918 /**
2919 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2920 * {@hide}
2921 */
2922 @Deprecated
2923 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2924 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2925 /**
2926 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2927 * {@hide}
2928 */
2929 @Deprecated
2930 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2931 /**
2932 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2933 * {@hide}
2934 */
2935 @Deprecated
2936 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2937 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2938 /**
markchien68b67842020-03-19 13:37:43 +08002939 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002940 * {@hide}
2941 */
2942 @Deprecated
markchien68b67842020-03-19 13:37:43 +08002943 public static final int TETHER_ERROR_MASTER_ERROR =
2944 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien75721e42020-01-21 13:11:06 +08002945 /**
2946 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2947 * {@hide}
2948 */
2949 @Deprecated
2950 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2951 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2952 /**
2953 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2954 * {@hide}
2955 */
2956 @Deprecated
2957 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2958 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2959 /**
markchien68b67842020-03-19 13:37:43 +08002960 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002961 * {@hide}
2962 */
2963 @Deprecated
2964 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002965 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002966 /**
markchien68b67842020-03-19 13:37:43 +08002967 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002968 * {@hide}
2969 */
2970 @Deprecated
2971 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002972 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002973 /**
2974 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2975 * {@hide}
2976 */
2977 @Deprecated
2978 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2979 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2980 /**
markchien68b67842020-03-19 13:37:43 +08002981 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien75721e42020-01-21 13:11:06 +08002982 * {@hide}
2983 */
markchien5bd499c2019-01-16 17:44:13 +08002984 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002985 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002986 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien75721e42020-01-21 13:11:06 +08002987 /**
2988 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2989 * {@hide}
2990 */
2991 @Deprecated
2992 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2993 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2994 /**
2995 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2996 * {@hide}
2997 */
markchien5bd499c2019-01-16 17:44:13 +08002998 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002999 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09003000 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003001
3002 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003003 * Get a more detailed error code after a Tethering or Untethering
3004 * request asynchronously failed.
3005 *
3006 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003007 * @return error The error code of the last error tethering or untethering the named
3008 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08003009 *
markchien75721e42020-01-21 13:11:06 +08003010 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003011 * {@hide}
3012 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003013 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00003014 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien75721e42020-01-21 13:11:06 +08003015 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003016 public int getLastTetherError(String iface) {
markchien68b67842020-03-19 13:37:43 +08003017 int error = mTetheringManager.getLastTetherError(iface);
3018 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3019 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3020 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3021 // instead.
3022 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3023 }
3024 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003025 }
3026
markchiendd41c822019-03-06 16:25:00 +08003027 /** @hide */
3028 @Retention(RetentionPolicy.SOURCE)
3029 @IntDef(value = {
3030 TETHER_ERROR_NO_ERROR,
3031 TETHER_ERROR_PROVISION_FAILED,
3032 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3033 })
3034 public @interface EntitlementResultCode {
3035 }
3036
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003037 /**
markchiendd41c822019-03-06 16:25:00 +08003038 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08003039 * entitlement succeeded.
markchien75721e42020-01-21 13:11:06 +08003040 *
3041 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08003042 * @hide
3043 */
3044 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003045 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08003046 public interface OnTetheringEntitlementResultListener {
3047 /**
3048 * Called to notify entitlement result.
3049 *
3050 * @param resultCode an int value of entitlement result. It may be one of
3051 * {@link #TETHER_ERROR_NO_ERROR},
3052 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3053 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3054 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07003055 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08003056 }
3057
3058 /**
markchien5bd499c2019-01-16 17:44:13 +08003059 * Get the last value of the entitlement check on this downstream. If the cached value is
3060 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3061 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3062 * guaranteed that the UI-based entitlement check will complete in any specific time period
3063 * and may in fact never complete. Any successful entitlement check the platform performs for
3064 * any reason will update the cached value.
3065 *
3066 * @param type the downstream type of tethering. Must be one of
3067 * {@link #TETHERING_WIFI},
3068 * {@link #TETHERING_USB}, or
3069 * {@link #TETHERING_BLUETOOTH}.
3070 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08003071 * @param executor the executor on which callback will be invoked.
3072 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3073 * notify the caller of the result of entitlement check. The listener may be called zero
3074 * or one time.
markchien75721e42020-01-21 13:11:06 +08003075 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08003076 * {@hide}
3077 */
3078 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003079 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08003080 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08003081 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3082 @NonNull @CallbackExecutor Executor executor,
3083 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003084 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchiendd41c822019-03-06 16:25:00 +08003085 ResultReceiver wrappedListener = new ResultReceiver(null) {
3086 @Override
3087 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslin9cc04192021-03-04 09:38:21 +08003088 final long token = Binder.clearCallingIdentity();
3089 try {
3090 executor.execute(() -> {
3091 listener.onTetheringEntitlementResult(resultCode);
3092 });
3093 } finally {
3094 Binder.restoreCallingIdentity(token);
3095 }
markchiendd41c822019-03-06 16:25:00 +08003096 }
3097 };
3098
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00003099 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienb0bb7862019-12-16 20:15:20 +08003100 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08003101 }
3102
3103 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003104 * Report network connectivity status. This is currently used only
3105 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003106 * <p>This method requires the caller to hold the permission
3107 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003108 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003109 * @param networkType The type of network you want to report on
3110 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09003111 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003112 * {@hide}
3113 */
3114 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003115 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003116 try {
3117 mService.reportInetCondition(networkType, percentage);
3118 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003119 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003120 }
3121 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003122
3123 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003124 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07003125 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003126 * the framework to re-evaluate network connectivity and/or switch to another
3127 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003128 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003129 * @param network The {@link Network} the application was attempting to use
3130 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04003131 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3132 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003133 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003134 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09003135 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003136 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003137 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04003138 // One of these will be ignored because it matches system's current state.
3139 // The other will trigger the necessary reevaluation.
3140 mService.reportNetworkConnectivity(network, true);
3141 mService.reportNetworkConnectivity(network, false);
3142 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003143 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003144 }
3145 }
3146
3147 /**
3148 * Report to the framework whether a network has working connectivity.
3149 * This provides a hint to the system that a particular network is providing
3150 * working connectivity or not. In response the framework may re-evaluate
3151 * the network's connectivity and might take further action thereafter.
3152 *
3153 * @param network The {@link Network} the application was attempting to use
3154 * or {@code null} to indicate the current default network.
3155 * @param hasConnectivity {@code true} if the application was able to successfully access the
3156 * Internet using {@code network} or {@code false} if not.
3157 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003158 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003159 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003160 try {
3161 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003162 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003163 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003164 }
3165 }
3166
3167 /**
Chalard Jeanaac3b872021-03-17 17:03:34 +09003168 * Set a network-independent global HTTP proxy.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003169 *
Chalard Jeanaac3b872021-03-17 17:03:34 +09003170 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3171 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3172 * accessing any network, regardless of what the settings for that network are.
3173 *
3174 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3175 * proxy is likely to break networking on multiple networks. This method is only meant
3176 * for device policy clients looking to do general internal filtering or similar use cases.
3177 *
3178 * {@see #getGlobalProxy}
3179 * {@see LinkProperties#getHttpProxy}
3180 *
3181 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3182 * method with a {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003183 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003184 */
Chalard Jeanaac3b872021-03-17 17:03:34 +09003185 // Used by Device Policy Manager to set the global proxy.
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003186 @SystemApi(client = MODULE_LIBRARIES)
paulhuec0a9632019-08-12 16:25:11 +08003187 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeanaac3b872021-03-17 17:03:34 +09003188 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003189 try {
3190 mService.setGlobalProxy(p);
3191 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003192 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003193 }
3194 }
3195
3196 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003197 * Retrieve any network-independent global HTTP proxy.
3198 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003199 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003200 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003201 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003202 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003203 @SystemApi(client = MODULE_LIBRARIES)
3204 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04003205 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003206 try {
3207 return mService.getGlobalProxy();
3208 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003209 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003210 }
3211 }
3212
3213 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003214 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3215 * network-specific HTTP proxy. If {@code network} is null, the
3216 * network-specific proxy returned is the proxy of the default active
3217 * network.
3218 *
3219 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3220 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3221 * or when {@code network} is {@code null},
3222 * the {@code ProxyInfo} for the default active network. Returns
3223 * {@code null} when no proxy applies or the caller doesn't have
3224 * permission to use {@code network}.
3225 * @hide
3226 */
3227 public ProxyInfo getProxyForNetwork(Network network) {
3228 try {
3229 return mService.getProxyForNetwork(network);
3230 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003231 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003232 }
3233 }
3234
3235 /**
Paul Jensen12131352014-12-10 15:12:18 -05003236 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3237 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003238 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003239 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003240 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003241 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003242 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003243 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003244 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003245 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003246 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003247 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003248
3249 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003250 * Returns true if the hardware supports the given network type
3251 * else it returns false. This doesn't indicate we have coverage
3252 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003253 * hardware supports it. For example a GSM phone without a SIM
3254 * should still return {@code true} for mobile data, but a wifi only
3255 * tablet would return {@code false}.
3256 *
3257 * @param networkType The network type we'd like to check
3258 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003259 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003260 * @hide
3261 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003262 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003263 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003264 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003265 public boolean isNetworkSupported(int networkType) {
3266 try {
3267 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003268 } catch (RemoteException e) {
3269 throw e.rethrowFromSystemServer();
3270 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003271 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003272
3273 /**
3274 * Returns if the currently active data network is metered. A network is
3275 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003276 * that connection due to monetary costs, data limitations or
3277 * battery/performance issues. You should check this before doing large
3278 * data transfers, and warn the user or delay the operation until another
3279 * network is available.
3280 *
3281 * @return {@code true} if large transfers should be avoided, otherwise
3282 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003283 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003284 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003285 public boolean isActiveNetworkMetered() {
3286 try {
3287 return mService.isActiveNetworkMetered();
3288 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003289 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003290 }
3291 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003292
Robert Greenwalt26744a52013-02-15 10:56:35 -08003293 /**
Sarah Chincab74db2020-11-25 12:15:14 -08003294 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003295 *
Sarah Chincab74db2020-11-25 12:15:14 -08003296 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003297 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003298 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003299 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003300 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003301 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003302 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003303 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003304 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003305 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003306 }
3307 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003308
3309 /**
3310 * Set the value for enabling/disabling airplane mode
3311 *
3312 * @param enable whether to enable airplane mode or not
3313 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003314 * @hide
3315 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003316 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003317 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003318 android.Manifest.permission.NETWORK_SETTINGS,
3319 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3320 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003321 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003322 public void setAirplaneMode(boolean enable) {
3323 try {
3324 mService.setAirplaneMode(enable);
3325 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003326 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003327 }
3328 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003329
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003330 /**
3331 * Registers the specified {@link NetworkProvider}.
3332 * Each listener must only be registered once. The listener can be unregistered with
3333 * {@link #unregisterNetworkProvider}.
3334 *
3335 * @param provider the provider to register
3336 * @return the ID of the provider. This ID must be used by the provider when registering
3337 * {@link android.net.NetworkAgent}s.
3338 * @hide
3339 */
3340 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003341 @RequiresPermission(anyOf = {
3342 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3343 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003344 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3345 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003346 throw new IllegalStateException("NetworkProviders can only be registered once");
3347 }
3348
3349 try {
3350 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3351 provider.getName());
3352 provider.setProviderId(providerId);
3353 } catch (RemoteException e) {
3354 throw e.rethrowFromSystemServer();
3355 }
3356 return provider.getProviderId();
3357 }
3358
3359 /**
3360 * Unregisters the specified NetworkProvider.
3361 *
3362 * @param provider the provider to unregister
3363 * @hide
3364 */
3365 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003366 @RequiresPermission(anyOf = {
3367 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3368 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003369 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3370 try {
3371 mService.unregisterNetworkProvider(provider.getMessenger());
3372 } catch (RemoteException e) {
3373 throw e.rethrowFromSystemServer();
3374 }
3375 provider.setProviderId(NetworkProvider.ID_NONE);
3376 }
3377
Chalard Jean1ef1d902021-01-05 08:40:09 +09003378 /**
3379 * Register or update a network offer with ConnectivityService.
3380 *
3381 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jeand7268cd2021-03-24 17:43:10 +09003382 * them to networking requests made by apps or the system. A callback identifies an offer
3383 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3384 * score and the capabilities of the network it might be able to bring up ; these act as
3385 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jean1ef1d902021-01-05 08:40:09 +09003386 * provider.
3387 *
3388 * The provider is under no obligation to be able to bring up the network it offers at any
3389 * given time. Instead, this mechanism is meant to limit requests received by providers
3390 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3391 * the quality of the network satisfying a given request to their own offer.
3392 *
3393 * An offer can be updated by calling this again with the same callback object. This is
3394 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3395 * provider with the changes caused by the changes in the offer.
3396 *
3397 * @param provider The provider making this offer.
3398 * @param score The prospective score of the network.
3399 * @param caps The prospective capabilities of the network.
3400 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003401 * @hide exposed via the NetworkProvider class.
Chalard Jean1ef1d902021-01-05 08:40:09 +09003402 */
3403 @RequiresPermission(anyOf = {
3404 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3405 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanb004da52021-03-22 22:44:02 +09003406 public void offerNetwork(@NonNull final int providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09003407 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3408 @NonNull final INetworkOfferCallback callback) {
3409 try {
Chalard Jeanb004da52021-03-22 22:44:02 +09003410 mService.offerNetwork(providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09003411 Objects.requireNonNull(score, "null score"),
3412 Objects.requireNonNull(caps, "null caps"),
3413 Objects.requireNonNull(callback, "null callback"));
3414 } catch (RemoteException e) {
3415 throw e.rethrowFromSystemServer();
3416 }
3417 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003418
Chalard Jean1ef1d902021-01-05 08:40:09 +09003419 /**
3420 * Withdraw a network offer made with {@link #offerNetwork}.
3421 *
3422 * @param callback The callback passed at registration time. This must be the same object
3423 * that was passed to {@link #offerNetwork}
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003424 * @hide exposed via the NetworkProvider class.
Chalard Jean1ef1d902021-01-05 08:40:09 +09003425 */
3426 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3427 try {
3428 mService.unofferNetwork(Objects.requireNonNull(callback));
3429 } catch (RemoteException e) {
3430 throw e.rethrowFromSystemServer();
3431 }
3432 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003433 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003434 @RequiresPermission(anyOf = {
3435 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3436 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003437 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3438 try {
3439 mService.declareNetworkRequestUnfulfillable(request);
3440 } catch (RemoteException e) {
3441 throw e.rethrowFromSystemServer();
3442 }
3443 }
3444
Paul Jensenc2569432015-02-13 14:18:39 -05003445 /**
3446 * @hide
3447 * Register a NetworkAgent with ConnectivityService.
Chalard Jean1aea87a2019-12-13 19:47:12 +09003448 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003449 */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003450 @RequiresPermission(anyOf = {
3451 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3452 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003453 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeandd753522020-12-21 18:36:52 +09003454 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3455 int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003456 try {
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003457 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003458 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003459 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003460 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003461 }
3462
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003463 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003464 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3465 * changes. Should be extended by applications wanting notifications.
3466 *
3467 * A {@code NetworkCallback} is registered by calling
3468 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3469 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003470 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003471 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3472 * A {@code NetworkCallback} should be registered at most once at any time.
3473 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003474 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003475 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003476 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003477 * No flags associated with this callback.
3478 * @hide
3479 */
3480 public static final int FLAG_NONE = 0;
3481 /**
3482 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3483 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3484 * <p>
3485 * These include:
3486 * <li> Some transport info instances (retrieved via
3487 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3488 * contain location sensitive information.
3489 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3490 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3491 * </p>
3492 * <p>
3493 * Note:
3494 * <li> Retrieving this location sensitive information (subject to app's location
3495 * permissions) will be noted by system. </li>
3496 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3497 * not include location sensitive info.
3498 * </p>
3499 */
Roshan Piusf75ffaa2021-03-11 21:16:44 -08003500 // Note: Some existing fields which are location sensitive may still be included without
3501 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Pius7992afd2020-12-22 15:10:42 -08003502 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3503
3504 /** @hide */
3505 @Retention(RetentionPolicy.SOURCE)
3506 @IntDef(flag = true, prefix = "FLAG_", value = {
3507 FLAG_NONE,
3508 FLAG_INCLUDE_LOCATION_INFO
3509 })
3510 public @interface Flag { }
3511
3512 /**
3513 * All the valid flags for error checking.
3514 */
3515 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3516
3517 public NetworkCallback() {
3518 this(FLAG_NONE);
3519 }
3520
3521 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003522 if ((flags & VALID_FLAGS) != flags) {
3523 throw new IllegalArgumentException("Invalid flags");
3524 }
Roshan Pius7992afd2020-12-22 15:10:42 -08003525 mFlags = flags;
3526 }
3527
3528 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003529 * Called when the framework connects to a new network to evaluate whether it satisfies this
3530 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3531 * callback. There is no guarantee that this new network will satisfy any requests, or that
3532 * the network will stay connected for longer than the time necessary to evaluate it.
3533 * <p>
3534 * Most applications <b>should not</b> act on this callback, and should instead use
3535 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3536 * the framework in properly evaluating the network &mdash; for example, an application that
3537 * can automatically log in to a captive portal without user intervention.
3538 *
3539 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003540 *
3541 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003542 */
paulhua9a6e2a2019-03-22 16:35:06 +08003543 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003544
3545 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003546 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003547 * This callback may be called more than once if the {@link Network} that is
3548 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003549 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003550 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003551 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3552 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003553 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003554 * @hide
3555 */
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003556 public final void onAvailable(@NonNull Network network,
paulhua9a6e2a2019-03-22 16:35:06 +08003557 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003558 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003559 // Internally only this method is called when a new network is available, and
3560 // it calls the callback in the same way and order that older versions used
3561 // to call so as not to change the behavior.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003562 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3563 onBlockedStatusChanged(network, blocked);
3564 }
3565
3566 /**
3567 * Legacy variant of onAvailable that takes a boolean blocked reason.
3568 *
3569 * This method has never been public API, but it's not final, so there may be apps that
3570 * implemented it and rely on it being called. Do our best not to break them.
3571 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3572 * this method is called. There does not seem to be a way to avoid this.
3573 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3574 *
3575 * @hide
3576 */
3577 public void onAvailable(@NonNull Network network,
3578 @NonNull NetworkCapabilities networkCapabilities,
3579 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003580 onAvailable(network);
3581 if (!networkCapabilities.hasCapability(
3582 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3583 onNetworkSuspended(network);
3584 }
3585 onCapabilitiesChanged(network, networkCapabilities);
3586 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003587 // No call to onBlockedStatusChanged here. That is done by the caller.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003588 }
3589
3590 /**
3591 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003592 *
3593 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3594 * be available at the same time, and onAvailable will be called for each of these as they
3595 * appear.
3596 *
3597 * <p>For callbacks registered with {@link #requestNetwork} and
3598 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3599 * is the new best network for this request and is now tracked by this callback ; this
3600 * callback will no longer receive method calls about other networks that may have been
3601 * passed to this method previously. The previously-best network may have disconnected, or
3602 * it may still be around and the newly-best network may simply be better.
3603 *
3604 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3605 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3606 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3607 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3608 *
3609 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3610 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3611 * this callback as this is prone to race conditions (there is no guarantee the objects
3612 * returned by these methods will be current). Instead, wait for a call to
3613 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3614 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3615 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003616 *
3617 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003618 */
paulhua9a6e2a2019-03-22 16:35:06 +08003619 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003620
3621 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003622 * Called when the network is about to be lost, typically because there are no outstanding
3623 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3624 * with the new replacement network for graceful handover. This method is not guaranteed
3625 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3626 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003627 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003628 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3629 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3630 * this callback as this is prone to race conditions ; calling these methods while in a
3631 * callback may return an outdated or even a null object.
3632 *
3633 * @param network The {@link Network} that is about to be lost.
3634 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3635 * connected for graceful handover; note that the network may still
3636 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003637 */
paulhua9a6e2a2019-03-22 16:35:06 +08003638 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003639
3640 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003641 * Called when a network disconnects or otherwise no longer satisfies this request or
3642 * callback.
3643 *
3644 * <p>If the callback was registered with requestNetwork() or
3645 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3646 * returned by onAvailable() when that network is lost and no other network satisfies
3647 * the criteria of the request.
3648 *
3649 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3650 * each network which no longer satisfies the criteria of the callback.
3651 *
3652 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3653 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3654 * this callback as this is prone to race conditions ; calling these methods while in a
3655 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003656 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003657 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003658 */
paulhua9a6e2a2019-03-22 16:35:06 +08003659 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003660
3661 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003662 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003663 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3664 * requested network request cannot be fulfilled (whether or not a timeout was
3665 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003666 * {@link NetworkRequest} will have already been removed and released, as if
3667 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003668 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003669 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003670
3671 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003672 * Called when the network corresponding to this request changes capabilities but still
3673 * satisfies the requested criteria.
3674 *
3675 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3676 * to be called immediately after {@link #onAvailable}.
3677 *
3678 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3679 * ConnectivityManager methods in this callback as this is prone to race conditions :
3680 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003681 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003682 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius7992afd2020-12-22 15:10:42 -08003683 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003684 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003685 */
paulhua9a6e2a2019-03-22 16:35:06 +08003686 public void onCapabilitiesChanged(@NonNull Network network,
3687 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003688
3689 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003690 * Called when the network corresponding to this request changes {@link LinkProperties}.
3691 *
3692 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3693 * to be called immediately after {@link #onAvailable}.
3694 *
3695 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3696 * ConnectivityManager methods in this callback as this is prone to race conditions :
3697 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003698 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003699 * @param network The {@link Network} whose link properties have changed.
3700 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003701 */
paulhua9a6e2a2019-03-22 16:35:06 +08003702 public void onLinkPropertiesChanged(@NonNull Network network,
3703 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003704
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003705 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003706 * Called when the network the framework connected to for this request suspends data
3707 * transmission temporarily.
3708 *
3709 * <p>This generally means that while the TCP connections are still live temporarily
3710 * network data fails to transfer. To give a specific example, this is used on cellular
3711 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3712 * means read operations on sockets on this network will block once the buffers are
3713 * drained, and write operations will block once the buffers are full.
3714 *
3715 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3716 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3717 * this callback as this is prone to race conditions (there is no guarantee the objects
3718 * returned by these methods will be current).
3719 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003720 * @hide
3721 */
paulhua9a6e2a2019-03-22 16:35:06 +08003722 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003723
3724 /**
3725 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003726 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3727 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003728
3729 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3730 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3731 * this callback as this is prone to race conditions : calling these methods while in a
3732 * callback may return an outdated or even a null object.
3733 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003734 * @hide
3735 */
paulhua9a6e2a2019-03-22 16:35:06 +08003736 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003737
junyulai5ab727b2018-08-07 19:50:45 +08003738 /**
3739 * Called when access to the specified network is blocked or unblocked.
3740 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003741 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3742 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3743 * this callback as this is prone to race conditions : calling these methods while in a
3744 * callback may return an outdated or even a null object.
3745 *
junyulai5ab727b2018-08-07 19:50:45 +08003746 * @param network The {@link Network} whose blocked status has changed.
3747 * @param blocked The blocked status of this {@link Network}.
3748 */
junyulai61143782019-03-04 22:45:36 +08003749 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003750
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003751 /**
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09003752 * Called when access to the specified network is blocked or unblocked, or the reason for
3753 * access being blocked changes.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003754 *
3755 * If a NetworkCallback object implements this method,
3756 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3757 *
3758 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3759 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3760 * this callback as this is prone to race conditions : calling these methods while in a
3761 * callback may return an outdated or even a null object.
3762 *
3763 * @param network The {@link Network} whose blocked status has changed.
3764 * @param blocked The blocked status of this {@link Network}.
3765 * @hide
3766 */
3767 @SystemApi(client = MODULE_LIBRARIES)
3768 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3769 onBlockedStatusChanged(network, blocked != 0);
3770 }
3771
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003772 private NetworkRequest networkRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -08003773 private final int mFlags;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003774 }
3775
Hugo Benichi145e3792017-05-11 13:16:17 +09003776 /**
3777 * Constant error codes used by ConnectivityService to communicate about failures and errors
3778 * across a Binder boundary.
3779 * @hide
3780 */
3781 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003782 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003783 }
3784
3785 /** @hide */
3786 public static class TooManyRequestsException extends RuntimeException {}
3787
3788 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3789 switch (e.errorCode) {
3790 case Errors.TOO_MANY_REQUESTS:
3791 return new TooManyRequestsException();
3792 default:
3793 Log.w(TAG, "Unknown service error code " + e.errorCode);
3794 return new RuntimeException(e);
3795 }
3796 }
3797
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003798 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003799 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003800 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003801 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003802 /** @hide arg1 = TTL */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003803 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003804 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003805 public static final int CALLBACK_LOST = 4;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003806 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003807 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003808 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003809 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003810 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003811 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003812 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003813 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003814 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003815 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003816 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003817 public static final int CALLBACK_RESUMED = 10;
junyulai5ab727b2018-08-07 19:50:45 +08003818 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003819 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003820
Erik Kline66721822015-11-25 12:49:38 +09003821 /** @hide */
3822 public static String getCallbackName(int whichCallback) {
3823 switch (whichCallback) {
3824 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3825 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3826 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3827 case CALLBACK_LOST: return "CALLBACK_LOST";
3828 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3829 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3830 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003831 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3832 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3833 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003834 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003835 default:
3836 return Integer.toString(whichCallback);
3837 }
3838 }
3839
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003840 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003841 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003842 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003843
Hugo Benichife3325f2016-07-06 22:53:17 +09003844 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003845 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003846 }
3847
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003848 CallbackHandler(Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003849 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003850 }
3851
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003852 @Override
3853 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003854 if (message.what == EXPIRE_LEGACY_REQUEST) {
3855 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3856 return;
3857 }
3858
3859 final NetworkRequest request = getObject(message, NetworkRequest.class);
3860 final Network network = getObject(message, Network.class);
3861 final NetworkCallback callback;
3862 synchronized (sCallbacks) {
3863 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003864 if (callback == null) {
3865 Log.w(TAG,
3866 "callback not found for " + getCallbackName(message.what) + " message");
3867 return;
3868 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003869 if (message.what == CALLBACK_UNAVAIL) {
3870 sCallbacks.remove(request);
3871 callback.networkRequest = ALREADY_UNREGISTERED;
3872 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003873 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003874 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003875 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003876 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003877
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003878 switch (message.what) {
3879 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003880 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003881 break;
3882 }
3883 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003884 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3885 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003886 callback.onAvailable(network, cap, lp, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003887 break;
3888 }
3889 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003890 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003891 break;
3892 }
3893 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003894 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003895 break;
3896 }
3897 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003898 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003899 break;
3900 }
3901 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003902 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3903 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003904 break;
3905 }
3906 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003907 LinkProperties lp = getObject(message, LinkProperties.class);
3908 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003909 break;
3910 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003911 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003912 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003913 break;
3914 }
3915 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003916 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003917 break;
3918 }
junyulai5ab727b2018-08-07 19:50:45 +08003919 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003920 callback.onBlockedStatusChanged(network, message.arg1);
junyulai5ab727b2018-08-07 19:50:45 +08003921 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003922 }
3923 }
3924
Hugo Benichife3325f2016-07-06 22:53:17 +09003925 private <T> T getObject(Message msg, Class<T> c) {
3926 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003927 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003928 }
3929
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003930 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003931 synchronized (sCallbacks) {
3932 if (sCallbackHandler == null) {
3933 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003934 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003935 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003936 }
3937 }
3938
Hugo Benichiec180d52017-02-03 14:18:44 +09003939 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3940 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003941
Lorenzo Colittib199b962021-03-12 22:48:07 +09003942 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3943 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3944 CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003945 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003946 checkCallbackNotNull(callback);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003947 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3948 throw new IllegalArgumentException("null NetworkCapabilities");
3949 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003950 final NetworkRequest request;
Roshan Piusd26ae412020-01-16 12:17:17 -08003951 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003952 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003953 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003954 if (callback.networkRequest != null
3955 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003956 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3957 // and requests (http://b/20701525).
3958 Log.e(TAG, "NetworkCallback was already registered");
3959 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003960 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003961 Binder binder = new Binder();
Roshan Pius7992afd2020-12-22 15:10:42 -08003962 final int callbackFlags = callback.mFlags;
junyulaid1a78162021-01-11 16:53:38 +08003963 if (reqType == LISTEN) {
Roshan Piusd26ae412020-01-16 12:17:17 -08003964 request = mService.listenForNetwork(
Roshan Pius7992afd2020-12-22 15:10:42 -08003965 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08003966 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003967 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003968 request = mService.requestNetwork(
Lorenzo Colittib199b962021-03-12 22:48:07 +09003969 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3970 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003971 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003972 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003973 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003974 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003975 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003976 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003977 } catch (RemoteException e) {
3978 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003979 } catch (ServiceSpecificException e) {
3980 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003981 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003982 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003983 }
3984
Lorenzo Colittib199b962021-03-12 22:48:07 +09003985 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3986 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3987 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3988 legacyType, handler);
3989 }
3990
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003991 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003992 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003993 *
markchien0fe11402020-03-18 21:16:15 +08003994 * This API is only for use in internal system code that requests networks with legacy type and
3995 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchien769c5752020-01-14 12:54:40 +08003996 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003997 *
markchien769c5752020-01-14 12:54:40 +08003998 * @param request {@link NetworkRequest} describing this request.
markchien769c5752020-01-14 12:54:40 +08003999 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4000 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4001 * be a positive value (i.e. >0).
4002 * @param legacyType to specify the network type(#TYPE_*).
4003 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien0fe11402020-03-18 21:16:15 +08004004 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4005 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09004006 *
4007 * @hide
4008 */
markchien769c5752020-01-14 12:54:40 +08004009 @SystemApi
markchien0fe11402020-03-18 21:16:15 +08004010 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09004011 public void requestNetwork(@NonNull NetworkRequest request,
markchien0fe11402020-03-18 21:16:15 +08004012 int timeoutMs, int legacyType, @NonNull Handler handler,
4013 @NonNull NetworkCallback networkCallback) {
4014 if (legacyType == TYPE_NONE) {
4015 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4016 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004017 CallbackHandler cbHandler = new CallbackHandler(handler);
4018 NetworkCapabilities nc = request.networkCapabilities;
4019 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09004020 }
4021
4022 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004023 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004024 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004025 * <p>This method will attempt to find the best network that matches the passed
4026 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4027 * criteria. The platform will evaluate which network is the best at its own discretion.
4028 * Throughput, latency, cost per byte, policy, user preference and other considerations
4029 * may be factored in the decision of what is considered the best network.
4030 *
4031 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4032 * matching this request, while always attempting to match the request to a better network if
4033 * possible. If a better match is found, the platform will switch this request to the now-best
4034 * network and inform the app of the newly best network by invoking
4035 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4036 * will not try to maintain any other network than the best one currently matching the request:
4037 * a network not matching any network request may be disconnected at any time.
4038 *
4039 * <p>For example, an application could use this method to obtain a connected cellular network
4040 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4041 * radio to consume additional power. Or, an application could inform the system that it wants
4042 * a network supporting sending MMSes and have the system let it know about the currently best
4043 * MMS-supporting network through the provided {@link NetworkCallback}.
4044 *
4045 * <p>The status of the request can be followed by listening to the various callbacks described
4046 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4047 * used to direct traffic to the network (although accessing some networks may be subject to
4048 * holding specific permissions). Callers will learn about the specific characteristics of the
4049 * network through
4050 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4051 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4052 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4053 * matching the request at any given time; therefore when a better network matching the request
4054 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4055 * with the new network after which no further updates are given about the previously-best
4056 * network, unless it becomes the best again at some later time. All callbacks are invoked
4057 * in order on the same thread, which by default is a thread created by the framework running
4058 * in the app.
4059 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4060 * callbacks are invoked.
4061 *
4062 * <p>This{@link NetworkRequest} will live until released via
4063 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4064 * which point the system may let go of the network at any time.
4065 *
4066 * <p>A version of this method which takes a timeout is
4067 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4068 * wait for a limited amount of time for the network to become unavailable.
4069 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004070 * <p>It is presently unsupported to request a network with mutable
4071 * {@link NetworkCapabilities} such as
4072 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4073 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4074 * as these {@code NetworkCapabilities} represent states that a particular
4075 * network may never attain, and whether a network will attain these states
4076 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09004077 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004078 *
4079 * <p>This method requires the caller to hold either the
4080 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4081 * or the ability to modify system settings as determined by
4082 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004083 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004084 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4085 * number of outstanding requests to 100 per app (identified by their UID), shared with
4086 * all variants of this method, of {@link #registerNetworkCallback} as well as
4087 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4088 * Requesting a network with this method will count toward this limit. If this limit is
4089 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4090 * make sure to unregister the callbacks with
4091 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4092 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004093 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004094 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4095 * the callback must not be shared - it uniquely specifies this request.
4096 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004097 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4098 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004099 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004100 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004101 public void requestNetwork(@NonNull NetworkRequest request,
4102 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004103 requestNetwork(request, networkCallback, getDefaultHandler());
4104 }
4105
4106 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004107 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004108 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004109 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4110 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004111 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004112 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004113 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4114 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004115 *
4116 * @param request {@link NetworkRequest} describing this request.
4117 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4118 * the callback must not be shared - it uniquely specifies this request.
4119 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004120 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004121 public void requestNetwork(@NonNull NetworkRequest request,
4122 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004123 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004124 NetworkCapabilities nc = request.networkCapabilities;
4125 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004126 }
4127
4128 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004129 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohen67e58a02017-03-01 12:47:28 -08004130 * by a timeout.
4131 *
4132 * This function behaves identically to the non-timed-out version
4133 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4134 * is not found within the given time (in milliseconds) the
4135 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4136 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4137 * not have to be released if timed-out (it is automatically released). Unregistering a
4138 * request that timed out is not an error.
4139 *
4140 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4141 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4142 * for that purpose. Calling this method will attempt to bring up the requested network.
4143 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004144 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004145 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4146 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08004147 *
4148 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004149 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4150 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004151 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4152 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4153 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08004154 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004155 public void requestNetwork(@NonNull NetworkRequest request,
4156 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004157 checkTimeout(timeoutMs);
markchien0fe11402020-03-18 21:16:15 +08004158 NetworkCapabilities nc = request.networkCapabilities;
4159 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4160 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004161 }
4162
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004163 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004164 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004165 * by a timeout.
4166 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004167 * This method behaves identically to
4168 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4169 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08004170 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004171 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004172 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4173 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004174 *
4175 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004176 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4177 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004178 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004179 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4180 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004181 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004182 public void requestNetwork(@NonNull NetworkRequest request,
4183 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004184 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004185 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004186 NetworkCapabilities nc = request.networkCapabilities;
4187 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004188 }
4189
4190 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004191 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004192 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004193 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08004194 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04004195 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4196 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004197 */
Erik Klinefb087f12014-11-19 12:12:24 +09004198 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004199
4200 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004201 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004202 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004203 * {@link android.content.Intent#getParcelableExtra(String)}.
4204 */
Erik Klinefb087f12014-11-19 12:12:24 +09004205 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004206
4207
4208 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004209 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004210 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08004211 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004212 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004213 * the request may outlive the calling application and get called back when a suitable
4214 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004215 * <p>
4216 * The operation is an Intent broadcast that goes to a broadcast receiver that
4217 * you registered with {@link Context#registerReceiver} or through the
4218 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4219 * <p>
4220 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09004221 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4222 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004223 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004224 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004225 * Intent to reserve the network or it will be released shortly after the Intent
4226 * is processed.
4227 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04004228 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004229 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004230 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004231 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08004232 * The request may be released normally by calling
4233 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004234 * <p>It is presently unsupported to request a network with either
4235 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4236 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4237 * as these {@code NetworkCapabilities} represent states that a particular
4238 * network may never attain, and whether a network will attain these states
4239 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09004240 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004241 *
Chalard Jean7f06b342020-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 #registerNetworkCallback} 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 {@link #unregisterNetworkCallback(PendingIntent)}
4249 * or {@link #releaseNetworkRequest(PendingIntent)}.
4250 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004251 * <p>This method requires the caller to hold either the
4252 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4253 * or the ability to modify system settings as determined by
4254 * {@link android.provider.Settings.System#canWrite}.</p>
4255 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004256 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004257 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004258 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08004259 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004260 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4261 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004262 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004263 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004264 public void requestNetwork(@NonNull NetworkRequest request,
4265 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004266 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004267 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004268 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004269 mService.pendingRequestForNetwork(
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07004270 request.networkCapabilities, operation, mContext.getOpPackageName(),
4271 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004272 } catch (RemoteException e) {
4273 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004274 } catch (ServiceSpecificException e) {
4275 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004276 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004277 }
4278
4279 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004280 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4281 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004282 * This method has the same behavior as
4283 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004284 * releasing network resources and disconnecting.
4285 *
4286 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4287 * PendingIntent passed to
4288 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4289 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4290 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004291 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004292 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004293 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004294 try {
4295 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004296 } catch (RemoteException e) {
4297 throw e.rethrowFromSystemServer();
4298 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004299 }
4300
Hugo Benichiff4bf602017-05-09 15:19:01 +09004301 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004302 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004303 }
4304
4305 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004306 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004307 }
4308
4309 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004310 if (timeoutMs <= 0) {
4311 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4312 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004313 }
4314
4315 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004316 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004317 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004318 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4319 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004320 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004321 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4322 * number of outstanding requests to 100 per app (identified by their UID), shared with
4323 * all variants of this method, of {@link #requestNetwork} as well as
4324 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4325 * Requesting a network with this method will count toward this limit. If this limit is
4326 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4327 * make sure to unregister the callbacks with
4328 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4329 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004330 * @param request {@link NetworkRequest} describing this request.
4331 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4332 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004333 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004334 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004335 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004336 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004337 public void registerNetworkCallback(@NonNull NetworkRequest request,
4338 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004339 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4340 }
4341
4342 /**
4343 * Registers to receive notifications about all networks which satisfy the given
4344 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004345 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4346 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004347 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004348 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4349 * number of outstanding requests to 100 per app (identified by their UID), shared with
4350 * all variants of this method, of {@link #requestNetwork} as well as
4351 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4352 * Requesting a network with this method will count toward this limit. If this limit is
4353 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4354 * make sure to unregister the callbacks with
4355 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4356 *
4357 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004358 * @param request {@link NetworkRequest} describing this request.
4359 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4360 * networks change state.
4361 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004362 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004363 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004364 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004365 public void registerNetworkCallback(@NonNull NetworkRequest request,
4366 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004367 CallbackHandler cbHandler = new CallbackHandler(handler);
4368 NetworkCapabilities nc = request.networkCapabilities;
4369 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004370 }
4371
4372 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004373 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4374 * {@link NetworkRequest}.
4375 *
4376 * This function behaves identically to the version that takes a NetworkCallback, but instead
4377 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4378 * the request may outlive the calling application and get called back when a suitable
4379 * network is found.
4380 * <p>
4381 * The operation is an Intent broadcast that goes to a broadcast receiver that
4382 * you registered with {@link Context#registerReceiver} or through the
4383 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4384 * <p>
4385 * The operation Intent is delivered with two extras, a {@link Network} typed
4386 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4387 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4388 * the original requests parameters.
4389 * <p>
4390 * If there is already a request for this Intent registered (with the equality of
4391 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4392 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4393 * <p>
4394 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004395 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004396 *
4397 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4398 * number of outstanding requests to 100 per app (identified by their UID), shared with
4399 * all variants of this method, of {@link #requestNetwork} as well as
4400 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4401 * Requesting a network with this method will count toward this limit. If this limit is
4402 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4403 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4404 * or {@link #releaseNetworkRequest(PendingIntent)}.
4405 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004406 * @param request {@link NetworkRequest} describing this request.
4407 * @param operation Action to perform when the network is available (corresponds
4408 * to the {@link NetworkCallback#onAvailable} call. Typically
4409 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004410 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004411 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004412 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004413 public void registerNetworkCallback(@NonNull NetworkRequest request,
4414 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004415 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004416 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004417 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004418 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004419 request.networkCapabilities, operation, mContext.getOpPackageName(),
4420 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004421 } catch (RemoteException e) {
4422 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004423 } catch (ServiceSpecificException e) {
4424 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004425 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004426 }
4427
4428 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004429 * Registers to receive notifications about changes in the application's default network. This
4430 * may be a physical network or a virtual network, such as a VPN that applies to the
4431 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004432 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004433 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004434 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4435 * number of outstanding requests to 100 per app (identified by their UID), shared with
4436 * all variants of this method, of {@link #requestNetwork} as well as
4437 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4438 * Requesting a network with this method will count toward this limit. If this limit is
4439 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4440 * make sure to unregister the callbacks with
4441 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4442 *
Erik Klinee0aed632016-03-16 15:31:39 +09004443 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004444 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004445 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004446 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004447 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004448 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004449 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004450 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4451 }
4452
4453 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004454 * Registers to receive notifications about changes in the application's default network. This
4455 * may be a physical network or a virtual network, such as a VPN that applies to the
4456 * application. The callbacks will continue to be called until either the application exits or
4457 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4458 *
4459 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4460 * number of outstanding requests to 100 per app (identified by their UID), shared with
4461 * all variants of this method, of {@link #requestNetwork} as well as
4462 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4463 * Requesting a network with this method will count toward this limit. If this limit is
4464 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4465 * make sure to unregister the callbacks with
4466 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4467 *
4468 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4469 * application's default network changes.
4470 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4471 * @throws RuntimeException if the app already has too many callbacks registered.
4472 */
4473 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4474 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4475 @NonNull Handler handler) {
Chiachang Wang2e98f6c2021-04-20 15:41:24 +08004476 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colittib199b962021-03-12 22:48:07 +09004477 }
4478
4479 /**
4480 * Registers to receive notifications about changes in the default network for the specified
4481 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4482 * UID. The callbacks will continue to be called until either the application exits or
4483 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4484 *
4485 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4486 * number of outstanding requests to 100 per app (identified by their UID), shared with
4487 * all variants of this method, of {@link #requestNetwork} as well as
4488 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4489 * Requesting a network with this method will count toward this limit. If this limit is
4490 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4491 * make sure to unregister the callbacks with
4492 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4493 *
4494 * @param uid the UID for which to track default network changes.
4495 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4496 * UID's default network changes.
4497 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4498 * @throws RuntimeException if the app already has too many callbacks registered.
4499 * @hide
4500 */
Lorenzo Colitti3949d6e2021-03-22 18:23:21 +09004501 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittib199b962021-03-12 22:48:07 +09004502 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4503 @RequiresPermission(anyOf = {
4504 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4505 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wang2e98f6c2021-04-20 15:41:24 +08004506 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colittib199b962021-03-12 22:48:07 +09004507 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004508 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colittib199b962021-03-12 22:48:07 +09004509 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004510 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4511 }
4512
4513 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004514 * Registers to receive notifications about changes in the system default network. The callbacks
4515 * will continue to be called until either the application exits or
4516 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004517 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004518 * This method should not be used to determine networking state seen by applications, because in
4519 * many cases, most or even all application traffic may not use the default network directly,
4520 * and traffic from different applications may go on different networks by default. As an
4521 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4522 * and not onto the system default network. Applications or system components desiring to do
4523 * determine network state as seen by applications should use other methods such as
4524 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4525 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004526 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4527 * number of outstanding requests to 100 per app (identified by their UID), shared with
4528 * all variants of this method, of {@link #requestNetwork} as well as
4529 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4530 * Requesting a network with this method will count toward this limit. If this limit is
4531 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4532 * make sure to unregister the callbacks with
4533 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4534 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004535 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4536 * system default network changes.
4537 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004538 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004539 *
4540 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004541 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004542 @SystemApi(client = MODULE_LIBRARIES)
4543 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4544 @RequiresPermission(anyOf = {
4545 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4546 android.Manifest.permission.NETWORK_SETTINGS})
4547 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004548 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004549 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004550 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004551 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004552 }
4553
4554 /**
junyulaibd622262021-03-15 11:48:48 +08004555 * Registers to receive notifications about the best matching network which satisfy the given
4556 * {@link NetworkRequest}. The callbacks will continue to be called until
4557 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4558 * called.
4559 *
4560 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4561 * number of outstanding requests to 100 per app (identified by their UID), shared with
4562 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4563 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4564 * Requesting a network with this method will count toward this limit. If this limit is
4565 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4566 * make sure to unregister the callbacks with
4567 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4568 *
4569 *
4570 * @param request {@link NetworkRequest} describing this request.
4571 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4572 * networks change state.
4573 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4574 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai6b0a6a22021-03-05 15:51:17 +08004575 */
junyulai6b0a6a22021-03-05 15:51:17 +08004576 @SuppressLint("ExecutorRegistration")
4577 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4578 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4579 final NetworkCapabilities nc = request.networkCapabilities;
4580 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai8cae3c72021-03-12 20:05:08 +08004581 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai6b0a6a22021-03-05 15:51:17 +08004582 }
4583
4584 /**
fenglu73169332015-04-21 17:12:05 -07004585 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4586 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4587 * network connection for updated bandwidth information. The caller will be notified via
4588 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004589 * method assumes that the caller has previously called
4590 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4591 * changes.
fenglu76564332015-03-20 11:29:56 -07004592 *
fenglu41808e82015-04-27 14:28:04 -07004593 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004594 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004595 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004596 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004597 try {
fenglu73169332015-04-21 17:12:05 -07004598 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004599 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004600 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004601 }
4602 }
4603
4604 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004605 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004606 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4607 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4608 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004609 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4610 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004611 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004612 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4613 * triggering it as soon as this call returns.
4614 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004615 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004616 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004617 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004618 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004619 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004620 final List<NetworkRequest> reqs = new ArrayList<>();
4621 // Find all requests associated to this callback and stop callback triggers immediately.
4622 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4623 synchronized (sCallbacks) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004624 if (networkCallback.networkRequest == null) {
4625 throw new IllegalArgumentException("NetworkCallback was not registered");
4626 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07004627 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4628 Log.d(TAG, "NetworkCallback was already unregistered");
4629 return;
4630 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004631 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4632 if (e.getValue() == networkCallback) {
4633 reqs.add(e.getKey());
4634 }
4635 }
4636 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4637 for (NetworkRequest r : reqs) {
4638 try {
4639 mService.releaseNetworkRequest(r);
4640 } catch (RemoteException e) {
4641 throw e.rethrowFromSystemServer();
4642 }
4643 // Only remove mapping if rpc was successful.
4644 sCallbacks.remove(r);
4645 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004646 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004647 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004648 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004649
4650 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004651 * Unregisters a callback previously registered via
4652 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4653 *
4654 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4655 * PendingIntent passed to
4656 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4657 * Cannot be null.
4658 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004659 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004660 releaseNetworkRequest(operation);
4661 }
4662
4663 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004664 * Informs the system whether it should switch to {@code network} regardless of whether it is
4665 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4666 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4667 * the system default network regardless of any other network that's currently connected. If
4668 * {@code always} is true, then the choice is remembered, so that the next time the user
4669 * connects to this network, the system will switch to it.
4670 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004671 * @param network The network to accept.
4672 * @param accept Whether to accept the network even if unvalidated.
4673 * @param always Whether to remember this choice in the future.
4674 *
4675 * @hide
4676 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004677 @SystemApi(client = MODULE_LIBRARIES)
4678 @RequiresPermission(anyOf = {
4679 android.Manifest.permission.NETWORK_SETTINGS,
4680 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4681 android.Manifest.permission.NETWORK_STACK,
4682 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4683 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004684 try {
4685 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004686 } catch (RemoteException e) {
4687 throw e.rethrowFromSystemServer();
4688 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004689 }
4690
4691 /**
lucaslin25a50472019-03-12 13:08:03 +08004692 * Informs the system whether it should consider the network as validated even if it only has
4693 * partial connectivity. If {@code accept} is true, then the network will be considered as
4694 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4695 * is remembered, so that the next time the user connects to this network, the system will
4696 * switch to it.
4697 *
4698 * @param network The network to accept.
4699 * @param accept Whether to consider the network as validated even if it has partial
4700 * connectivity.
4701 * @param always Whether to remember this choice in the future.
4702 *
4703 * @hide
4704 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004705 @SystemApi(client = MODULE_LIBRARIES)
4706 @RequiresPermission(anyOf = {
4707 android.Manifest.permission.NETWORK_SETTINGS,
4708 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4709 android.Manifest.permission.NETWORK_STACK,
4710 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4711 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4712 boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004713 try {
4714 mService.setAcceptPartialConnectivity(network, accept, always);
4715 } catch (RemoteException e) {
4716 throw e.rethrowFromSystemServer();
4717 }
4718 }
4719
4720 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004721 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4722 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4723 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4724 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4725 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004726 * @param network The network to accept.
4727 *
4728 * @hide
4729 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004730 @SystemApi(client = MODULE_LIBRARIES)
4731 @RequiresPermission(anyOf = {
4732 android.Manifest.permission.NETWORK_SETTINGS,
4733 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4734 android.Manifest.permission.NETWORK_STACK,
4735 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4736 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004737 try {
4738 mService.setAvoidUnvalidated(network);
4739 } catch (RemoteException e) {
4740 throw e.rethrowFromSystemServer();
4741 }
4742 }
4743
4744 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004745 * Requests that the system open the captive portal app on the specified network.
4746 *
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004747 * <p>This is to be used on networks where a captive portal was detected, as per
4748 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4749 *
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004750 * @param network The network to log into.
4751 *
4752 * @hide
4753 */
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004754 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4755 @RequiresPermission(anyOf = {
4756 android.Manifest.permission.NETWORK_SETTINGS,
4757 android.Manifest.permission.NETWORK_STACK,
4758 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4759 })
4760 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004761 try {
4762 mService.startCaptivePortalApp(network);
4763 } catch (RemoteException e) {
4764 throw e.rethrowFromSystemServer();
4765 }
4766 }
4767
4768 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004769 * Requests that the system open the captive portal app with the specified extras.
4770 *
4771 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4772 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004773 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004774 * @param appExtras Extras to include in the app start intent.
4775 * @hide
4776 */
4777 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004778 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004779 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004780 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004781 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004782 } catch (RemoteException e) {
4783 throw e.rethrowFromSystemServer();
4784 }
4785 }
4786
4787 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004788 * Determine whether the device is configured to avoid bad wifi.
4789 * @hide
4790 */
4791 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004792 @RequiresPermission(anyOf = {
4793 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4794 android.Manifest.permission.NETWORK_STACK})
4795 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004796 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004797 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004798 } catch (RemoteException e) {
4799 throw e.rethrowFromSystemServer();
4800 }
4801 }
4802
4803 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004804 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4805 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004806 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4807 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004808 *
4809 * An example of such an operation might be a time-sensitive foreground activity, such as a
4810 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4811 */
4812 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4813
4814 /**
4815 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4816 * a backup channel for traffic that is primarily going over another network.
4817 *
4818 * An example might be maintaining backup connections to peers or servers for the purpose of
4819 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4820 * on backup paths should be negligible compared to the traffic on the main path.
4821 */
4822 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4823
4824 /**
4825 * It is acceptable to use metered data to improve network latency and performance.
4826 */
4827 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4828
4829 /**
4830 * Return value to use for unmetered networks. On such networks we currently set all the flags
4831 * to true.
4832 * @hide
4833 */
4834 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4835 MULTIPATH_PREFERENCE_HANDOVER |
4836 MULTIPATH_PREFERENCE_RELIABILITY |
4837 MULTIPATH_PREFERENCE_PERFORMANCE;
4838
4839 /** @hide */
4840 @Retention(RetentionPolicy.SOURCE)
4841 @IntDef(flag = true, value = {
4842 MULTIPATH_PREFERENCE_HANDOVER,
4843 MULTIPATH_PREFERENCE_RELIABILITY,
4844 MULTIPATH_PREFERENCE_PERFORMANCE,
4845 })
4846 public @interface MultipathPreference {
4847 }
4848
4849 /**
4850 * Provides a hint to the calling application on whether it is desirable to use the
4851 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4852 * for multipath data transfer on this network when it is not the system default network.
4853 * Applications desiring to use multipath network protocols should call this method before
4854 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004855 *
4856 * @param network The network on which the application desires to use multipath data.
4857 * If {@code null}, this method will return the a preference that will generally
4858 * apply to metered networks.
4859 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4860 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004861 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004862 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004863 try {
4864 return mService.getMultipathPreference(network);
4865 } catch (RemoteException e) {
4866 throw e.rethrowFromSystemServer();
4867 }
4868 }
4869
4870 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004871 * Resets all connectivity manager settings back to factory defaults.
4872 * @hide
4873 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004874 @SystemApi(client = MODULE_LIBRARIES)
4875 @RequiresPermission(anyOf = {
4876 android.Manifest.permission.NETWORK_SETTINGS,
4877 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scottd3bb5082015-03-30 13:17:11 -07004878 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004879 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004880 mService.factoryReset();
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00004881 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004882 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004883 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004884 }
4885 }
4886
4887 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004888 * Binds the current process to {@code network}. All Sockets created in the future
4889 * (and not explicitly bound via a bound SocketFactory from
4890 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4891 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4892 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4893 * work and all host name resolutions will fail. This is by design so an application doesn't
4894 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4895 * To clear binding pass {@code null} for {@code network}. Using individually bound
4896 * Sockets created by Network.getSocketFactory().createSocket() and
4897 * performing network-specific host name resolutions via
4898 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004899 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004900 *
4901 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4902 * the current binding.
4903 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4904 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004905 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004906 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004907 // instantiated.
4908 return setProcessDefaultNetwork(network);
4909 }
4910
4911 /**
4912 * Binds the current process to {@code network}. All Sockets created in the future
4913 * (and not explicitly bound via a bound SocketFactory from
4914 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4915 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4916 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4917 * work and all host name resolutions will fail. This is by design so an application doesn't
4918 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4919 * To clear binding pass {@code null} for {@code network}. Using individually bound
4920 * Sockets created by Network.getSocketFactory().createSocket() and
4921 * performing network-specific host name resolutions via
4922 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4923 * {@code setProcessDefaultNetwork}.
4924 *
4925 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4926 * the current binding.
4927 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4928 * @deprecated This function can throw {@link IllegalStateException}. Use
4929 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4930 * is a direct replacement.
4931 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004932 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004933 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004934 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004935 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4936
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004937 if (netId != NETID_UNSET) {
4938 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004939 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004940
4941 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4942 return false;
4943 }
4944
4945 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004946 // Set HTTP proxy system properties to match network.
4947 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004948 try {
Remi NGUYEN VANa1860ff2021-02-03 10:18:20 +09004949 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004950 } catch (SecurityException e) {
4951 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4952 Log.e(TAG, "Can't set proxy properties", e);
4953 }
Paul Jensen99c36662014-08-27 12:38:45 -04004954 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN33e3abb2021-03-18 23:27:19 +09004955 InetAddressCompat.clearDnsCache();
Paul Jensen99c36662014-08-27 12:38:45 -04004956 // Must flush socket pool as idle sockets will be bound to previous network and may
4957 // cause subsequent fetches to be performed on old network.
4958 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004959 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004960
4961 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004962 }
4963
4964 /**
4965 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004966 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004967 *
4968 * @return {@code Network} to which this process is bound, or {@code null}.
4969 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004970 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004971 public Network getBoundNetworkForProcess() {
4972 // Forcing callers to call thru non-static function ensures ConnectivityManager
4973 // instantiated.
4974 return getProcessDefaultNetwork();
4975 }
4976
4977 /**
4978 * Returns the {@link Network} currently bound to this process via
4979 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4980 *
4981 * @return {@code Network} to which this process is bound, or {@code null}.
4982 * @deprecated Using this function can lead to other functions throwing
4983 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4984 * {@code getBoundNetworkForProcess} is a direct replacement.
4985 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004986 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004987 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004988 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004989 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004990 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004991 return new Network(netId);
4992 }
4993
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004994 private void unsupportedStartingFrom(int version) {
4995 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004996 // The getApplicationInfo() call we make below is not supported in system context. Let
4997 // the call through here, and rely on the fact that ConnectivityService will refuse to
4998 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004999 return;
5000 }
5001
5002 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5003 throw new UnsupportedOperationException(
5004 "This method is not supported in target SDK version " + version + " and above");
5005 }
5006 }
5007
5008 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5009 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08005010 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09005011 // remove these exemptions. Note that this check is not secure, and apps can still access these
5012 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5013 // so is unsupported and may break in the future. http://b/22728205
5014 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07005015 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09005016 }
5017
Paul Jensene98c6e02014-05-29 10:12:39 -04005018 /**
5019 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04005020 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04005021 *
5022 * @param network The {@link Network} to bind host resolutions from the current process to, or
5023 * {@code null} to clear the current binding.
5024 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5025 * @hide
5026 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5027 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07005028 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00005029 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04005030 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04005031 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09005032 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04005033 }
Felipe Lemed16384b2016-01-22 09:44:57 -08005034
5035 /**
5036 * Device is not restricting metered network activity while application is running on
5037 * background.
5038 */
5039 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5040
5041 /**
5042 * Device is restricting metered network activity while application is running on background,
5043 * but application is allowed to bypass it.
5044 * <p>
5045 * In this state, application should take action to mitigate metered network access.
5046 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5047 */
5048 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5049
5050 /**
5051 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08005052 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08005053 * In this state, application should not try to use the network while running on background,
5054 * because it would be denied.
5055 */
5056 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5057
Felipe Leme6a5b7692016-01-27 14:46:39 -08005058 /**
5059 * A change in the background metered network activity restriction has occurred.
5060 * <p>
5061 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5062 * applies to them.
5063 * <p>
5064 * This is only sent to registered receivers, not manifest receivers.
5065 */
5066 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5067 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5068 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5069
Felipe Leme1b42ef92016-01-25 11:48:04 -08005070 /** @hide */
5071 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08005072 @IntDef(flag = false, value = {
5073 RESTRICT_BACKGROUND_STATUS_DISABLED,
5074 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5075 RESTRICT_BACKGROUND_STATUS_ENABLED,
5076 })
Felipe Lemed16384b2016-01-22 09:44:57 -08005077 public @interface RestrictBackgroundStatus {
5078 }
5079
Felipe Lemed16384b2016-01-22 09:44:57 -08005080 /**
5081 * Determines if the calling application is subject to metered network restrictions while
5082 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07005083 *
5084 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5085 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5086 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08005087 */
5088 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5089 try {
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09005090 return mService.getRestrictBackgroundStatusByCaller();
Felipe Lemed16384b2016-01-22 09:44:57 -08005091 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07005092 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08005093 }
5094 }
Ricky Waid53cf002018-01-23 04:09:45 +00005095
5096 /**
5097 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00005098 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5099 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00005100 *
5101 * @return Hash of network watchlist config file. Null if config does not exist.
5102 */
Chalard Jean42a9c292019-01-07 19:26:34 +09005103 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00005104 public byte[] getNetworkWatchlistConfigHash() {
5105 try {
5106 return mService.getNetworkWatchlistConfigHash();
5107 } catch (RemoteException e) {
5108 Log.e(TAG, "Unable to get watchlist config hash");
5109 throw e.rethrowFromSystemServer();
5110 }
5111 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005112
5113 /**
5114 * Returns the {@code uid} of the owner of a network connection.
5115 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08005116 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5117 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005118 * @param local The local {@link InetSocketAddress} of a connection.
5119 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005120 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08005121 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5122 * android.os.Process#INVALID_UID} if the connection is not found.
5123 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5124 * user.
5125 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005126 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08005127 public int getConnectionOwnerUid(
5128 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005129 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5130 try {
5131 return mService.getConnectionOwnerUid(connectionInfo);
5132 } catch (RemoteException e) {
5133 throw e.rethrowFromSystemServer();
5134 }
5135 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09005136
5137 private void printStackTrace() {
5138 if (DEBUG) {
5139 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5140 final StringBuffer sb = new StringBuffer();
5141 for (int i = 3; i < callStack.length; i++) {
5142 final String stackTrace = callStack[i].toString();
5143 if (stackTrace == null || stackTrace.contains("android.os")) {
5144 break;
5145 }
5146 sb.append(" [").append(stackTrace).append("]");
5147 }
5148 Log.d(TAG, "StackLog:" + sb.toString());
5149 }
5150 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005151
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09005152 /** @hide */
5153 public TestNetworkManager startOrGetTestNetworkManager() {
5154 final IBinder tnBinder;
5155 try {
5156 tnBinder = mService.startOrGetTestNetworkService();
5157 } catch (RemoteException e) {
5158 throw e.rethrowFromSystemServer();
5159 }
5160
5161 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5162 }
5163
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09005164 /** @hide */
5165 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5166 return new ConnectivityDiagnosticsManager(mContext, mService);
5167 }
5168
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005169 /**
5170 * Simulates a Data Stall for the specified Network.
5171 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09005172 * <p>This method should only be used for tests.
5173 *
Remi NGUYEN VAN5738b862021-04-08 16:26:20 +09005174 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5175 * have the system behave as if it had happened, but does not actually stall connectivity.
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005176 *
5177 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN5738b862021-04-08 16:26:20 +09005178 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5179 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5180 * SystemClock.elapsedRealtime.
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005181 * @param network The Network for which a Data Stall is being simluated.
5182 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5183 * @throws SecurityException if the caller is not the owner of the given network.
5184 * @hide
5185 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09005186 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005187 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5188 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN5738b862021-04-08 16:26:20 +09005189 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005190 @NonNull Network network, @NonNull PersistableBundle extras) {
5191 try {
5192 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5193 } catch (RemoteException e) {
5194 e.rethrowFromSystemServer();
5195 }
5196 }
James Mattisdcea9fb2020-10-28 21:48:54 -07005197
Daniel Bright60f02ed2020-06-15 16:10:01 -07005198 @NonNull
5199 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5200
5201 /**
5202 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5203 * receive available QoS events related to the {@link Network} and local ip + port
5204 * specified within socketInfo.
5205 * <p/>
5206 * The same {@link QosCallback} must be unregistered before being registered a second time,
5207 * otherwise {@link QosCallbackRegistrationException} is thrown.
5208 * <p/>
5209 * This API does not, in itself, require any permission if called with a network that is not
5210 * restricted. However, the underlying implementation currently only supports the IMS network,
5211 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5212 * useful, because they'd never be called back on networks that they would have access to.
5213 *
5214 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5215 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5216 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5217 * @throws RuntimeException if the app already has too many callbacks registered.
5218 *
5219 * Exceptions after the time of registration is passed through
5220 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5221 *
5222 * @param socketInfo the socket information used to match QoS events
Daniel Bright60f02ed2020-06-15 16:10:01 -07005223 * @param executor The executor on which the callback will be invoked. The provided
5224 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Brightb953a3e2021-03-10 11:51:50 -08005225 * callbacks cannot be guaranteed.onQosCallbackRegistered
5226 * @param callback receives qos events that satisfy socketInfo
Daniel Bright60f02ed2020-06-15 16:10:01 -07005227 *
5228 * @hide
5229 */
5230 @SystemApi
5231 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Brightb953a3e2021-03-10 11:51:50 -08005232 @CallbackExecutor @NonNull final Executor executor,
5233 @NonNull final QosCallback callback) {
Daniel Bright60f02ed2020-06-15 16:10:01 -07005234 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005235 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Brightb953a3e2021-03-10 11:51:50 -08005236 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005237
5238 try {
5239 synchronized (mQosCallbackConnections) {
5240 if (getQosCallbackConnection(callback) == null) {
5241 final QosCallbackConnection connection =
5242 new QosCallbackConnection(this, callback, executor);
5243 mQosCallbackConnections.add(connection);
5244 mService.registerQosSocketCallback(socketInfo, connection);
5245 } else {
5246 Log.e(TAG, "registerQosCallback: Callback already registered");
5247 throw new QosCallbackRegistrationException();
5248 }
5249 }
5250 } catch (final RemoteException e) {
5251 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5252
5253 // The same unregister method method is called for consistency even though nothing
5254 // will be sent to the ConnectivityService since the callback was never successfully
5255 // registered.
5256 unregisterQosCallback(callback);
5257 e.rethrowFromSystemServer();
5258 } catch (final ServiceSpecificException e) {
5259 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5260 unregisterQosCallback(callback);
5261 throw convertServiceException(e);
5262 }
5263 }
5264
5265 /**
5266 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5267 * events once unregistered and can be registered a second time.
5268 * <p/>
5269 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5270 *
5271 * @param callback the callback being unregistered
5272 *
5273 * @hide
5274 */
5275 @SystemApi
5276 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5277 Objects.requireNonNull(callback, "The callback must be non-null");
5278 try {
5279 synchronized (mQosCallbackConnections) {
5280 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5281 if (connection != null) {
5282 connection.stopReceivingMessages();
5283 mService.unregisterQosCallback(connection);
5284 mQosCallbackConnections.remove(connection);
5285 } else {
5286 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5287 }
5288 }
5289 } catch (final RemoteException e) {
5290 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5291 e.rethrowFromSystemServer();
5292 }
5293 }
5294
5295 /**
5296 * Gets the connection related to the callback.
5297 *
5298 * @param callback the callback to look up
5299 * @return the related connection
5300 */
5301 @Nullable
5302 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5303 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5304 // Checking by reference here is intentional
5305 if (connection.getCallback() == callback) {
5306 return connection;
5307 }
5308 }
5309 return null;
5310 }
Junyu Lai23568a42021-01-19 11:10:56 +00005311
5312 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08005313 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Lai23568a42021-01-19 11:10:56 +00005314 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5315 * be used to request that the system provide a network without causing the network to be
5316 * in the foreground.
5317 *
5318 * <p>This method will attempt to find the best network that matches the passed
5319 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5320 * criteria. The platform will evaluate which network is the best at its own discretion.
5321 * Throughput, latency, cost per byte, policy, user preference and other considerations
5322 * may be factored in the decision of what is considered the best network.
5323 *
5324 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5325 * matching this request, while always attempting to match the request to a better network if
5326 * possible. If a better match is found, the platform will switch this request to the now-best
5327 * network and inform the app of the newly best network by invoking
5328 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5329 * will not try to maintain any other network than the best one currently matching the request:
5330 * a network not matching any network request may be disconnected at any time.
5331 *
5332 * <p>For example, an application could use this method to obtain a connected cellular network
5333 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5334 * radio to consume additional power. Or, an application could inform the system that it wants
5335 * a network supporting sending MMSes and have the system let it know about the currently best
5336 * MMS-supporting network through the provided {@link NetworkCallback}.
5337 *
5338 * <p>The status of the request can be followed by listening to the various callbacks described
5339 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5340 * used to direct traffic to the network (although accessing some networks may be subject to
5341 * holding specific permissions). Callers will learn about the specific characteristics of the
5342 * network through
5343 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5344 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5345 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5346 * matching the request at any given time; therefore when a better network matching the request
5347 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5348 * with the new network after which no further updates are given about the previously-best
5349 * network, unless it becomes the best again at some later time. All callbacks are invoked
5350 * in order on the same thread, which by default is a thread created by the framework running
5351 * in the app.
5352 *
5353 * <p>This{@link NetworkRequest} will live until released via
5354 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5355 * which point the system may let go of the network at any time.
5356 *
5357 * <p>It is presently unsupported to request a network with mutable
5358 * {@link NetworkCapabilities} such as
5359 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5360 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5361 * as these {@code NetworkCapabilities} represent states that a particular
5362 * network may never attain, and whether a network will attain these states
5363 * is unknown prior to bringing up the network so the framework does not
5364 * know how to go about satisfying a request with these capabilities.
5365 *
5366 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5367 * number of outstanding requests to 100 per app (identified by their UID), shared with
5368 * all variants of this method, of {@link #registerNetworkCallback} as well as
5369 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5370 * Requesting a network with this method will count toward this limit. If this limit is
5371 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5372 * make sure to unregister the callbacks with
5373 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5374 *
5375 * @param request {@link NetworkRequest} describing this request.
Junyu Lai23568a42021-01-19 11:10:56 +00005376 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5377 * the callback must not be shared - it uniquely specifies this request.
junyulai56ed9a32021-04-15 00:39:49 +08005378 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5379 * If null, the callback is invoked on the default internal Handler.
Junyu Lai23568a42021-01-19 11:10:56 +00005380 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5381 * @throws SecurityException if missing the appropriate permissions.
5382 * @throws RuntimeException if the app already has too many callbacks registered.
5383 *
5384 * @hide
5385 */
5386 @SystemApi(client = MODULE_LIBRARIES)
5387 @SuppressLint("ExecutorRegistration")
5388 @RequiresPermission(anyOf = {
5389 android.Manifest.permission.NETWORK_SETTINGS,
5390 android.Manifest.permission.NETWORK_STACK,
5391 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5392 })
5393 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai56ed9a32021-04-15 00:39:49 +08005394 @NonNull NetworkCallback networkCallback,
5395 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Junyu Lai23568a42021-01-19 11:10:56 +00005396 final NetworkCapabilities nc = request.networkCapabilities;
5397 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaif4bc12f2021-03-09 20:49:48 +08005398 TYPE_NONE, new CallbackHandler(handler));
Junyu Lai23568a42021-01-19 11:10:56 +00005399 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005400
5401 /**
James Mattis6e6fabf2021-01-10 14:24:24 -08005402 * Used by automotive devices to set the network preferences used to direct traffic at an
5403 * application level as per the given OemNetworkPreferences. An example use-case would be an
5404 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5405 * vehicle via a particular network.
5406 *
5407 * Calling this will overwrite the existing preference.
5408 *
5409 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5410 * @param executor the executor on which listener will be invoked.
5411 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5412 * communicate completion of setOemNetworkPreference(). This will only be
5413 * called once upon successful completion of setOemNetworkPreference().
5414 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5415 * @throws SecurityException if missing the appropriate permissions.
5416 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005417 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005418 */
James Mattis7a253542021-01-26 16:23:52 -08005419 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005420 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005421 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005422 @Nullable @CallbackExecutor final Executor executor,
Chalard Jeancc9ad152021-03-03 16:37:13 +09005423 @Nullable final Runnable listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08005424 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5425 if (null != listener) {
5426 Objects.requireNonNull(executor, "Executor must be non-null");
5427 }
Chalard Jeancc9ad152021-03-03 16:37:13 +09005428 final IOnCompleteListener listenerInternal = listener == null ? null :
5429 new IOnCompleteListener.Stub() {
James Mattis6e6fabf2021-01-10 14:24:24 -08005430 @Override
5431 public void onComplete() {
Chalard Jeancc9ad152021-03-03 16:37:13 +09005432 executor.execute(listener::run);
James Mattis6e6fabf2021-01-10 14:24:24 -08005433 }
5434 };
5435
5436 try {
5437 mService.setOemNetworkPreference(preference, listenerInternal);
5438 } catch (RemoteException e) {
5439 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5440 throw e.rethrowFromSystemServer();
5441 }
5442 }
lucaslin1a6095c2021-03-12 00:46:33 +08005443
Chalard Jean03433052021-02-25 17:23:40 +09005444 /**
5445 * Request that a user profile is put by default on a network matching a given preference.
5446 *
5447 * See the documentation for the individual preferences for a description of the supported
5448 * behaviors.
5449 *
5450 * @param profile the profile concerned.
5451 * @param preference the preference for this profile.
5452 * @param executor an executor to execute the listener on. Optional if listener is null.
5453 * @param listener an optional listener to listen for completion of the operation.
5454 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5455 * @throws SecurityException if missing the appropriate permissions.
5456 * @hide
5457 */
Chalard Jeancc9ad152021-03-03 16:37:13 +09005458 // This function is for establishing per-profile default networking and can only be called by
5459 // the device policy manager, running as the system server. It would make no sense to call it
5460 // on a context for a user because it does not establish a setting on behalf of a user, rather
5461 // it establishes a setting for a user on behalf of the DPM.
5462 @SuppressLint({"UserHandle"})
5463 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09005464 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5465 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5466 @ProfileNetworkPreference final int preference,
5467 @Nullable @CallbackExecutor final Executor executor,
5468 @Nullable final Runnable listener) {
5469 if (null != listener) {
5470 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5471 }
5472 final IOnCompleteListener proxy;
5473 if (null == listener) {
5474 proxy = null;
5475 } else {
5476 proxy = new IOnCompleteListener.Stub() {
5477 @Override
5478 public void onComplete() {
5479 executor.execute(listener::run);
5480 }
5481 };
5482 }
5483 try {
5484 mService.setProfileNetworkPreference(profile, preference, proxy);
5485 } catch (RemoteException e) {
5486 throw e.rethrowFromSystemServer();
5487 }
5488 }
5489
lucaslin1a6095c2021-03-12 00:46:33 +08005490 // The first network ID of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005491 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin1a6095c2021-03-12 00:46:33 +08005492 // The network ID range of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005493 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin1a6095c2021-03-12 00:46:33 +08005494
5495 /**
5496 * Get the network ID range reserved for IPSec tunnel interfaces.
5497 *
5498 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5499 * @hide
5500 */
5501 @SystemApi(client = MODULE_LIBRARIES)
5502 @NonNull
5503 public static Range<Integer> getIpSecNetIdRange() {
5504 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5505 }
lucaslin50205af2021-03-12 16:11:27 +08005506
5507 /**
5508 * Get private DNS mode from settings.
5509 *
lucaslin73c98602021-03-17 14:53:35 +08005510 * @param context The Context to query the private DNS mode from settings.
lucaslin50205af2021-03-12 16:11:27 +08005511 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5512 *
5513 * @hide
5514 */
5515 @SystemApi(client = MODULE_LIBRARIES)
5516 @NonNull
5517 @PrivateDnsMode
lucaslinacd3ded2021-03-16 17:11:14 +08005518 public static String getPrivateDnsMode(@NonNull Context context) {
5519 final ContentResolver cr = context.getContentResolver();
lucaslin50205af2021-03-12 16:11:27 +08005520 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5521 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5522 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5523 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5524 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5525 return mode;
5526 }
paulhu28321462021-03-25 12:36:56 +08005527
5528 /**
5529 * Set private DNS mode to settings.
5530 *
5531 * @param context The {@link Context} to set the private DNS mode.
5532 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5533 *
5534 * @hide
5535 */
5536 @SystemApi(client = MODULE_LIBRARIES)
5537 public static void setPrivateDnsMode(@NonNull Context context,
5538 @NonNull @PrivateDnsMode String mode) {
5539 if (!(mode == PRIVATE_DNS_MODE_OFF
5540 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5541 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5542 throw new IllegalArgumentException("Invalid private dns mode");
5543 }
5544 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5545 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005546}