blob: ff1e78f0326e9808257f178a5030c8b8d31c8a30 [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;
Artur Satayevb9ea02f2019-12-10 17:47:52 +000041import android.compat.annotation.UnsupportedAppUsage;
lucaslin50205af2021-03-12 16:11:27 +080042import android.content.ContentResolver;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070043import android.content.Context;
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -070044import android.content.Intent;
junyulaia86defc2018-12-27 17:25:29 +080045import android.net.IpSecManager.UdpEncapsulationSocket;
46import android.net.SocketKeepalive.Callback;
markchien10ddd022020-01-20 19:31:56 +080047import android.net.TetheringManager.StartTetheringCallback;
markchien75721e42020-01-21 13:11:06 +080048import android.net.TetheringManager.TetheringEventCallback;
markchien10ddd022020-01-20 19:31:56 +080049import android.net.TetheringManager.TetheringRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -080050import android.net.wifi.WifiNetworkSuggestion;
Robert Greenwalt2034b912009-08-12 16:08:25 -070051import android.os.Binder;
Mathew Inwoodac5968e2018-12-20 15:30:45 +000052import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070053import android.os.Build.VERSION_CODES;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080054import android.os.Bundle;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070055import android.os.Handler;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080056import android.os.IBinder;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070057import android.os.Looper;
58import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070059import android.os.Messenger;
junyulai61143782019-03-04 22:45:36 +080060import android.os.ParcelFileDescriptor;
Cody Kestingb5c7abd2020-04-15 12:33:28 -070061import android.os.PersistableBundle;
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +090062import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.os.RemoteException;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080064import android.os.ResultReceiver;
Hugo Benichi145e3792017-05-11 13:16:17 +090065import android.os.ServiceSpecificException;
Chalard Jean03433052021-02-25 17:23:40 +090066import android.os.UserHandle;
Jeff Sharkey971cd162011-08-29 16:02:57 -070067import android.provider.Settings;
Wink Saville02eb35c2014-12-05 11:10:30 -080068import android.telephony.SubscriptionManager;
Meng Wang91311c02019-11-18 17:10:00 -080069import android.telephony.TelephonyManager;
lucaslin50205af2021-03-12 16:11:27 +080070import android.text.TextUtils;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080071import android.util.ArrayMap;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070072import android.util.Log;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090073import android.util.Range;
Erik Kline50068e52017-01-26 18:08:28 +090074import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080075
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +090076import com.android.connectivity.aidl.INetworkAgent;
markchien75721e42020-01-21 13:11:06 +080077import com.android.internal.annotations.GuardedBy;
Robert Greenwalt3d6c9582014-05-21 20:04:36 -070078
Paul Jensen99c36662014-08-27 12:38:45 -040079import libcore.net.event.NetworkEventDispatcher;
80
junyulai61143782019-03-04 22:45:36 +080081import java.io.IOException;
82import java.io.UncheckedIOException;
Felipe Lemed16384b2016-01-22 09:44:57 -080083import java.lang.annotation.Retention;
84import java.lang.annotation.RetentionPolicy;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090085import java.net.DatagramSocket;
Jeremy Klein04863332015-12-28 15:11:58 -080086import java.net.InetAddress;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -070087import java.net.InetSocketAddress;
junyulaic7ea1242019-01-08 20:04:33 +080088import java.net.Socket;
Hugo Benichi45a49542017-03-06 09:17:06 +090089import java.util.ArrayList;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090090import java.util.Collection;
Jeremy Klein04863332015-12-28 15:11:58 -080091import java.util.HashMap;
Hugo Benichi45a49542017-03-06 09:17:06 +090092import java.util.List;
93import java.util.Map;
markchien75721e42020-01-21 13:11:06 +080094import java.util.Objects;
junyulaia86defc2018-12-27 17:25:29 +080095import java.util.concurrent.Executor;
junyulai9f872232019-01-16 20:23:34 +080096import java.util.concurrent.ExecutorService;
97import java.util.concurrent.Executors;
98import java.util.concurrent.RejectedExecutionException;
Jeremy Klein04863332015-12-28 15:11:58 -080099
The Android Open Source Project28527d22009-03-03 19:31:44 -0800100/**
101 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600102 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800103 * <p>
104 * The primary responsibilities of this class are to:
105 * <ol>
106 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
107 * <li>Send broadcast intents when network connectivity changes</li>
108 * <li>Attempt to "fail over" to another network when connectivity to a network
109 * is lost</li>
110 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
111 * state of the available networks</li>
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700112 * <li>Provide an API that allows applications to request and select networks for their data
113 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800114 * </ol>
115 */
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600116@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700117public class ConnectivityManager {
118 private static final String TAG = "ConnectivityManager";
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +0900119 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700120
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700122 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800123 * been established or lost. The NetworkInfo for the affected network is
124 * sent as an extra; it should be consulted to see what kind of
125 * connectivity event occurred.
126 * <p/>
Mark Lue1682a02016-12-05 10:57:55 -0800127 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
128 * broadcast if they declare the broadcast receiver in their manifest. Apps
129 * will still receive broadcasts if they register their
130 * {@link android.content.BroadcastReceiver} with
131 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
132 * and that context is still valid.
133 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800134 * If this is a connection that was the result of failing over from a
135 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
136 * set to true.
137 * <p/>
138 * For a loss of connectivity, if the connectivity manager is attempting
139 * to connect (or has already connected) to another network, the
140 * NetworkInfo for the new network is also passed as an extra. This lets
141 * any receivers of the broadcast know that they should not necessarily
142 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt26744a52013-02-15 10:56:35 -0800143 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800144 * the failover attempt succeeded (and so there is still overall data
145 * connectivity), or that the failover attempt failed, meaning that all
146 * connectivity has been lost.
147 * <p/>
148 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
149 * is set to {@code true} if there are no connected networks at all.
Chalard Jeanae2424a2018-02-10 05:33:50 +0900150 *
151 * @deprecated apps should use the more versatile {@link #requestNetwork},
152 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
153 * functions instead for faster and more detailed updates about the network
154 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800156 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jeanae2424a2018-02-10 05:33:50 +0900157 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700159
The Android Open Source Project28527d22009-03-03 19:31:44 -0800160 /**
Paul Jensened4d55c2015-02-27 22:55:47 -0500161 * The device has connected to a network that has presented a captive
162 * portal, which is blocking Internet connectivity. The user was presented
163 * with a notification that network sign in is required,
164 * and the user invoked the notification's action indicating they
Paul Jensen4173cce2015-05-22 10:50:39 -0400165 * desire to sign in to the network. Apps handling this activity should
Paul Jensened4d55c2015-02-27 22:55:47 -0500166 * facilitate signing in to the network. This action includes a
167 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
168 * the network presenting the captive portal; all communication with the
169 * captive portal must be done using this {@code Network} object.
170 * <p/>
Paul Jensen4173cce2015-05-22 10:50:39 -0400171 * This activity includes a {@link CaptivePortal} extra named
172 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
173 * outcomes of the captive portal sign in to the system:
174 * <ul>
175 * <li> When the app handling this action believes the user has signed in to
176 * the network and the captive portal has been dismissed, the app should
177 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
178 * reevaluate the network. If reevaluation finds the network no longer
179 * subject to a captive portal, the network may become the default active
Chalard Jean73d9db72018-06-04 16:52:49 +0900180 * data network.</li>
Paul Jensen4173cce2015-05-22 10:50:39 -0400181 * <li> When the app handling this action believes the user explicitly wants
Paul Jensened4d55c2015-02-27 22:55:47 -0500182 * to ignore the captive portal and the network, the app should call
Paul Jensen4173cce2015-05-22 10:50:39 -0400183 * {@link CaptivePortal#ignoreNetwork}. </li>
184 * </ul>
Paul Jensened4d55c2015-02-27 22:55:47 -0500185 */
186 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
187 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
188
189 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800190 * The lookup key for a {@link NetworkInfo} object. Retrieve with
191 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700192 *
Chalard Jeancc47b522019-01-11 16:47:53 +0900193 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
194 * can't accurately represent modern network characteristics.
195 * Please obtain information about networks from the {@link NetworkCapabilities}
196 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800197 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700198 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800199 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700200
The Android Open Source Project28527d22009-03-03 19:31:44 -0800201 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700202 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700203 *
204 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeancc47b522019-01-11 16:47:53 +0900205 * @deprecated The network type is not rich enough to represent the characteristics
206 * of modern networks. Please use {@link NetworkCapabilities} instead,
207 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700208 */
Chalard Jeancc47b522019-01-11 16:47:53 +0900209 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700210 public static final String EXTRA_NETWORK_TYPE = "networkType";
211
212 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800213 * The lookup key for a boolean that indicates whether a connect event
214 * is for a network to which the connectivity manager was failing over
215 * following a disconnect on another network.
216 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai5c2f6262018-12-13 12:47:51 +0800217 *
218 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800219 */
junyulai5c2f6262018-12-13 12:47:51 +0800220 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800221 public static final String EXTRA_IS_FAILOVER = "isFailover";
222 /**
223 * The lookup key for a {@link NetworkInfo} object. This is supplied when
224 * there is another network that it may be possible to connect to. Retrieve with
225 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800226 *
227 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800228 */
junyulai5c2f6262018-12-13 12:47:51 +0800229 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
231 /**
232 * The lookup key for a boolean that indicates whether there is a
233 * complete lack of connectivity, i.e., no network is available.
234 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
235 */
236 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
237 /**
238 * The lookup key for a string that indicates why an attempt to connect
239 * to a network failed. The string has no particular structure. It is
240 * intended to be used in notifications presented to users. Retrieve
241 * it with {@link android.content.Intent#getStringExtra(String)}.
242 */
243 public static final String EXTRA_REASON = "reason";
244 /**
245 * The lookup key for a string that provides optionally supplied
246 * extra information about the network state. The information
247 * may be passed up from the lower networking layers, and its
248 * meaning may be specific to a particular network type. Retrieve
249 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800250 *
251 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800252 */
junyulai5c2f6262018-12-13 12:47:51 +0800253 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800254 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700255 /**
256 * The lookup key for an int that provides information about
257 * our connection to the internet at large. 0 indicates no connection,
258 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700259 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700260 * {@hide}
261 */
262 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800263 /**
Paul Jensen4173cce2015-05-22 10:50:39 -0400264 * The lookup key for a {@link CaptivePortal} object included with the
265 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
266 * object can be used to either indicate to the system that the captive
267 * portal has been dismissed or that the user does not want to pursue
268 * signing in to captive portal. Retrieve it with
269 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensened4d55c2015-02-27 22:55:47 -0500270 */
Paul Jensen4173cce2015-05-22 10:50:39 -0400271 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist0f3b4442015-09-22 15:54:32 -0700272
273 /**
274 * Key for passing a URL to the captive portal login activity.
275 */
276 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
277
Paul Jensened4d55c2015-02-27 22:55:47 -0500278 /**
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900279 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
280 * portal login activity.
281 * {@hide}
282 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900283 @SystemApi
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900284 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
285 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
286
287 /**
Hugo Benichidce21c52016-12-14 08:23:40 +0900288 * Key for passing a user agent string to the captive portal login activity.
289 * {@hide}
290 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900291 @SystemApi
Hugo Benichidce21c52016-12-14 08:23:40 +0900292 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
293 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
294
295 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700296 * Broadcast action to indicate the change of data activity status
297 * (idle or active) on a network in a recent period.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800298 * The network becomes active when data transmission is started, or
299 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700300 * {@hide}
301 */
302 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean73d9db72018-06-04 16:52:49 +0900303 public static final String ACTION_DATA_ACTIVITY_CHANGE =
304 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700305 /**
306 * The lookup key for an enum that indicates the network device type on which this data activity
307 * change happens.
308 * {@hide}
309 */
310 public static final String EXTRA_DEVICE_TYPE = "deviceType";
311 /**
312 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
313 * it is actively sending or receiving data and {@code false} means it is idle.
314 * {@hide}
315 */
316 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma601fba92014-03-12 18:42:23 -0700317 /**
318 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
319 * {@hide}
320 */
321 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700322
323 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800324 * Broadcast Action: The setting for background data usage has changed
325 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
326 * <p>
327 * If an application uses the network in the background, it should listen
328 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700329 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800330 * <p>
331 *
332 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
333 * of background data depends on several combined factors, and
334 * this broadcast is no longer sent. Instead, when background
335 * data is unavailable, {@link #getActiveNetworkInfo()} will now
336 * appear disconnected. During first boot after a platform
337 * upgrade, this broadcast will be sent once if
338 * {@link #getBackgroundDataSetting()} was {@code false} before
339 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800340 */
341 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800342 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800343 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
344 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
345
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700346 /**
347 * Broadcast Action: The network connection may not be good
348 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
349 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
350 * the network and it's condition.
351 * @hide
352 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800353 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100354 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700355 public static final String INET_CONDITION_ACTION =
356 "android.net.conn.INET_CONDITION_ACTION";
357
Robert Greenwalt2034b912009-08-12 16:08:25 -0700358 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800359 * Broadcast Action: A tetherable connection has come or gone.
360 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline449ccfe2017-04-17 16:47:23 +0900361 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
362 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt26744a52013-02-15 10:56:35 -0800363 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
364 * the current state of tethering. Each include a list of
365 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800366 * @hide
367 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800368 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000369 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800370 public static final String ACTION_TETHER_STATE_CHANGED =
markchien1f523702019-12-25 19:40:32 +0800371 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800372
373 /**
374 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800375 * gives a String[] listing all the interfaces configured for
376 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800377 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000378 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800379 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800380
381 /**
382 * @hide
Erik Kline449ccfe2017-04-17 16:47:23 +0900383 * gives a String[] listing all the interfaces currently in local-only
384 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800385 */
markchien1f523702019-12-25 19:40:32 +0800386 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline449ccfe2017-04-17 16:47:23 +0900387
388 /**
389 * @hide
390 * gives a String[] listing all the interfaces currently tethered
391 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
392 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000393 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800394 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800395
396 /**
397 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800398 * gives a String[] listing all the interfaces we tried to tether and
399 * failed. Use {@link #getLastTetherError} to find the error code
400 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800401 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000402 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800403 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800404
405 /**
Russell Brenner4774b022013-02-12 10:03:14 -0800406 * Broadcast Action: The captive portal tracker has finished its test.
407 * Sent only while running Setup Wizard, in lieu of showing a user
408 * notification.
409 * @hide
410 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800411 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner4774b022013-02-12 10:03:14 -0800412 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
413 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
414 /**
415 * The lookup key for a boolean that indicates whether a captive portal was detected.
416 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
417 * @hide
418 */
419 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
420
421 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900422 * Action used to display a dialog that asks the user whether to connect to a network that is
423 * not validated. This intent is used to start the dialog in settings via startActivity.
424 *
425 * @hide
426 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800427 @SystemApi(client = MODULE_LIBRARIES)
428 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900429
430 /**
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900431 * Action used to display a dialog that asks the user whether to avoid a network that is no
432 * longer validated. This intent is used to start the dialog in settings via startActivity.
433 *
434 * @hide
435 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800436 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900437 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslin1a0ca5f2021-03-04 17:09:51 +0800438 "android.net.action.PROMPT_LOST_VALIDATION";
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900439
440 /**
lucaslin25a50472019-03-12 13:08:03 +0800441 * Action used to display a dialog that asks the user whether to stay connected to a network
442 * that has not validated. This intent is used to start the dialog in settings via
443 * startActivity.
444 *
445 * @hide
446 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800447 @SystemApi(client = MODULE_LIBRARIES)
lucaslin25a50472019-03-12 13:08:03 +0800448 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslin1a0ca5f2021-03-04 17:09:51 +0800449 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
lucaslin25a50472019-03-12 13:08:03 +0800450
451 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800452 * Invalid tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900453 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800454 * @hide
455 */
markchien1f523702019-12-25 19:40:32 +0800456 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800457
458 /**
459 * Wifi tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900460 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800461 * @hide
462 */
463 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900464 public static final int TETHERING_WIFI = 0;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800465
466 /**
467 * USB tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900468 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800469 * @hide
470 */
471 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900472 public static final int TETHERING_USB = 1;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800473
474 /**
475 * Bluetooth tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900476 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800477 * @hide
478 */
479 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900480 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800481
482 /**
Jimmy Chen87db1542019-07-15 18:03:23 +0800483 * Wifi P2p tethering type.
484 * Wifi P2p tethering is set through events automatically, and don't
485 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
486 * @hide
487 */
markchien1f523702019-12-25 19:40:32 +0800488 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chen87db1542019-07-15 18:03:23 +0800489
490 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800491 * Extra used for communicating with the TetherService. Includes the type of tethering to
492 * enable if any.
493 * @hide
494 */
markchien75721e42020-01-21 13:11:06 +0800495 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800496
497 /**
498 * Extra used for communicating with the TetherService. Includes the type of tethering for
499 * which to cancel provisioning.
500 * @hide
501 */
markchien75721e42020-01-21 13:11:06 +0800502 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800503
504 /**
505 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
506 * provisioning.
507 * @hide
508 */
markchien75721e42020-01-21 13:11:06 +0800509 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800510
511 /**
512 * Tells the TetherService to run a provision check now.
513 * @hide
514 */
markchien75721e42020-01-21 13:11:06 +0800515 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800516
517 /**
518 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
519 * which will receive provisioning results. Can be left empty.
520 * @hide
521 */
markchien75721e42020-01-21 13:11:06 +0800522 public static final String EXTRA_PROVISION_CALLBACK =
523 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800524
525 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800526 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700527 * @hide
528 */
paulhu62af6122020-01-13 16:46:45 +0800529 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700530 public static final int TYPE_NONE = -1;
531
532 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900533 * A Mobile data connection. Devices may support more than one.
534 *
535 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
536 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
537 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700538 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900539 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700540 public static final int TYPE_MOBILE = 0;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900541
Robert Greenwalt2034b912009-08-12 16:08:25 -0700542 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900543 * A WIFI data connection. Devices may support more than one.
544 *
545 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
546 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
547 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700548 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900549 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700550 public static final int TYPE_WIFI = 1;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900551
Robert Greenwalt2034b912009-08-12 16:08:25 -0700552 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800553 * An MMS-specific Mobile data connection. This network type may use the
554 * same network interface as {@link #TYPE_MOBILE} or it may use a different
555 * one. This is used by applications needing to talk to the carrier's
556 * Multimedia Messaging Service servers.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900557 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900558 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900559 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900560 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700561 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700562 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700563 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900564
Robert Greenwalt2034b912009-08-12 16:08:25 -0700565 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800566 * A SUPL-specific Mobile data connection. This network type may use the
567 * same network interface as {@link #TYPE_MOBILE} or it may use a different
568 * one. This is used by applications needing to talk to the carrier's
569 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900570 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900571 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900572 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900573 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700574 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700575 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700576 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900577
Robert Greenwalt2034b912009-08-12 16:08:25 -0700578 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800579 * A DUN-specific Mobile data connection. This network type may use the
580 * same network interface as {@link #TYPE_MOBILE} or it may use a different
581 * one. This is sometimes by the system when setting up an upstream connection
582 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900583 *
584 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
585 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
586 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700587 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900588 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700589 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900590
Robert Greenwalt2034b912009-08-12 16:08:25 -0700591 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800592 * A High Priority Mobile data connection. This network type uses the
593 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900594 * is different.
595 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900596 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
597 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
598 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700599 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700600 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700601 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900602
jshbfa81722010-03-11 15:04:43 -0800603 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900604 * A WiMAX data connection.
605 *
606 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
607 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
608 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800609 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900610 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800611 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800612
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800613 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900614 * A Bluetooth data connection.
615 *
616 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
617 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
618 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800619 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900620 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800621 public static final int TYPE_BLUETOOTH = 7;
622
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700623 /**
Chiachang Wang7d5f3782020-07-28 13:53:09 +0800624 * Fake data connection. This should not be used on shipping devices.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900625 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700626 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900627 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800628 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800629
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700630 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900631 * An Ethernet data connection.
632 *
633 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
634 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
635 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700636 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900637 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800638 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700639
Wink Savilleb7c92c72011-03-12 14:52:01 -0800640 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800641 * Over the air Administration.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900642 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800643 * {@hide}
644 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900645 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900646 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800647 public static final int TYPE_MOBILE_FOTA = 10;
648
649 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800650 * IP Multimedia Subsystem.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900651 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800652 * {@hide}
653 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900654 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100655 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800656 public static final int TYPE_MOBILE_IMS = 11;
657
658 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800659 * Carrier Branded Services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900660 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800661 * {@hide}
662 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900663 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900664 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800665 public static final int TYPE_MOBILE_CBS = 12;
666
repo syncf5de5572011-07-29 23:55:49 -0700667 /**
668 * A Wi-Fi p2p connection. Only requesting processes will have access to
669 * the peers connected.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900670 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700671 * {@hide}
672 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900673 @Deprecated
paulhu028732e2020-01-15 15:38:23 +0800674 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700675 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800676
Wink Saville70dbdcc2013-07-29 15:00:57 -0700677 /**
678 * The network to use for initially attaching to the network
Chalard Jean5acb7b72018-03-08 13:54:53 +0900679 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville70dbdcc2013-07-29 15:00:57 -0700680 * {@hide}
681 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900682 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100683 @UnsupportedAppUsage
Wink Saville70dbdcc2013-07-29 15:00:57 -0700684 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700685
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900686 /**
Robert Greenwalt9db5f3c2015-07-09 14:49:35 -0700687 * Emergency PDN connection for emergency services. This
688 * may include IMS and MMS in emergency situations.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900689 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram201d45f2014-06-26 11:03:44 -0700690 * {@hide}
691 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900692 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900693 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram201d45f2014-06-26 11:03:44 -0700694 public static final int TYPE_MOBILE_EMERGENCY = 15;
695
Hui Lu07f29332014-01-15 11:05:36 -0500696 /**
697 * The network that uses proxy to achieve connectivity.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900698 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu07f29332014-01-15 11:05:36 -0500699 * {@hide}
700 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900701 @Deprecated
Remi NGUYEN VANdaeafee2020-11-30 19:23:45 +0900702 @SystemApi
Hui Lu07f29332014-01-15 11:05:36 -0500703 public static final int TYPE_PROXY = 16;
Wink Saville70dbdcc2013-07-29 15:00:57 -0700704
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700705 /**
706 * A virtual network using one or more native bearers.
707 * It may or may not be providing security services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900708 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700709 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900710 @Deprecated
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700711 public static final int TYPE_VPN = 17;
Hui Lu07f29332014-01-15 11:05:36 -0500712
Benedict Wong80156022018-11-14 17:40:55 -0800713 /**
714 * A network that is exclusively meant to be used for testing
715 *
716 * @deprecated Use {@link NetworkCapabilities} instead.
717 * @hide
718 */
719 @Deprecated
720 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700721
Chalard Jean74fe1c72020-03-25 01:24:04 +0900722 /**
723 * @deprecated Use {@link NetworkCapabilities} instead.
724 * @hide
725 */
726 @Deprecated
727 @Retention(RetentionPolicy.SOURCE)
728 @IntDef(prefix = { "TYPE_" }, value = {
729 TYPE_NONE,
730 TYPE_MOBILE,
731 TYPE_WIFI,
732 TYPE_MOBILE_MMS,
733 TYPE_MOBILE_SUPL,
734 TYPE_MOBILE_DUN,
735 TYPE_MOBILE_HIPRI,
736 TYPE_WIMAX,
737 TYPE_BLUETOOTH,
738 TYPE_DUMMY,
739 TYPE_ETHERNET,
740 TYPE_MOBILE_FOTA,
741 TYPE_MOBILE_IMS,
742 TYPE_MOBILE_CBS,
743 TYPE_WIFI_P2P,
744 TYPE_MOBILE_IA,
745 TYPE_MOBILE_EMERGENCY,
746 TYPE_PROXY,
747 TYPE_VPN,
748 TYPE_TEST
749 })
750 public @interface LegacyNetworkType {}
751
Chalard Jean1f42df12019-11-21 14:48:00 +0900752 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
753 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
754 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
755 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
756 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
757
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700758 /** {@hide} */
Benedict Wong80156022018-11-14 17:40:55 -0800759 public static final int MAX_RADIO_TYPE = TYPE_TEST;
760
761 /** {@hide} */
762 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800763
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900764 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
765
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800766 /**
767 * If you want to set the default network preference,you can directly
768 * change the networkAttributes array in framework's config.xml.
769 *
770 * @deprecated Since we support so many more networks now, the single
771 * network default network preference can't really express
Robert Greenwalt26744a52013-02-15 10:56:35 -0800772 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800773 * networkAttributes in config.xml. You can determine
Robert Greenwalt1ee3d2c2012-12-07 09:56:50 -0800774 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800775 * from an App.
776 */
777 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800778 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
779
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700780 /**
Robert Greenwalta1402df2014-03-19 17:56:12 -0700781 * @hide
782 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900783 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltc34f83b2014-06-08 16:42:59 -0700784
Paul Jensen0478ace2014-07-11 12:28:19 -0400785 /**
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900786 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
787 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean73d9db72018-06-04 16:52:49 +0900788 * registered from those that were already unregistered.
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900789 * @hide
790 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900791 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900792 new NetworkRequest.Builder().clearCapabilities().build();
793
794 /**
Paul Jensen0478ace2014-07-11 12:28:19 -0400795 * A NetID indicating no Network is selected.
796 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
797 * @hide
798 */
799 public static final int NETID_UNSET = 0;
800
Erik Kline1ecdd962017-10-30 15:29:44 +0900801 /**
802 * Private DNS Mode values.
803 *
804 * The "private_dns_mode" global setting stores a String value which is
805 * expected to be one of the following.
806 */
807
808 /**
809 * @hide
810 */
lucaslin50205af2021-03-12 16:11:27 +0800811 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900812 public static final String PRIVATE_DNS_MODE_OFF = "off";
813 /**
814 * @hide
815 */
lucaslin50205af2021-03-12 16:11:27 +0800816 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900817 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
818 /**
819 * @hide
820 */
lucaslin50205af2021-03-12 16:11:27 +0800821 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900822 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin50205af2021-03-12 16:11:27 +0800823
824 /** @hide */
825 @Retention(RetentionPolicy.SOURCE)
826 @StringDef(value = {
827 PRIVATE_DNS_MODE_OFF,
828 PRIVATE_DNS_MODE_OPPORTUNISTIC,
829 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
830 })
831 public @interface PrivateDnsMode {}
Erik Kline1ecdd962017-10-30 15:29:44 +0900832
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900833 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700834 private final IConnectivityManager mService;
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +0900835
Paul Jensen12131352014-12-10 15:12:18 -0500836 /**
837 * A kludge to facilitate static access where a Context pointer isn't available, like in the
838 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
839 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
840 * methods that take a Context argument.
841 */
842 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800843
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +0900844 private final Context mContext;
845
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +0000846 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800847
Robert Greenwalt26744a52013-02-15 10:56:35 -0800848 /**
849 * Tests if a given integer represents a valid network type.
850 * @param networkType the type to be tested
851 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen1c9f2e42015-05-06 10:42:25 -0400852 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
853 * validate a network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800854 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700855 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700856 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900857 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800858 }
859
Robert Greenwalt26744a52013-02-15 10:56:35 -0800860 /**
861 * Returns a non-localized string representing a given network type.
862 * ONLY used for debugging output.
863 * @param type the type needing naming
864 * @return a String for the given type, or a string version of the type ("87")
865 * if no name is known.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900866 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800867 * {@hide}
868 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900869 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000870 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700871 public static String getNetworkTypeName(int type) {
872 switch (type) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900873 case TYPE_NONE:
874 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700875 case TYPE_MOBILE:
876 return "MOBILE";
877 case TYPE_WIFI:
878 return "WIFI";
879 case TYPE_MOBILE_MMS:
880 return "MOBILE_MMS";
881 case TYPE_MOBILE_SUPL:
882 return "MOBILE_SUPL";
883 case TYPE_MOBILE_DUN:
884 return "MOBILE_DUN";
885 case TYPE_MOBILE_HIPRI:
886 return "MOBILE_HIPRI";
887 case TYPE_WIMAX:
888 return "WIMAX";
889 case TYPE_BLUETOOTH:
890 return "BLUETOOTH";
891 case TYPE_DUMMY:
892 return "DUMMY";
893 case TYPE_ETHERNET:
894 return "ETHERNET";
895 case TYPE_MOBILE_FOTA:
896 return "MOBILE_FOTA";
897 case TYPE_MOBILE_IMS:
898 return "MOBILE_IMS";
899 case TYPE_MOBILE_CBS:
900 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700901 case TYPE_WIFI_P2P:
902 return "WIFI_P2P";
Wink Saville70dbdcc2013-07-29 15:00:57 -0700903 case TYPE_MOBILE_IA:
904 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -0700905 case TYPE_MOBILE_EMERGENCY:
906 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -0500907 case TYPE_PROXY:
908 return "PROXY";
Erik Klineb1ff7002014-11-19 17:23:41 +0900909 case TYPE_VPN:
910 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700911 default:
912 return Integer.toString(type);
913 }
914 }
915
Robert Greenwalt26744a52013-02-15 10:56:35 -0800916 /**
Aaron Huangdfba5d12020-06-27 07:18:23 +0800917 * @hide
Aaron Huangdfba5d12020-06-27 07:18:23 +0800918 */
lucaslin8c121bf2021-03-17 14:16:01 +0800919 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huangdfba5d12020-06-27 07:18:23 +0800920 public void systemReady() {
921 try {
922 mService.systemReady();
923 } catch (RemoteException e) {
924 throw e.rethrowFromSystemServer();
925 }
926 }
927
928 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800929 * Checks if a given type uses the cellular data connection.
930 * This should be replaced in the future by a network property.
931 * @param networkType the type to check
932 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +0900933 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800934 * {@hide}
935 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900936 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900937 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700938 public static boolean isNetworkTypeMobile(int networkType) {
939 switch (networkType) {
940 case TYPE_MOBILE:
941 case TYPE_MOBILE_MMS:
942 case TYPE_MOBILE_SUPL:
943 case TYPE_MOBILE_DUN:
944 case TYPE_MOBILE_HIPRI:
945 case TYPE_MOBILE_FOTA:
946 case TYPE_MOBILE_IMS:
947 case TYPE_MOBILE_CBS:
Wink Saville70dbdcc2013-07-29 15:00:57 -0700948 case TYPE_MOBILE_IA:
Ram201d45f2014-06-26 11:03:44 -0700949 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700950 return true;
951 default:
952 return false;
953 }
954 }
955
Robert Greenwalt26744a52013-02-15 10:56:35 -0800956 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700957 * Checks if the given network type is backed by a Wi-Fi radio.
958 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900959 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700960 * @hide
961 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900962 @Deprecated
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700963 public static boolean isNetworkTypeWifi(int networkType) {
964 switch (networkType) {
965 case TYPE_WIFI:
966 case TYPE_WIFI_P2P:
967 return true;
968 default:
969 return false;
970 }
971 }
972
973 /**
Chalard Jean03433052021-02-25 17:23:40 +0900974 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
975 * Specify that the traffic for this user should by follow the default rules.
976 * @hide
977 */
Chalard Jean560d4032021-03-17 14:33:24 +0900978 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +0900979 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
980
981 /**
982 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
983 * Specify that the traffic for this user should by default go on a network with
984 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
985 * if no such network is available.
986 * @hide
987 */
Chalard Jean560d4032021-03-17 14:33:24 +0900988 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +0900989 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
990
991 /** @hide */
992 @Retention(RetentionPolicy.SOURCE)
993 @IntDef(value = {
994 PROFILE_NETWORK_PREFERENCE_DEFAULT,
995 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
996 })
997 public @interface ProfileNetworkPreference {
998 }
999
1000 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001001 * Specifies the preferred network type. When the device has more
1002 * than one type available the preferred network type will be used.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001003 *
1004 * @param preference the network type to prefer over all others. It is
1005 * unspecified what happens to the old preferred network in the
1006 * overall ordering.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001007 * @deprecated Functionality has been removed as it no longer makes sense,
1008 * with many more than two networks - we'd need an array to express
1009 * preference. Instead we use dynamic network properties of
1010 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001011 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001012 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001013 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001014 }
1015
Robert Greenwalt26744a52013-02-15 10:56:35 -08001016 /**
1017 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001018 *
1019 * @return an integer representing the preferred network type
1020 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001021 * @deprecated Functionality has been removed as it no longer makes sense,
1022 * with many more than two networks - we'd need an array to express
1023 * preference. Instead we use dynamic network properties of
1024 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001025 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001026 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001027 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001028 public int getNetworkPreference() {
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001029 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001030 }
1031
Scott Mainf58b7d82011-10-06 19:02:28 -07001032 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001033 * Returns details about the currently active default data network. When
1034 * connected, this network is the default route for outgoing connections.
1035 * You should always check {@link NetworkInfo#isConnected()} before initiating
1036 * network traffic. This may return {@code null} when there is no default
1037 * network.
Chalard Jean7c85ba42018-03-29 17:45:24 +09001038 * Note that if the default network is a VPN, this method will return the
1039 * NetworkInfo for one of its underlying networks instead, or null if the
1040 * VPN agent did not specify any. Apps interested in learning about VPNs
1041 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001042 *
1043 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001044 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001045 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001046 */
junyulai5c2f6262018-12-13 12:47:51 +08001047 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001048 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001049 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001050 public NetworkInfo getActiveNetworkInfo() {
1051 try {
1052 return mService.getActiveNetworkInfo();
1053 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001054 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001055 }
1056 }
1057
Robert Greenwalt26744a52013-02-15 10:56:35 -08001058 /**
Paul Jensenc2569432015-02-13 14:18:39 -05001059 * Returns a {@link Network} object corresponding to the currently active
1060 * default data network. In the event that the current active default data
1061 * network disconnects, the returned {@code Network} object will no longer
1062 * be usable. This will return {@code null} when there is no default
1063 * network.
1064 *
1065 * @return a {@link Network} object for the current default network or
1066 * {@code null} if no default network is currently active
Paul Jensenc2569432015-02-13 14:18:39 -05001067 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001068 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001069 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001070 public Network getActiveNetwork() {
1071 try {
1072 return mService.getActiveNetwork();
1073 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001074 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001075 }
1076 }
1077
1078 /**
Robin Leeda4d2e22016-03-24 12:07:00 +00001079 * Returns a {@link Network} object corresponding to the currently active
1080 * default data network for a specific UID. In the event that the default data
1081 * network disconnects, the returned {@code Network} object will no longer
1082 * be usable. This will return {@code null} when there is no default
1083 * network for the UID.
Robin Leeda4d2e22016-03-24 12:07:00 +00001084 *
1085 * @return a {@link Network} object for the current default network for the
1086 * given UID or {@code null} if no default network is currently active
1087 *
1088 * @hide
1089 */
paulhuec0a9632019-08-12 16:25:11 +08001090 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001091 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001092 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001093 return getActiveNetworkForUid(uid, false);
1094 }
1095
1096 /** {@hide} */
1097 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001098 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001099 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001100 } catch (RemoteException e) {
1101 throw e.rethrowFromSystemServer();
1102 }
1103 }
1104
1105 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001106 * Adds or removes a requirement for given UID ranges to use the VPN.
1107 *
1108 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1109 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1110 * otherwise have permission to bypass the VPN (e.g., because they have the
1111 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1112 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1113 * set to {@code false}, a previously-added restriction is removed.
1114 * <p>
1115 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1116 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1117 * remove a previously-added range, the exact range must be removed as is.
1118 * <p>
1119 * The changes are applied asynchronously and may not have been applied by the time the method
1120 * returns. Apps will be notified about any changes that apply to them via
1121 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1122 * effect.
1123 * <p>
1124 * This method should be called only by the VPN code.
1125 *
1126 * @param ranges the UID ranges to restrict
1127 * @param requireVpn whether the specified UID ranges must use a VPN
1128 *
1129 * TODO: expose as @SystemApi.
1130 * @hide
1131 */
1132 @RequiresPermission(anyOf = {
1133 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1134 android.Manifest.permission.NETWORK_STACK})
1135 public void setRequireVpnForUids(boolean requireVpn,
1136 @NonNull Collection<Range<Integer>> ranges) {
1137 Objects.requireNonNull(ranges);
1138 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1139 // This method is not necessarily expected to be used outside the system server, so
1140 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1141 // stack process, or by tests.
1142 UidRange[] rangesArray = new UidRange[ranges.size()];
1143 int index = 0;
1144 for (Range<Integer> range : ranges) {
1145 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1146 }
1147 try {
1148 mService.setRequireVpnForUids(requireVpn, rangesArray);
1149 } catch (RemoteException e) {
1150 throw e.rethrowFromSystemServer();
1151 }
1152 }
1153
1154 /**
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001155 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1156 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1157 * but is still supported for backwards compatibility.
1158 * <p>
1159 * This type of VPN is assumed always to use the system default network, and must always declare
1160 * exactly one underlying network, which is the network that was the default when the VPN
1161 * connected.
1162 * <p>
1163 * Calling this method with {@code true} enables legacy behaviour, specifically:
1164 * <ul>
1165 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1166 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1167 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1168 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1169 * underlying the VPN.</li>
1170 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1171 * similarly replaced by the VPN network state.</li>
1172 * <li>Information on current network interfaces passed to NetworkStatsService will not
1173 * include any VPN interfaces.</li>
1174 * </ul>
1175 *
1176 * @param enabled whether legacy lockdown VPN is enabled or disabled
1177 *
1178 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1179 *
1180 * @hide
1181 */
1182 @RequiresPermission(anyOf = {
1183 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1184 android.Manifest.permission.NETWORK_SETTINGS})
1185 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1186 try {
1187 mService.setLegacyLockdownVpnEnabled(enabled);
1188 } catch (RemoteException e) {
1189 throw e.rethrowFromSystemServer();
1190 }
1191 }
1192
1193 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001194 * Returns details about the currently active default data network
1195 * for a given uid. This is for internal use only to avoid spying
1196 * other apps.
1197 *
1198 * @return a {@link NetworkInfo} object for the current default network
1199 * for the given uid or {@code null} if no default network is
1200 * available for the specified uid.
1201 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001202 * {@hide}
1203 */
paulhuec0a9632019-08-12 16:25:11 +08001204 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001205 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001206 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001207 return getActiveNetworkInfoForUid(uid, false);
1208 }
1209
1210 /** {@hide} */
1211 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001212 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001213 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001214 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001215 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001216 }
1217 }
1218
Robert Greenwalt26744a52013-02-15 10:56:35 -08001219 /**
1220 * Returns connection status information about a particular
1221 * network type.
1222 *
1223 * @param networkType integer specifying which networkType in
1224 * which you're interested.
1225 * @return a {@link NetworkInfo} object for the requested
1226 * network type or {@code null} if the type is not
Chalard Jean7c85ba42018-03-29 17:45:24 +09001227 * supported by the device. If {@code networkType} is
1228 * TYPE_VPN and a VPN is active for the calling app,
1229 * then this method will try to return one of the
1230 * underlying networks for the VPN or null if the
1231 * VPN agent didn't specify any.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001232 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001233 * @deprecated This method does not support multiple connected networks
1234 * of the same type. Use {@link #getAllNetworks} and
1235 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001236 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001237 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001238 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001239 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001240 public NetworkInfo getNetworkInfo(int networkType) {
1241 try {
1242 return mService.getNetworkInfo(networkType);
1243 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001244 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001245 }
1246 }
1247
Robert Greenwalt26744a52013-02-15 10:56:35 -08001248 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001249 * Returns connection status information about a particular
1250 * Network.
1251 *
1252 * @param network {@link Network} specifying which network
1253 * in which you're interested.
1254 * @return a {@link NetworkInfo} object for the requested
1255 * network or {@code null} if the {@code Network}
1256 * is not valid.
junyulai5c2f6262018-12-13 12:47:51 +08001257 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001258 */
junyulai5c2f6262018-12-13 12:47:51 +08001259 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001260 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001261 @Nullable
1262 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001263 return getNetworkInfoForUid(network, Process.myUid(), false);
1264 }
1265
1266 /** {@hide} */
1267 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001268 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001269 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001270 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001271 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001272 }
1273 }
1274
1275 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001276 * Returns connection status information about all network
1277 * types supported by the device.
1278 *
1279 * @return an array of {@link NetworkInfo} objects. Check each
1280 * {@link NetworkInfo#getType} for which type each applies.
1281 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001282 * @deprecated This method does not support multiple connected networks
1283 * of the same type. Use {@link #getAllNetworks} and
1284 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001285 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001286 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001287 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001288 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001289 public NetworkInfo[] getAllNetworkInfo() {
1290 try {
1291 return mService.getAllNetworkInfo();
1292 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001293 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001294 }
1295 }
1296
Robert Greenwalt26744a52013-02-15 10:56:35 -08001297 /**
junyulai57840802021-03-03 12:09:05 +08001298 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1299 * connected.
1300 * @hide
1301 */
1302 @SystemApi(client = MODULE_LIBRARIES)
1303 @RequiresPermission(anyOf = {
1304 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1305 android.Manifest.permission.NETWORK_STACK,
1306 android.Manifest.permission.NETWORK_SETTINGS})
1307 @NonNull
1308 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1309 try {
1310 return mService.getAllNetworkStateSnapshot();
1311 } catch (RemoteException e) {
1312 throw e.rethrowFromSystemServer();
1313 }
1314 }
1315
1316 /**
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001317 * Returns the {@link Network} object currently serving a given type, or
1318 * null if the given type is not connected.
1319 *
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001320 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04001321 * @deprecated This method does not support multiple connected networks
1322 * of the same type. Use {@link #getAllNetworks} and
1323 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001324 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001325 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001326 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001327 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001328 public Network getNetworkForType(int networkType) {
1329 try {
1330 return mService.getNetworkForType(networkType);
1331 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001332 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001333 }
1334 }
1335
1336 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001337 * Returns an array of all {@link Network} currently tracked by the
1338 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001339 *
1340 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001341 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001342 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001343 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001344 public Network[] getAllNetworks() {
1345 try {
1346 return mService.getAllNetworks();
1347 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001348 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001349 }
1350 }
1351
1352 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001353 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001354 * the Networks that applications run by the given user will use by default.
1355 * @hide
1356 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001357 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001358 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1359 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001360 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001361 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001362 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001363 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001364 }
1365 }
1366
1367 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001368 * Returns the IP information for the current default network.
1369 *
1370 * @return a {@link LinkProperties} object describing the IP info
1371 * for the current default network, or {@code null} if there
1372 * is no current default network.
1373 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001374 * {@hide}
Chalard Jeancc47b522019-01-11 16:47:53 +09001375 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1376 * value of {@link #getActiveNetwork()} instead. In particular,
1377 * this method will return non-null LinkProperties even if the
1378 * app is blocked by policy from using this network.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001379 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001380 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-01-11 16:47:53 +09001381 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001382 public LinkProperties getActiveLinkProperties() {
1383 try {
1384 return mService.getActiveLinkProperties();
1385 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001386 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001387 }
1388 }
1389
Robert Greenwalt26744a52013-02-15 10:56:35 -08001390 /**
1391 * Returns the IP information for a given network type.
1392 *
1393 * @param networkType the network type of interest.
1394 * @return a {@link LinkProperties} object describing the IP info
1395 * for the given networkType, or {@code null} if there is
1396 * no current default network.
1397 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001398 * {@hide}
Paul Jensena8e6dc62015-03-18 12:23:02 -04001399 * @deprecated This method does not support multiple connected networks
1400 * of the same type. Use {@link #getAllNetworks},
1401 * {@link #getNetworkInfo(android.net.Network)}, and
1402 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001403 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001404 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001405 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001406 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001407 public LinkProperties getLinkProperties(int networkType) {
1408 try {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001409 return mService.getLinkPropertiesForType(networkType);
1410 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001411 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001412 }
1413 }
1414
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001415 /**
1416 * Get the {@link LinkProperties} for the given {@link Network}. This
1417 * will return {@code null} if the network is unknown.
1418 *
1419 * @param network The {@link Network} object identifying the network in question.
1420 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001421 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001422 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001423 @Nullable
1424 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001425 try {
1426 return mService.getLinkProperties(network);
1427 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001428 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001429 }
1430 }
1431
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001432 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001433 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001434 * will return {@code null} if the network is unknown.
1435 *
Roshan Pius7992afd2020-12-22 15:10:42 -08001436 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1437 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1438 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1439 * this location sensitive information (subject to app's location permissions) will be
1440 * noted by system. To include any location sensitive data in {@link TransportInfo},
1441 * use a {@link NetworkCallback} with
1442 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1443 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001444 * @param network The {@link Network} object identifying the network in question.
Roshan Pius7992afd2020-12-22 15:10:42 -08001445 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001446 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001447 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001448 @Nullable
1449 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001450 try {
Roshan Piusc97d8062020-12-17 14:53:09 -08001451 return mService.getNetworkCapabilities(
1452 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001453 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001454 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001455 }
1456 }
1457
Robert Greenwalt26744a52013-02-15 10:56:35 -08001458 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001459 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001460 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1461 * portal is present.
1462 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1463 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1464 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001465 * The system network validation may be using different strategies to detect captive portals,
1466 * so this method does not necessarily return a URL used by the system. It only returns a URL
1467 * that may be relevant for other components trying to detect captive portals.
paulhuec0a9632019-08-12 16:25:11 +08001468 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001469 * @hide
paulhuec0a9632019-08-12 16:25:11 +08001470 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1471 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001472 */
paulhuec0a9632019-08-12 16:25:11 +08001473 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001474 @SystemApi
paulhuec0a9632019-08-12 16:25:11 +08001475 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001476 public String getCaptivePortalServerUrl() {
1477 try {
1478 return mService.getCaptivePortalServerUrl();
1479 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001480 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001481 }
1482 }
1483
1484 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001485 * Tells the underlying networking system that the caller wants to
1486 * begin using the named feature. The interpretation of {@code feature}
1487 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001488 *
1489 * <p>This method requires the caller to hold either the
1490 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1491 * or the ability to modify system settings as determined by
1492 * {@link android.provider.Settings.System#canWrite}.</p>
1493 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001494 * @param networkType specifies which network the request pertains to
1495 * @param feature the name of the feature to be used
1496 * @return an integer value representing the outcome of the request.
1497 * The interpretation of this value is specific to each networking
1498 * implementation+feature combination, except that the value {@code -1}
1499 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001500 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001501 * @deprecated Deprecated in favor of the cleaner
1502 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001503 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001504 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001505 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001506 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001507 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001508 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001509 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001510 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1511 if (netCap == null) {
1512 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1513 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001514 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001515 }
1516
1517 NetworkRequest request = null;
1518 synchronized (sLegacyRequests) {
1519 LegacyRequest l = sLegacyRequests.get(netCap);
1520 if (l != null) {
1521 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1522 renewRequestLocked(l);
1523 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001524 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001525 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001526 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001527 }
1528 }
1529
1530 request = requestNetworkForFeatureLocked(netCap);
1531 }
1532 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001533 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001534 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001535 } else {
1536 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001537 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001538 }
1539 }
1540
1541 /**
1542 * Tells the underlying networking system that the caller is finished
1543 * using the named feature. The interpretation of {@code feature}
1544 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001545 *
1546 * <p>This method requires the caller to hold either the
1547 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1548 * or the ability to modify system settings as determined by
1549 * {@link android.provider.Settings.System#canWrite}.</p>
1550 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001551 * @param networkType specifies which network the request pertains to
1552 * @param feature the name of the feature that is no longer needed
1553 * @return an integer value representing the outcome of the request.
1554 * The interpretation of this value is specific to each networking
1555 * implementation+feature combination, except that the value {@code -1}
1556 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001557 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001558 * @deprecated Deprecated in favor of the cleaner
1559 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001560 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001561 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001562 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001563 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001564 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001565 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001566 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001567 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1568 if (netCap == null) {
1569 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1570 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001571 return -1;
1572 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001573
Paul Jensen034dea32014-12-17 10:39:34 -05001574 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001575 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001576 }
1577 return 1;
1578 }
1579
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001580 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001581 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1582 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001583 switch (feature) {
1584 case "enableCBS":
1585 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1586 case "enableDUN":
1587 case "enableDUNAlways":
1588 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1589 case "enableFOTA":
1590 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1591 case "enableHIPRI":
1592 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1593 case "enableIMS":
1594 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1595 case "enableMMS":
1596 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1597 case "enableSUPL":
1598 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1599 default:
1600 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001601 }
Erik Kline50068e52017-01-26 18:08:28 +09001602 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1603 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001604 }
1605 return null;
1606 }
1607
Robert Greenwalt5a367872014-06-02 15:32:02 -07001608 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001609 if (netCap == null) return TYPE_NONE;
1610 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1611 return TYPE_MOBILE_CBS;
1612 }
1613 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1614 return TYPE_MOBILE_IMS;
1615 }
1616 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1617 return TYPE_MOBILE_FOTA;
1618 }
1619 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1620 return TYPE_MOBILE_DUN;
1621 }
1622 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1623 return TYPE_MOBILE_SUPL;
1624 }
1625 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1626 return TYPE_MOBILE_MMS;
1627 }
1628 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1629 return TYPE_MOBILE_HIPRI;
1630 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001631 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1632 return TYPE_WIFI_P2P;
1633 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001634 return TYPE_NONE;
1635 }
1636
1637 private static class LegacyRequest {
1638 NetworkCapabilities networkCapabilities;
1639 NetworkRequest networkRequest;
1640 int expireSequenceNumber;
1641 Network currentNetwork;
1642 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001643
1644 private void clearDnsBinding() {
1645 if (currentNetwork != null) {
1646 currentNetwork = null;
1647 setProcessDefaultNetworkForHostResolution(null);
1648 }
1649 }
1650
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001651 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001652 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001653 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001654 currentNetwork = network;
1655 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001656 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001657 }
1658 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001659 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001660 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001661 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1662 }
1663 };
1664 }
1665
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001666 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001667 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1668 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001669
1670 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1671 synchronized (sLegacyRequests) {
1672 LegacyRequest l = sLegacyRequests.get(netCap);
1673 if (l != null) return l.networkRequest;
1674 }
1675 return null;
1676 }
1677
1678 private void renewRequestLocked(LegacyRequest l) {
1679 l.expireSequenceNumber++;
1680 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1681 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1682 }
1683
1684 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1685 int ourSeqNum = -1;
1686 synchronized (sLegacyRequests) {
1687 LegacyRequest l = sLegacyRequests.get(netCap);
1688 if (l == null) return;
1689 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001690 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001691 }
1692 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1693 }
1694
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001695 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001696 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1697 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001698 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001699 try {
1700 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001701 } catch (RemoteException e) {
1702 throw e.rethrowFromSystemServer();
1703 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001704 LegacyRequest l = new LegacyRequest();
1705 l.networkCapabilities = netCap;
1706 l.delay = delay;
1707 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001708 l.networkRequest = sendRequestForNetwork(
1709 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001710 if (l.networkRequest == null) return null;
1711 sLegacyRequests.put(netCap, l);
1712 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1713 return l.networkRequest;
1714 }
1715
1716 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1717 if (delay >= 0) {
1718 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001719 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001720 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1721 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001722 }
1723 }
1724
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001725 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001726 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1727 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001728 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001729 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001730 }
Paul Jensen034dea32014-12-17 10:39:34 -05001731 if (l == null) return false;
1732 unregisterNetworkCallback(l.networkCallback);
1733 l.clearDnsBinding();
1734 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001735 }
1736
Erik Kline50068e52017-01-26 18:08:28 +09001737 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1738 static {
1739 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1740 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1741 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1742 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1743 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1744 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1745 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1746 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1747 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1748 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1749 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1750 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1751 }
1752
1753 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1754 static {
1755 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1756 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1757 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1758 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1759 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1760 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1761 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1762 }
1763
1764 /**
1765 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1766 * instance suitable for registering a request or callback. Throws an
1767 * IllegalArgumentException if no mapping from the legacy type to
1768 * NetworkCapabilities is known.
1769 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001770 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1771 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001772 * @hide
1773 */
1774 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1775 final NetworkCapabilities nc = new NetworkCapabilities();
1776
1777 // Map from type to transports.
1778 final int NOT_FOUND = -1;
1779 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001780 if (transport == NOT_FOUND) {
1781 throw new IllegalArgumentException("unknown legacy type: " + type);
1782 }
Erik Kline50068e52017-01-26 18:08:28 +09001783 nc.addTransportType(transport);
1784
1785 // Map from type to capabilities.
1786 nc.addCapability(sLegacyTypeToCapability.get(
1787 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1788 nc.maybeMarkCapabilitiesRestricted();
1789 return nc;
1790 }
1791
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001792 /** @hide */
1793 public static class PacketKeepaliveCallback {
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001794 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayevfc03a992019-11-15 19:12:49 +00001795 public PacketKeepaliveCallback() {
1796 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001797 /** The requested keepalive was successfully started. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001798 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001799 public void onStarted() {}
1800 /** The keepalive was successfully stopped. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001801 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001802 public void onStopped() {}
1803 /** An error occurred. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001804 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001805 public void onError(int error) {}
1806 }
1807
1808 /**
1809 * Allows applications to request that the system periodically send specific packets on their
1810 * behalf, using hardware offload to save battery power.
1811 *
1812 * To request that the system send keepalives, call one of the methods that return a
1813 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1814 * passing in a non-null callback. If the callback is successfully started, the callback's
1815 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1816 * specifying one of the {@code ERROR_*} constants in this class.
1817 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001818 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1819 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1820 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001821 *
junyulaia86defc2018-12-27 17:25:29 +08001822 * @deprecated Use {@link SocketKeepalive} instead.
1823 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001824 * @hide
1825 */
1826 public class PacketKeepalive {
1827
1828 private static final String TAG = "PacketKeepalive";
1829
1830 /** @hide */
1831 public static final int SUCCESS = 0;
1832
1833 /** @hide */
1834 public static final int NO_KEEPALIVE = -1;
1835
1836 /** @hide */
1837 public static final int BINDER_DIED = -10;
1838
1839 /** The specified {@code Network} is not connected. */
1840 public static final int ERROR_INVALID_NETWORK = -20;
1841 /** The specified IP addresses are invalid. For example, the specified source IP address is
1842 * not configured on the specified {@code Network}. */
1843 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1844 /** The requested port is invalid. */
1845 public static final int ERROR_INVALID_PORT = -22;
1846 /** The packet length is invalid (e.g., too long). */
1847 public static final int ERROR_INVALID_LENGTH = -23;
1848 /** The packet transmission interval is invalid (e.g., too short). */
1849 public static final int ERROR_INVALID_INTERVAL = -24;
1850
1851 /** The hardware does not support this request. */
1852 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001853 /** The hardware returned an error. */
1854 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001855
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001856 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001857 public static final int NATT_PORT = 4500;
1858
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001859 /** The minimum interval in seconds between keepalive packet transmissions */
1860 public static final int MIN_INTERVAL = 10;
1861
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001862 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001863 private final ISocketKeepaliveCallback mCallback;
1864 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001865
1866 private volatile Integer mSlot;
1867
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001868 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001869 public void stop() {
1870 try {
junyulai9f872232019-01-16 20:23:34 +08001871 mExecutor.execute(() -> {
1872 try {
1873 if (mSlot != null) {
1874 mService.stopKeepalive(mNetwork, mSlot);
1875 }
1876 } catch (RemoteException e) {
1877 Log.e(TAG, "Error stopping packet keepalive: ", e);
1878 throw e.rethrowFromSystemServer();
1879 }
1880 });
1881 } catch (RejectedExecutionException e) {
1882 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001883 }
1884 }
1885
1886 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001887 Objects.requireNonNull(network, "network cannot be null");
1888 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001889 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08001890 mExecutor = Executors.newSingleThreadExecutor();
1891 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001892 @Override
junyulai9f872232019-01-16 20:23:34 +08001893 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08001894 final long token = Binder.clearCallingIdentity();
1895 try {
1896 mExecutor.execute(() -> {
1897 mSlot = slot;
1898 callback.onStarted();
1899 });
1900 } finally {
1901 Binder.restoreCallingIdentity(token);
1902 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001903 }
junyulai9f872232019-01-16 20:23:34 +08001904
1905 @Override
1906 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08001907 final long token = Binder.clearCallingIdentity();
1908 try {
1909 mExecutor.execute(() -> {
1910 mSlot = null;
1911 callback.onStopped();
1912 });
1913 } finally {
1914 Binder.restoreCallingIdentity(token);
1915 }
junyulai9f872232019-01-16 20:23:34 +08001916 mExecutor.shutdown();
1917 }
1918
1919 @Override
1920 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08001921 final long token = Binder.clearCallingIdentity();
1922 try {
1923 mExecutor.execute(() -> {
1924 mSlot = null;
1925 callback.onError(error);
1926 });
1927 } finally {
1928 Binder.restoreCallingIdentity(token);
1929 }
junyulai9f872232019-01-16 20:23:34 +08001930 mExecutor.shutdown();
1931 }
1932
1933 @Override
1934 public void onDataReceived() {
1935 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1936 // this callback when data is received.
1937 }
1938 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001939 }
1940 }
1941
1942 /**
1943 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1944 *
junyulaia86defc2018-12-27 17:25:29 +08001945 * @deprecated Use {@link #createSocketKeepalive} instead.
1946 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001947 * @hide
1948 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001949 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001950 public PacketKeepalive startNattKeepalive(
1951 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1952 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1953 final PacketKeepalive k = new PacketKeepalive(network, callback);
1954 try {
junyulai9f872232019-01-16 20:23:34 +08001955 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001956 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1957 } catch (RemoteException e) {
1958 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08001959 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001960 }
1961 return k;
1962 }
1963
Chiachang Wangc5f86f42021-01-15 11:06:21 +08001964 // Construct an invalid fd.
1965 private ParcelFileDescriptor createInvalidFd() {
1966 final int invalidFd = -1;
1967 return ParcelFileDescriptor.adoptFd(invalidFd);
1968 }
1969
The Android Open Source Project28527d22009-03-03 19:31:44 -08001970 /**
junyulaia86defc2018-12-27 17:25:29 +08001971 * Request that keepalives be started on a IPsec NAT-T socket.
1972 *
1973 * @param network The {@link Network} the socket is on.
1974 * @param socket The socket that needs to be kept alive.
1975 * @param source The source address of the {@link UdpEncapsulationSocket}.
1976 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1977 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1978 * must run callback sequentially, otherwise the order of callbacks cannot be
1979 * guaranteed.
1980 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1981 * changes. Must be extended by applications that use this API.
1982 *
junyulaic7ea1242019-01-08 20:04:33 +08001983 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1984 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08001985 **/
junyulai61143782019-03-04 22:45:36 +08001986 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08001987 @NonNull UdpEncapsulationSocket socket,
1988 @NonNull InetAddress source,
1989 @NonNull InetAddress destination,
1990 @NonNull @CallbackExecutor Executor executor,
1991 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08001992 ParcelFileDescriptor dup;
1993 try {
junyulaic4fb2482019-03-27 11:00:37 +08001994 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1995 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08001996 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1997 } catch (IOException ignored) {
1998 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1999 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002000 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002001 }
2002 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2003 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08002004 }
2005
2006 /**
2007 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2008 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2009 *
2010 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08002011 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2012 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2013 * from that port.
junyulai48a59382019-01-15 11:32:44 +08002014 * @param source The source address of the {@link UdpEncapsulationSocket}.
2015 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2016 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2017 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2018 * must run callback sequentially, otherwise the order of callbacks cannot be
2019 * guaranteed.
2020 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2021 * changes. Must be extended by applications that use this API.
2022 *
junyulaic7ea1242019-01-08 20:04:33 +08002023 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2024 * given socket.
junyulai48a59382019-01-15 11:32:44 +08002025 * @hide
2026 */
2027 @SystemApi
2028 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002029 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2030 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08002031 @NonNull InetAddress source,
2032 @NonNull InetAddress destination,
2033 @NonNull @CallbackExecutor Executor executor,
2034 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002035 ParcelFileDescriptor dup;
2036 try {
junyulaic4fb2482019-03-27 11:00:37 +08002037 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08002038 dup = pfd.dup();
2039 } catch (IOException ignored) {
2040 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2041 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002042 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002043 }
2044 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VAN642d6ab2021-03-11 10:56:49 +00002045 -1 /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08002046 }
2047
2048 /**
junyulaic7ea1242019-01-08 20:04:33 +08002049 * Request that keepalives be started on a TCP socket.
2050 * The socket must be established.
2051 *
2052 * @param network The {@link Network} the socket is on.
2053 * @param socket The socket that needs to be kept alive.
2054 * @param executor The executor on which callback will be invoked. This implementation assumes
2055 * the provided {@link Executor} runs the callbacks in sequence with no
2056 * concurrency. Failing this, no guarantee of correctness can be made. It is
2057 * the responsibility of the caller to ensure the executor provides this
2058 * guarantee. A simple way of creating such an executor is with the standard
2059 * tool {@code Executors.newSingleThreadExecutor}.
2060 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2061 * changes. Must be extended by applications that use this API.
2062 *
2063 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2064 * given socket.
2065 * @hide
2066 */
2067 @SystemApi
2068 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002069 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002070 @NonNull Socket socket,
2071 @NonNull Executor executor,
2072 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002073 ParcelFileDescriptor dup;
2074 try {
2075 dup = ParcelFileDescriptor.fromSocket(socket);
2076 } catch (UncheckedIOException ignored) {
2077 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2078 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002079 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002080 }
2081 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002082 }
2083
2084 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002085 * Ensure that a network route exists to deliver traffic to the specified
2086 * host via the specified network interface. An attempt to add a route that
2087 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002088 *
2089 * <p>This method requires the caller to hold either the
2090 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2091 * or the ability to modify system settings as determined by
2092 * {@link android.provider.Settings.System#canWrite}.</p>
2093 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002094 * @param networkType the type of the network over which traffic to the specified
2095 * host is to be routed
2096 * @param hostAddress the IP address of the host to which the route is desired
2097 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002098 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002099 * @deprecated Deprecated in favor of the
2100 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2101 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002102 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002103 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002104 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002105 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002106 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002107 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002108 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002109 }
2110
2111 /**
2112 * Ensure that a network route exists to deliver traffic to the specified
2113 * host via the specified network interface. An attempt to add a route that
2114 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002115 *
2116 * <p>This method requires the caller to hold either the
2117 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2118 * or the ability to modify system settings as determined by
2119 * {@link android.provider.Settings.System#canWrite}.</p>
2120 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002121 * @param networkType the type of the network over which traffic to the specified
2122 * host is to be routed
2123 * @param hostAddress the IP address of the host to which the route is desired
2124 * @return {@code true} on success, {@code false} on failure
2125 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002126 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002127 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002128 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002129 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002130 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002131 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002132 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002133 try {
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002134 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2135 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002136 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002137 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002138 }
2139 }
2140
2141 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002142 * @return the context's attribution tag
2143 */
2144 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2145 private @Nullable String getAttributionTag() {
2146 return mContext.getAttributionTag();
2147 }
2148
2149 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002150 * Returns the value of the setting for background data usage. If false,
2151 * applications should not use the network if the application is not in the
2152 * foreground. Developers should respect this setting, and check the value
2153 * of this before performing any background data operations.
2154 * <p>
2155 * All applications that have background services that use the network
2156 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002157 * <p>
Scott Main50589142011-10-06 18:32:43 -07002158 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002159 * background data depends on several combined factors, and this method will
2160 * always return {@code true}. Instead, when background data is unavailable,
2161 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002162 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002163 * @return Whether background data usage is allowed.
2164 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002165 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002166 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002167 // assume that background data is allowed; final authority is
2168 // NetworkInfo which may be blocked.
2169 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002170 }
2171
2172 /**
2173 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002174 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002175 * @param allowBackgroundData Whether an application should use data while
2176 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002177 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002178 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2179 * @see #getBackgroundDataSetting()
2180 * @hide
2181 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002182 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002183 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002184 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002185 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002186 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002187
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002188 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002189 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002190 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002191 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002192 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002193 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002194 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002195 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2196 if (tm != null) {
2197 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2198 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2199 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2200 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2201 + " retVal=" + retVal);
2202 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002203 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002204 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002205 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002206 }
2207
The Android Open Source Project28527d22009-03-03 19:31:44 -08002208 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002209 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002210 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002211 */
2212 public interface OnNetworkActiveListener {
2213 /**
2214 * Called on the main thread of the process to report that the current data network
2215 * has become active, and it is now a good time to perform any pending network
2216 * operations. Note that this listener only tells you when the network becomes
2217 * active; if at any other time you want to know whether it is active (and thus okay
2218 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002219 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002220 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002221 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002222 }
2223
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002224 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002225 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002226
2227 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002228 * Start listening to reports when the system's default data network is active, meaning it is
2229 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2230 * to determine the current state of the system's default network after registering the
2231 * listener.
2232 * <p>
2233 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002234 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002235 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002236 *
2237 * @param l The listener to be told when the network is active.
2238 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002239 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002240 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2241 @Override
2242 public void onNetworkActive() throws RemoteException {
2243 l.onNetworkActive();
2244 }
2245 };
2246
2247 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002248 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002249 mNetworkActivityListeners.put(l, rl);
2250 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002251 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002252 }
2253 }
2254
2255 /**
2256 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002257 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002258 *
2259 * @param l Previously registered listener.
2260 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002261 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002262 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002263 if (rl == null) {
2264 throw new IllegalArgumentException("Listener was not registered.");
2265 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002266 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002267 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002268 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002269 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002270 }
2271 }
2272
2273 /**
2274 * Return whether the data network is currently active. An active network means that
2275 * it is currently in a high power state for performing data transmission. On some
2276 * types of networks, it may be expensive to move and stay in such a state, so it is
2277 * more power efficient to batch network traffic together when the radio is already in
2278 * this state. This method tells you whether right now is currently a good time to
2279 * initiate network traffic, as the network is already active.
2280 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002281 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002282 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002283 return mService.isDefaultNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002284 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002285 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002286 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002287 }
2288
2289 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002290 * {@hide}
2291 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002292 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002293 mContext = Objects.requireNonNull(context, "missing context");
2294 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002295 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002296 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002297 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002298
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002299 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002300 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002301 public static ConnectivityManager from(Context context) {
2302 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2303 }
2304
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002305 /** @hide */
2306 public NetworkRequest getDefaultRequest() {
2307 try {
2308 // This is not racy as the default request is final in ConnectivityService.
2309 return mService.getDefaultRequest();
2310 } catch (RemoteException e) {
2311 throw e.rethrowFromSystemServer();
2312 }
2313 }
2314
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002315 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002316 * Check if the package is a allowed to write settings. This also accounts that such an access
2317 * happened.
2318 *
2319 * @return {@code true} iff the package is allowed to write settings.
2320 */
2321 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2322 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2323 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2324 boolean throwException) {
2325 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2326 callingAttributionTag, throwException);
2327 }
2328
2329 /**
Paul Jensen12131352014-12-10 15:12:18 -05002330 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2331 * situations where a Context pointer is unavailable.
2332 * @hide
2333 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002334 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002335 static ConnectivityManager getInstanceOrNull() {
2336 return sInstance;
2337 }
2338
2339 /**
2340 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2341 * situations where a Context pointer is unavailable.
2342 * @hide
2343 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002344 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002345 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002346 private static ConnectivityManager getInstance() {
2347 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002348 throw new IllegalStateException("No ConnectivityManager yet constructed");
2349 }
Paul Jensen895c3942015-03-10 10:54:12 -04002350 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002351 }
2352
2353 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002354 * Get the set of tetherable, available interfaces. This list is limited by
2355 * device configuration and current interface existence.
2356 *
2357 * @return an array of 0 or more Strings of tetherable interface names.
2358 *
markchien75721e42020-01-21 13:11:06 +08002359 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002360 * {@hide}
2361 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002362 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002363 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002364 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002365 public String[] getTetherableIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002366 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002367 }
2368
2369 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002370 * Get the set of tethered interfaces.
2371 *
2372 * @return an array of 0 or more String of currently tethered interface names.
2373 *
markchien75721e42020-01-21 13:11:06 +08002374 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002375 * {@hide}
2376 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002377 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002378 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002379 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002380 public String[] getTetheredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002381 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002382 }
2383
2384 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002385 * Get the set of interface names which attempted to tether but
2386 * failed. Re-attempting to tether may cause them to reset to the Tethered
2387 * state. Alternatively, causing the interface to be destroyed and recreated
2388 * may cause them to reset to the available state.
2389 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2390 * information on the cause of the errors.
2391 *
2392 * @return an array of 0 or more String indicating the interface names
2393 * which failed to tether.
2394 *
markchien75721e42020-01-21 13:11:06 +08002395 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002396 * {@hide}
2397 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002398 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002399 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002400 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002401 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002402 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002403 }
2404
2405 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002406 * Get the set of tethered dhcp ranges.
2407 *
markchien9e046242020-02-06 19:23:26 +08002408 * @deprecated This method is not supported.
2409 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002410 * {@hide}
2411 */
paulhuec0a9632019-08-12 16:25:11 +08002412 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien75721e42020-01-21 13:11:06 +08002413 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002414 public String[] getTetheredDhcpRanges() {
markchien9e046242020-02-06 19:23:26 +08002415 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002416 }
2417
2418 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002419 * Attempt to tether the named interface. This will setup a dhcp server
2420 * on the interface, forward and NAT IP packets and forward DNS requests
2421 * to the best active upstream network interface. Note that if no upstream
2422 * IP network interface is available, dhcp will still run and traffic will be
2423 * allowed between the tethered devices and this device, though upstream net
2424 * access will of course fail until an upstream network interface becomes
2425 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002426 *
2427 * <p>This method requires the caller to hold either the
2428 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2429 * or the ability to modify system settings as determined by
2430 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002431 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002432 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2433 * and WifiStateMachine which need direct access. All other clients should use
2434 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2435 * logic.</p>
2436 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002437 * @param iface the interface name to tether.
2438 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002439 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002440 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002441 * {@hide}
2442 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002443 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien10ddd022020-01-20 19:31:56 +08002444 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002445 public int tether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002446 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002447 }
2448
2449 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002450 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002451 *
2452 * <p>This method requires the caller to hold either the
2453 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2454 * or the ability to modify system settings as determined by
2455 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002456 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002457 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2458 * and WifiStateMachine which need direct access. All other clients should use
2459 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2460 * logic.</p>
2461 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002462 * @param iface the interface name to untether.
2463 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2464 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002465 * {@hide}
2466 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002467 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002468 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002469 public int untether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002470 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002471 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002472
2473 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002474 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002475 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002476 * due to device configuration.
2477 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002478 * <p>If this app does not have permission to use this API, it will always
2479 * return false rather than throw an exception.</p>
2480 *
2481 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2482 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2483 *
2484 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2485 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2486 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002487 * @return a boolean - {@code true} indicating Tethering is supported.
2488 *
markchien75721e42020-01-21 13:11:06 +08002489 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002490 * {@hide}
2491 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002492 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002493 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2494 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002495 public boolean isTetheringSupported() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002496 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002497 }
2498
2499 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002500 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien10ddd022020-01-20 19:31:56 +08002501 *
2502 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002503 * @hide
2504 */
2505 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002506 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002507 public static abstract class OnStartTetheringCallback {
2508 /**
2509 * Called when tethering has been successfully started.
2510 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002511 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002512
2513 /**
2514 * Called when starting tethering failed.
2515 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002516 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002517 }
2518
2519 /**
2520 * Convenient overload for
2521 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2522 * handler to run on the current thread's {@link Looper}.
markchien10ddd022020-01-20 19:31:56 +08002523 *
2524 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002525 * @hide
2526 */
2527 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002528 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002529 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002530 public void startTethering(int type, boolean showProvisioningUi,
2531 final OnStartTetheringCallback callback) {
2532 startTethering(type, showProvisioningUi, callback, null);
2533 }
2534
2535 /**
2536 * Runs tether provisioning for the given type if needed and then starts tethering if
2537 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2538 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2539 * schedules tether provisioning re-checks if appropriate.
2540 *
2541 * @param type The type of tethering to start. Must be one of
2542 * {@link ConnectivityManager.TETHERING_WIFI},
2543 * {@link ConnectivityManager.TETHERING_USB}, or
2544 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2545 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2546 * is one. This should be true the first time this function is called and also any time
2547 * the user can see this UI. It gives users information from their carrier about the
2548 * check failing and how they can sign up for tethering if possible.
2549 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2550 * of the result of trying to tether.
2551 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien10ddd022020-01-20 19:31:56 +08002552 *
2553 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002554 * @hide
2555 */
2556 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002557 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002558 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002559 public void startTethering(int type, boolean showProvisioningUi,
2560 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002561 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002562
markchien10ddd022020-01-20 19:31:56 +08002563 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002564 @Override
markchien10ddd022020-01-20 19:31:56 +08002565 public void execute(Runnable command) {
2566 if (handler == null) {
2567 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002568 } else {
markchien10ddd022020-01-20 19:31:56 +08002569 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002570 }
2571 }
2572 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002573
markchien10ddd022020-01-20 19:31:56 +08002574 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2575 @Override
2576 public void onTetheringStarted() {
2577 callback.onTetheringStarted();
2578 }
2579
2580 @Override
markchien68b67842020-03-19 13:37:43 +08002581 public void onTetheringFailed(final int error) {
markchien10ddd022020-01-20 19:31:56 +08002582 callback.onTetheringFailed();
2583 }
2584 };
2585
2586 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien68b67842020-03-19 13:37:43 +08002587 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien10ddd022020-01-20 19:31:56 +08002588
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002589 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002590 }
2591
2592 /**
2593 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2594 * applicable.
2595 *
2596 * @param type The type of tethering to stop. Must be one of
2597 * {@link ConnectivityManager.TETHERING_WIFI},
2598 * {@link ConnectivityManager.TETHERING_USB}, or
2599 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien75721e42020-01-21 13:11:06 +08002600 *
2601 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002602 * @hide
2603 */
2604 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002605 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002606 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002607 public void stopTethering(int type) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002608 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002609 }
2610
2611 /**
markchiena005c992019-02-27 14:56:11 +08002612 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2613 * upstream status.
2614 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002615 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien75721e42020-01-21 13:11:06 +08002616 * @hide
markchiena005c992019-02-27 14:56:11 +08002617 */
2618 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002619 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002620 public abstract static class OnTetheringEventCallback {
2621
2622 /**
2623 * Called when tethering upstream changed. This can be called multiple times and can be
2624 * called any time.
2625 *
2626 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2627 * have any upstream.
2628 */
2629 public void onUpstreamChanged(@Nullable Network network) {}
2630 }
2631
markchien75721e42020-01-21 13:11:06 +08002632 @GuardedBy("mTetheringEventCallbacks")
2633 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2634 mTetheringEventCallbacks = new ArrayMap<>();
2635
markchiena005c992019-02-27 14:56:11 +08002636 /**
2637 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002638 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002639 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2640 * with a null argument. The same callback object cannot be registered twice.
2641 *
2642 * @param executor the executor on which callback will be invoked.
2643 * @param callback the callback to be called when tethering has change events.
markchien75721e42020-01-21 13:11:06 +08002644 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002645 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002646 * @hide
2647 */
2648 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002649 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002650 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2651 public void registerTetheringEventCallback(
2652 @NonNull @CallbackExecutor Executor executor,
2653 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002654 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchiena005c992019-02-27 14:56:11 +08002655
markchien75721e42020-01-21 13:11:06 +08002656 final TetheringEventCallback tetherCallback =
2657 new TetheringEventCallback() {
2658 @Override
2659 public void onUpstreamChanged(@Nullable Network network) {
2660 callback.onUpstreamChanged(network);
2661 }
2662 };
2663
2664 synchronized (mTetheringEventCallbacks) {
2665 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002666 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002667 }
markchiena005c992019-02-27 14:56:11 +08002668 }
2669
2670 /**
2671 * Remove tethering event callback previously registered with
2672 * {@link #registerTetheringEventCallback}.
2673 *
2674 * @param callback previously registered callback.
markchien75721e42020-01-21 13:11:06 +08002675 *
2676 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002677 * @hide
2678 */
2679 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002680 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002681 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2682 public void unregisterTetheringEventCallback(
2683 @NonNull final OnTetheringEventCallback callback) {
markchien75721e42020-01-21 13:11:06 +08002684 Objects.requireNonNull(callback, "The callback must be non-null");
2685 synchronized (mTetheringEventCallbacks) {
2686 final TetheringEventCallback tetherCallback =
2687 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002688 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002689 }
markchiena005c992019-02-27 14:56:11 +08002690 }
2691
2692
2693 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002694 * Get the list of regular expressions that define any tetherable
2695 * USB network interfaces. If USB tethering is not supported by the
2696 * device, this list should be empty.
2697 *
2698 * @return an array of 0 or more regular expression Strings defining
2699 * what interfaces are considered tetherable usb interfaces.
2700 *
markchien75721e42020-01-21 13:11:06 +08002701 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002702 * {@hide}
2703 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002704 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002705 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002706 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002707 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002708 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002709 }
2710
2711 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002712 * Get the list of regular expressions that define any tetherable
2713 * Wifi network interfaces. If Wifi tethering is not supported by the
2714 * device, this list should be empty.
2715 *
2716 * @return an array of 0 or more regular expression Strings defining
2717 * what interfaces are considered tetherable wifi interfaces.
2718 *
markchien75721e42020-01-21 13:11:06 +08002719 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002720 * {@hide}
2721 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002722 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002723 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002724 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002725 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002726 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002727 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002728
Danica Chang96567052010-08-11 14:54:43 -07002729 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002730 * Get the list of regular expressions that define any tetherable
2731 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2732 * device, this list should be empty.
2733 *
2734 * @return an array of 0 or more regular expression Strings defining
2735 * what interfaces are considered tetherable bluetooth interfaces.
2736 *
markchien75721e42020-01-21 13:11:06 +08002737 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2738 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002739 * {@hide}
2740 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002741 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002742 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002743 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002744 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002745 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002746 }
2747
Mike Lockwooded4a1742011-07-19 13:04:47 -07002748 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002749 * Attempt to both alter the mode of USB and Tethering of USB. A
2750 * utility method to deal with some of the complexity of USB - will
2751 * attempt to switch to Rndis and subsequently tether the resulting
2752 * interface on {@code true} or turn off tethering and switch off
2753 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002754 *
2755 * <p>This method requires the caller to hold either the
2756 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2757 * or the ability to modify system settings as determined by
2758 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002759 *
2760 * @param enable a boolean - {@code true} to enable tethering
2761 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002762 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002763 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002764 * {@hide}
2765 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002766 @UnsupportedAppUsage
markchien10ddd022020-01-20 19:31:56 +08002767 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002768 public int setUsbTethering(boolean enable) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002769 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002770 }
2771
markchien75721e42020-01-21 13:11:06 +08002772 /**
2773 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2774 * {@hide}
2775 */
markchien5bd499c2019-01-16 17:44:13 +08002776 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002777 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002778 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien75721e42020-01-21 13:11:06 +08002779 /**
2780 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2781 * {@hide}
2782 */
2783 @Deprecated
2784 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2785 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2786 /**
2787 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2788 * {@hide}
2789 */
2790 @Deprecated
2791 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2792 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2793 /**
2794 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2795 * {@hide}
2796 */
2797 @Deprecated
2798 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2799 /**
2800 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2801 * {@hide}
2802 */
2803 @Deprecated
2804 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2805 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2806 /**
markchien68b67842020-03-19 13:37:43 +08002807 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002808 * {@hide}
2809 */
2810 @Deprecated
markchien68b67842020-03-19 13:37:43 +08002811 public static final int TETHER_ERROR_MASTER_ERROR =
2812 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien75721e42020-01-21 13:11:06 +08002813 /**
2814 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2815 * {@hide}
2816 */
2817 @Deprecated
2818 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2819 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2820 /**
2821 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2822 * {@hide}
2823 */
2824 @Deprecated
2825 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2826 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2827 /**
markchien68b67842020-03-19 13:37:43 +08002828 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002829 * {@hide}
2830 */
2831 @Deprecated
2832 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002833 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002834 /**
markchien68b67842020-03-19 13:37:43 +08002835 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002836 * {@hide}
2837 */
2838 @Deprecated
2839 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002840 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002841 /**
2842 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2843 * {@hide}
2844 */
2845 @Deprecated
2846 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2847 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2848 /**
markchien68b67842020-03-19 13:37:43 +08002849 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien75721e42020-01-21 13:11:06 +08002850 * {@hide}
2851 */
markchien5bd499c2019-01-16 17:44:13 +08002852 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002853 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002854 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien75721e42020-01-21 13:11:06 +08002855 /**
2856 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2857 * {@hide}
2858 */
2859 @Deprecated
2860 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2861 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2862 /**
2863 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2864 * {@hide}
2865 */
markchien5bd499c2019-01-16 17:44:13 +08002866 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002867 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002868 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002869
2870 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002871 * Get a more detailed error code after a Tethering or Untethering
2872 * request asynchronously failed.
2873 *
2874 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002875 * @return error The error code of the last error tethering or untethering the named
2876 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002877 *
markchien75721e42020-01-21 13:11:06 +08002878 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002879 * {@hide}
2880 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002881 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002882 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien75721e42020-01-21 13:11:06 +08002883 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002884 public int getLastTetherError(String iface) {
markchien68b67842020-03-19 13:37:43 +08002885 int error = mTetheringManager.getLastTetherError(iface);
2886 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2887 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2888 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2889 // instead.
2890 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2891 }
2892 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002893 }
2894
markchiendd41c822019-03-06 16:25:00 +08002895 /** @hide */
2896 @Retention(RetentionPolicy.SOURCE)
2897 @IntDef(value = {
2898 TETHER_ERROR_NO_ERROR,
2899 TETHER_ERROR_PROVISION_FAILED,
2900 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2901 })
2902 public @interface EntitlementResultCode {
2903 }
2904
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002905 /**
markchiendd41c822019-03-06 16:25:00 +08002906 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08002907 * entitlement succeeded.
markchien75721e42020-01-21 13:11:06 +08002908 *
2909 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08002910 * @hide
2911 */
2912 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002913 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08002914 public interface OnTetheringEntitlementResultListener {
2915 /**
2916 * Called to notify entitlement result.
2917 *
2918 * @param resultCode an int value of entitlement result. It may be one of
2919 * {@link #TETHER_ERROR_NO_ERROR},
2920 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2921 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2922 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07002923 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08002924 }
2925
2926 /**
markchien5bd499c2019-01-16 17:44:13 +08002927 * Get the last value of the entitlement check on this downstream. If the cached value is
2928 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2929 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2930 * guaranteed that the UI-based entitlement check will complete in any specific time period
2931 * and may in fact never complete. Any successful entitlement check the platform performs for
2932 * any reason will update the cached value.
2933 *
2934 * @param type the downstream type of tethering. Must be one of
2935 * {@link #TETHERING_WIFI},
2936 * {@link #TETHERING_USB}, or
2937 * {@link #TETHERING_BLUETOOTH}.
2938 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08002939 * @param executor the executor on which callback will be invoked.
2940 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2941 * notify the caller of the result of entitlement check. The listener may be called zero
2942 * or one time.
markchien75721e42020-01-21 13:11:06 +08002943 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08002944 * {@hide}
2945 */
2946 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002947 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08002948 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08002949 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2950 @NonNull @CallbackExecutor Executor executor,
2951 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002952 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchiendd41c822019-03-06 16:25:00 +08002953 ResultReceiver wrappedListener = new ResultReceiver(null) {
2954 @Override
2955 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslin9cc04192021-03-04 09:38:21 +08002956 final long token = Binder.clearCallingIdentity();
2957 try {
2958 executor.execute(() -> {
2959 listener.onTetheringEntitlementResult(resultCode);
2960 });
2961 } finally {
2962 Binder.restoreCallingIdentity(token);
2963 }
markchiendd41c822019-03-06 16:25:00 +08002964 }
2965 };
2966
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002967 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienb0bb7862019-12-16 20:15:20 +08002968 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08002969 }
2970
2971 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002972 * Report network connectivity status. This is currently used only
2973 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04002974 * <p>This method requires the caller to hold the permission
2975 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08002976 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002977 * @param networkType The type of network you want to report on
2978 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09002979 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002980 * {@hide}
2981 */
2982 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09002983 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002984 try {
2985 mService.reportInetCondition(networkType, percentage);
2986 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002987 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002988 }
2989 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002990
2991 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002992 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07002993 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002994 * the framework to re-evaluate network connectivity and/or switch to another
2995 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002996 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002997 * @param network The {@link Network} the application was attempting to use
2998 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04002999 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3000 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003001 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003002 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09003003 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003004 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003005 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04003006 // One of these will be ignored because it matches system's current state.
3007 // The other will trigger the necessary reevaluation.
3008 mService.reportNetworkConnectivity(network, true);
3009 mService.reportNetworkConnectivity(network, false);
3010 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003011 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003012 }
3013 }
3014
3015 /**
3016 * Report to the framework whether a network has working connectivity.
3017 * This provides a hint to the system that a particular network is providing
3018 * working connectivity or not. In response the framework may re-evaluate
3019 * the network's connectivity and might take further action thereafter.
3020 *
3021 * @param network The {@link Network} the application was attempting to use
3022 * or {@code null} to indicate the current default network.
3023 * @param hasConnectivity {@code true} if the application was able to successfully access the
3024 * Internet using {@code network} or {@code false} if not.
3025 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003026 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003027 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003028 try {
3029 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003030 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003031 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003032 }
3033 }
3034
3035 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003036 * Set a network-independent global http proxy. This is not normally what you want
3037 * for typical HTTP proxies - they are general network dependent. However if you're
3038 * doing something unusual like general internal filtering this may be useful. On
3039 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003040 *
3041 * @param p A {@link ProxyInfo} object defining the new global
3042 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003043 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003044 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003045 @SystemApi(client = MODULE_LIBRARIES)
paulhuec0a9632019-08-12 16:25:11 +08003046 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003047 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003048 try {
3049 mService.setGlobalProxy(p);
3050 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003051 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003052 }
3053 }
3054
3055 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003056 * Retrieve any network-independent global HTTP proxy.
3057 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003058 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003059 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003060 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003061 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003062 @SystemApi(client = MODULE_LIBRARIES)
3063 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04003064 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003065 try {
3066 return mService.getGlobalProxy();
3067 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003068 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003069 }
3070 }
3071
3072 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003073 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3074 * network-specific HTTP proxy. If {@code network} is null, the
3075 * network-specific proxy returned is the proxy of the default active
3076 * network.
3077 *
3078 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3079 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3080 * or when {@code network} is {@code null},
3081 * the {@code ProxyInfo} for the default active network. Returns
3082 * {@code null} when no proxy applies or the caller doesn't have
3083 * permission to use {@code network}.
3084 * @hide
3085 */
3086 public ProxyInfo getProxyForNetwork(Network network) {
3087 try {
3088 return mService.getProxyForNetwork(network);
3089 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003090 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003091 }
3092 }
3093
3094 /**
Paul Jensen12131352014-12-10 15:12:18 -05003095 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3096 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003097 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003098 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003099 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003100 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003101 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003102 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003103 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003104 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003105 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003106 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003107
3108 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003109 * Returns true if the hardware supports the given network type
3110 * else it returns false. This doesn't indicate we have coverage
3111 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003112 * hardware supports it. For example a GSM phone without a SIM
3113 * should still return {@code true} for mobile data, but a wifi only
3114 * tablet would return {@code false}.
3115 *
3116 * @param networkType The network type we'd like to check
3117 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003118 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003119 * @hide
3120 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003121 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003122 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003123 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003124 public boolean isNetworkSupported(int networkType) {
3125 try {
3126 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003127 } catch (RemoteException e) {
3128 throw e.rethrowFromSystemServer();
3129 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003130 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003131
3132 /**
3133 * Returns if the currently active data network is metered. A network is
3134 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003135 * that connection due to monetary costs, data limitations or
3136 * battery/performance issues. You should check this before doing large
3137 * data transfers, and warn the user or delay the operation until another
3138 * network is available.
3139 *
3140 * @return {@code true} if large transfers should be avoided, otherwise
3141 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003142 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003143 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003144 public boolean isActiveNetworkMetered() {
3145 try {
3146 return mService.isActiveNetworkMetered();
3147 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003148 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003149 }
3150 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003151
Robert Greenwalt26744a52013-02-15 10:56:35 -08003152 /**
Sarah Chincab74db2020-11-25 12:15:14 -08003153 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003154 *
Sarah Chincab74db2020-11-25 12:15:14 -08003155 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003156 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003157 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003158 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003159 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003160 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003161 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003162 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003163 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003164 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003165 }
3166 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003167
3168 /**
3169 * Set the value for enabling/disabling airplane mode
3170 *
3171 * @param enable whether to enable airplane mode or not
3172 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003173 * @hide
3174 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003175 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003176 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003177 android.Manifest.permission.NETWORK_SETTINGS,
3178 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3179 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003180 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003181 public void setAirplaneMode(boolean enable) {
3182 try {
3183 mService.setAirplaneMode(enable);
3184 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003185 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003186 }
3187 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003188
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003189 /**
3190 * Registers the specified {@link NetworkProvider}.
3191 * Each listener must only be registered once. The listener can be unregistered with
3192 * {@link #unregisterNetworkProvider}.
3193 *
3194 * @param provider the provider to register
3195 * @return the ID of the provider. This ID must be used by the provider when registering
3196 * {@link android.net.NetworkAgent}s.
3197 * @hide
3198 */
3199 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003200 @RequiresPermission(anyOf = {
3201 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3202 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003203 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3204 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003205 throw new IllegalStateException("NetworkProviders can only be registered once");
3206 }
3207
3208 try {
3209 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3210 provider.getName());
3211 provider.setProviderId(providerId);
3212 } catch (RemoteException e) {
3213 throw e.rethrowFromSystemServer();
3214 }
3215 return provider.getProviderId();
3216 }
3217
3218 /**
3219 * Unregisters the specified NetworkProvider.
3220 *
3221 * @param provider the provider to unregister
3222 * @hide
3223 */
3224 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003225 @RequiresPermission(anyOf = {
3226 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3227 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003228 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3229 try {
3230 mService.unregisterNetworkProvider(provider.getMessenger());
3231 } catch (RemoteException e) {
3232 throw e.rethrowFromSystemServer();
3233 }
3234 provider.setProviderId(NetworkProvider.ID_NONE);
3235 }
3236
3237
3238 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003239 @RequiresPermission(anyOf = {
3240 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3241 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003242 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3243 try {
3244 mService.declareNetworkRequestUnfulfillable(request);
3245 } catch (RemoteException e) {
3246 throw e.rethrowFromSystemServer();
3247 }
3248 }
3249
Paul Jensenc2569432015-02-13 14:18:39 -05003250 /**
3251 * @hide
3252 * Register a NetworkAgent with ConnectivityService.
Chalard Jean1aea87a2019-12-13 19:47:12 +09003253 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003254 */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003255 @RequiresPermission(anyOf = {
3256 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3257 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003258 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeandd753522020-12-21 18:36:52 +09003259 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3260 int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003261 try {
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003262 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003263 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003264 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003265 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003266 }
3267
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003268 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003269 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3270 * changes. Should be extended by applications wanting notifications.
3271 *
3272 * A {@code NetworkCallback} is registered by calling
3273 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3274 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003275 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003276 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3277 * A {@code NetworkCallback} should be registered at most once at any time.
3278 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003279 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003280 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003281 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003282 * No flags associated with this callback.
3283 * @hide
3284 */
3285 public static final int FLAG_NONE = 0;
3286 /**
3287 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3288 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3289 * <p>
3290 * These include:
3291 * <li> Some transport info instances (retrieved via
3292 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3293 * contain location sensitive information.
3294 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3295 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3296 * </p>
3297 * <p>
3298 * Note:
3299 * <li> Retrieving this location sensitive information (subject to app's location
3300 * permissions) will be noted by system. </li>
3301 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3302 * not include location sensitive info.
3303 * </p>
3304 */
3305 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3306
3307 /** @hide */
3308 @Retention(RetentionPolicy.SOURCE)
3309 @IntDef(flag = true, prefix = "FLAG_", value = {
3310 FLAG_NONE,
3311 FLAG_INCLUDE_LOCATION_INFO
3312 })
3313 public @interface Flag { }
3314
3315 /**
3316 * All the valid flags for error checking.
3317 */
3318 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3319
3320 public NetworkCallback() {
3321 this(FLAG_NONE);
3322 }
3323
3324 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003325 if ((flags & VALID_FLAGS) != flags) {
3326 throw new IllegalArgumentException("Invalid flags");
3327 }
Roshan Pius7992afd2020-12-22 15:10:42 -08003328 mFlags = flags;
3329 }
3330
3331 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003332 * Called when the framework connects to a new network to evaluate whether it satisfies this
3333 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3334 * callback. There is no guarantee that this new network will satisfy any requests, or that
3335 * the network will stay connected for longer than the time necessary to evaluate it.
3336 * <p>
3337 * Most applications <b>should not</b> act on this callback, and should instead use
3338 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3339 * the framework in properly evaluating the network &mdash; for example, an application that
3340 * can automatically log in to a captive portal without user intervention.
3341 *
3342 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003343 *
3344 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003345 */
paulhua9a6e2a2019-03-22 16:35:06 +08003346 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003347
3348 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003349 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003350 * This callback may be called more than once if the {@link Network} that is
3351 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003352 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003353 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003354 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3355 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003356 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003357 * @hide
3358 */
paulhua9a6e2a2019-03-22 16:35:06 +08003359 public void onAvailable(@NonNull Network network,
3360 @NonNull NetworkCapabilities networkCapabilities,
3361 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003362 // Internally only this method is called when a new network is available, and
3363 // it calls the callback in the same way and order that older versions used
3364 // to call so as not to change the behavior.
3365 onAvailable(network);
3366 if (!networkCapabilities.hasCapability(
3367 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3368 onNetworkSuspended(network);
3369 }
3370 onCapabilitiesChanged(network, networkCapabilities);
3371 onLinkPropertiesChanged(network, linkProperties);
junyulai5ab727b2018-08-07 19:50:45 +08003372 onBlockedStatusChanged(network, blocked);
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003373 }
3374
3375 /**
3376 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003377 *
3378 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3379 * be available at the same time, and onAvailable will be called for each of these as they
3380 * appear.
3381 *
3382 * <p>For callbacks registered with {@link #requestNetwork} and
3383 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3384 * is the new best network for this request and is now tracked by this callback ; this
3385 * callback will no longer receive method calls about other networks that may have been
3386 * passed to this method previously. The previously-best network may have disconnected, or
3387 * it may still be around and the newly-best network may simply be better.
3388 *
3389 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3390 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3391 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3392 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3393 *
3394 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3395 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3396 * this callback as this is prone to race conditions (there is no guarantee the objects
3397 * returned by these methods will be current). Instead, wait for a call to
3398 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3399 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3400 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003401 *
3402 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003403 */
paulhua9a6e2a2019-03-22 16:35:06 +08003404 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003405
3406 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003407 * Called when the network is about to be lost, typically because there are no outstanding
3408 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3409 * with the new replacement network for graceful handover. This method is not guaranteed
3410 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3411 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003412 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003413 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3414 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3415 * this callback as this is prone to race conditions ; calling these methods while in a
3416 * callback may return an outdated or even a null object.
3417 *
3418 * @param network The {@link Network} that is about to be lost.
3419 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3420 * connected for graceful handover; note that the network may still
3421 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003422 */
paulhua9a6e2a2019-03-22 16:35:06 +08003423 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003424
3425 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003426 * Called when a network disconnects or otherwise no longer satisfies this request or
3427 * callback.
3428 *
3429 * <p>If the callback was registered with requestNetwork() or
3430 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3431 * returned by onAvailable() when that network is lost and no other network satisfies
3432 * the criteria of the request.
3433 *
3434 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3435 * each network which no longer satisfies the criteria of the callback.
3436 *
3437 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3438 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3439 * this callback as this is prone to race conditions ; calling these methods while in a
3440 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003441 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003442 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003443 */
paulhua9a6e2a2019-03-22 16:35:06 +08003444 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003445
3446 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003447 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003448 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3449 * requested network request cannot be fulfilled (whether or not a timeout was
3450 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003451 * {@link NetworkRequest} will have already been removed and released, as if
3452 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003453 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003454 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003455
3456 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003457 * Called when the network corresponding to this request changes capabilities but still
3458 * satisfies the requested criteria.
3459 *
3460 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3461 * to be called immediately after {@link #onAvailable}.
3462 *
3463 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3464 * ConnectivityManager methods in this callback as this is prone to race conditions :
3465 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003466 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003467 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius7992afd2020-12-22 15:10:42 -08003468 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003469 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003470 */
paulhua9a6e2a2019-03-22 16:35:06 +08003471 public void onCapabilitiesChanged(@NonNull Network network,
3472 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003473
3474 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003475 * Called when the network corresponding to this request changes {@link LinkProperties}.
3476 *
3477 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3478 * to be called immediately after {@link #onAvailable}.
3479 *
3480 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3481 * ConnectivityManager methods in this callback as this is prone to race conditions :
3482 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003483 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003484 * @param network The {@link Network} whose link properties have changed.
3485 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003486 */
paulhua9a6e2a2019-03-22 16:35:06 +08003487 public void onLinkPropertiesChanged(@NonNull Network network,
3488 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003489
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003490 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003491 * Called when the network the framework connected to for this request suspends data
3492 * transmission temporarily.
3493 *
3494 * <p>This generally means that while the TCP connections are still live temporarily
3495 * network data fails to transfer. To give a specific example, this is used on cellular
3496 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3497 * means read operations on sockets on this network will block once the buffers are
3498 * drained, and write operations will block once the buffers are full.
3499 *
3500 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3501 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3502 * this callback as this is prone to race conditions (there is no guarantee the objects
3503 * returned by these methods will be current).
3504 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003505 * @hide
3506 */
paulhua9a6e2a2019-03-22 16:35:06 +08003507 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003508
3509 /**
3510 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003511 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3512 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003513
3514 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3515 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3516 * this callback as this is prone to race conditions : calling these methods while in a
3517 * callback may return an outdated or even a null object.
3518 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003519 * @hide
3520 */
paulhua9a6e2a2019-03-22 16:35:06 +08003521 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003522
junyulai5ab727b2018-08-07 19:50:45 +08003523 /**
3524 * Called when access to the specified network is blocked or unblocked.
3525 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003526 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3527 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3528 * this callback as this is prone to race conditions : calling these methods while in a
3529 * callback may return an outdated or even a null object.
3530 *
junyulai5ab727b2018-08-07 19:50:45 +08003531 * @param network The {@link Network} whose blocked status has changed.
3532 * @param blocked The blocked status of this {@link Network}.
3533 */
junyulai61143782019-03-04 22:45:36 +08003534 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003535
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003536 private NetworkRequest networkRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -08003537 private final int mFlags;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003538 }
3539
Hugo Benichi145e3792017-05-11 13:16:17 +09003540 /**
3541 * Constant error codes used by ConnectivityService to communicate about failures and errors
3542 * across a Binder boundary.
3543 * @hide
3544 */
3545 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003546 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003547 }
3548
3549 /** @hide */
3550 public static class TooManyRequestsException extends RuntimeException {}
3551
3552 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3553 switch (e.errorCode) {
3554 case Errors.TOO_MANY_REQUESTS:
3555 return new TooManyRequestsException();
3556 default:
3557 Log.w(TAG, "Unknown service error code " + e.errorCode);
3558 return new RuntimeException(e);
3559 }
3560 }
3561
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003562 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003563 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003564 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003565 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003566 /** @hide arg1 = TTL */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003567 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003568 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003569 public static final int CALLBACK_LOST = 4;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003570 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003571 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003572 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003573 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003574 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003575 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003576 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003577 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003578 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003579 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003580 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003581 public static final int CALLBACK_RESUMED = 10;
junyulai5ab727b2018-08-07 19:50:45 +08003582 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003583 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003584
Erik Kline66721822015-11-25 12:49:38 +09003585 /** @hide */
3586 public static String getCallbackName(int whichCallback) {
3587 switch (whichCallback) {
3588 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3589 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3590 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3591 case CALLBACK_LOST: return "CALLBACK_LOST";
3592 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3593 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3594 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003595 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3596 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3597 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003598 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003599 default:
3600 return Integer.toString(whichCallback);
3601 }
3602 }
3603
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003604 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003605 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003606 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003607
Hugo Benichife3325f2016-07-06 22:53:17 +09003608 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003609 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003610 }
3611
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003612 CallbackHandler(Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003613 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003614 }
3615
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003616 @Override
3617 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003618 if (message.what == EXPIRE_LEGACY_REQUEST) {
3619 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3620 return;
3621 }
3622
3623 final NetworkRequest request = getObject(message, NetworkRequest.class);
3624 final Network network = getObject(message, Network.class);
3625 final NetworkCallback callback;
3626 synchronized (sCallbacks) {
3627 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003628 if (callback == null) {
3629 Log.w(TAG,
3630 "callback not found for " + getCallbackName(message.what) + " message");
3631 return;
3632 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003633 if (message.what == CALLBACK_UNAVAIL) {
3634 sCallbacks.remove(request);
3635 callback.networkRequest = ALREADY_UNREGISTERED;
3636 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003637 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003638 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003639 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003640 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003641
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003642 switch (message.what) {
3643 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003644 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003645 break;
3646 }
3647 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003648 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3649 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai5ab727b2018-08-07 19:50:45 +08003650 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003651 break;
3652 }
3653 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003654 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003655 break;
3656 }
3657 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003658 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003659 break;
3660 }
3661 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003662 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003663 break;
3664 }
3665 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003666 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3667 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003668 break;
3669 }
3670 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003671 LinkProperties lp = getObject(message, LinkProperties.class);
3672 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003673 break;
3674 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003675 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003676 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003677 break;
3678 }
3679 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003680 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003681 break;
3682 }
junyulai5ab727b2018-08-07 19:50:45 +08003683 case CALLBACK_BLK_CHANGED: {
3684 boolean blocked = message.arg1 != 0;
3685 callback.onBlockedStatusChanged(network, blocked);
3686 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003687 }
3688 }
3689
Hugo Benichife3325f2016-07-06 22:53:17 +09003690 private <T> T getObject(Message msg, Class<T> c) {
3691 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003692 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003693 }
3694
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003695 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003696 synchronized (sCallbacks) {
3697 if (sCallbackHandler == null) {
3698 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003699 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003700 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003701 }
3702 }
3703
Hugo Benichiec180d52017-02-03 14:18:44 +09003704 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3705 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003706
Hugo Benichiec180d52017-02-03 14:18:44 +09003707 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaid1a78162021-01-11 16:53:38 +08003708 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003709 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003710 checkCallbackNotNull(callback);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003711 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3712 throw new IllegalArgumentException("null NetworkCapabilities");
3713 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003714 final NetworkRequest request;
Roshan Piusd26ae412020-01-16 12:17:17 -08003715 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003716 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003717 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003718 if (callback.networkRequest != null
3719 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003720 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3721 // and requests (http://b/20701525).
3722 Log.e(TAG, "NetworkCallback was already registered");
3723 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003724 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003725 Binder binder = new Binder();
Roshan Pius7992afd2020-12-22 15:10:42 -08003726 final int callbackFlags = callback.mFlags;
junyulaid1a78162021-01-11 16:53:38 +08003727 if (reqType == LISTEN) {
Roshan Piusd26ae412020-01-16 12:17:17 -08003728 request = mService.listenForNetwork(
Roshan Pius7992afd2020-12-22 15:10:42 -08003729 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08003730 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003731 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003732 request = mService.requestNetwork(
junyulaid1a78162021-01-11 16:53:38 +08003733 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
Roshan Pius7992afd2020-12-22 15:10:42 -08003734 callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003735 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003736 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003737 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003738 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003739 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003740 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003741 } catch (RemoteException e) {
3742 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003743 } catch (ServiceSpecificException e) {
3744 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003745 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003746 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003747 }
3748
3749 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003750 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003751 *
markchien0fe11402020-03-18 21:16:15 +08003752 * This API is only for use in internal system code that requests networks with legacy type and
3753 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchien769c5752020-01-14 12:54:40 +08003754 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003755 *
markchien769c5752020-01-14 12:54:40 +08003756 * @param request {@link NetworkRequest} describing this request.
markchien769c5752020-01-14 12:54:40 +08003757 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3758 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3759 * be a positive value (i.e. >0).
3760 * @param legacyType to specify the network type(#TYPE_*).
3761 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien0fe11402020-03-18 21:16:15 +08003762 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3763 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003764 *
3765 * @hide
3766 */
markchien769c5752020-01-14 12:54:40 +08003767 @SystemApi
markchien0fe11402020-03-18 21:16:15 +08003768 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003769 public void requestNetwork(@NonNull NetworkRequest request,
markchien0fe11402020-03-18 21:16:15 +08003770 int timeoutMs, int legacyType, @NonNull Handler handler,
3771 @NonNull NetworkCallback networkCallback) {
3772 if (legacyType == TYPE_NONE) {
3773 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3774 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003775 CallbackHandler cbHandler = new CallbackHandler(handler);
3776 NetworkCapabilities nc = request.networkCapabilities;
3777 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003778 }
3779
3780 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003781 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003782 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003783 * <p>This method will attempt to find the best network that matches the passed
3784 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3785 * criteria. The platform will evaluate which network is the best at its own discretion.
3786 * Throughput, latency, cost per byte, policy, user preference and other considerations
3787 * may be factored in the decision of what is considered the best network.
3788 *
3789 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3790 * matching this request, while always attempting to match the request to a better network if
3791 * possible. If a better match is found, the platform will switch this request to the now-best
3792 * network and inform the app of the newly best network by invoking
3793 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3794 * will not try to maintain any other network than the best one currently matching the request:
3795 * a network not matching any network request may be disconnected at any time.
3796 *
3797 * <p>For example, an application could use this method to obtain a connected cellular network
3798 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3799 * radio to consume additional power. Or, an application could inform the system that it wants
3800 * a network supporting sending MMSes and have the system let it know about the currently best
3801 * MMS-supporting network through the provided {@link NetworkCallback}.
3802 *
3803 * <p>The status of the request can be followed by listening to the various callbacks described
3804 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3805 * used to direct traffic to the network (although accessing some networks may be subject to
3806 * holding specific permissions). Callers will learn about the specific characteristics of the
3807 * network through
3808 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3809 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3810 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3811 * matching the request at any given time; therefore when a better network matching the request
3812 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3813 * with the new network after which no further updates are given about the previously-best
3814 * network, unless it becomes the best again at some later time. All callbacks are invoked
3815 * in order on the same thread, which by default is a thread created by the framework running
3816 * in the app.
3817 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3818 * callbacks are invoked.
3819 *
3820 * <p>This{@link NetworkRequest} will live until released via
3821 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3822 * which point the system may let go of the network at any time.
3823 *
3824 * <p>A version of this method which takes a timeout is
3825 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3826 * wait for a limited amount of time for the network to become unavailable.
3827 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003828 * <p>It is presently unsupported to request a network with mutable
3829 * {@link NetworkCapabilities} such as
3830 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3831 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3832 * as these {@code NetworkCapabilities} represent states that a particular
3833 * network may never attain, and whether a network will attain these states
3834 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09003835 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003836 *
3837 * <p>This method requires the caller to hold either the
3838 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3839 * or the ability to modify system settings as determined by
3840 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003841 *
Chalard Jean7f06b342020-05-20 16:11:50 +09003842 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3843 * number of outstanding requests to 100 per app (identified by their UID), shared with
3844 * all variants of this method, of {@link #registerNetworkCallback} as well as
3845 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3846 * Requesting a network with this method will count toward this limit. If this limit is
3847 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3848 * make sure to unregister the callbacks with
3849 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3850 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003851 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003852 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3853 * the callback must not be shared - it uniquely specifies this request.
3854 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09003855 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3856 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09003857 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003858 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003859 public void requestNetwork(@NonNull NetworkRequest request,
3860 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003861 requestNetwork(request, networkCallback, getDefaultHandler());
3862 }
3863
3864 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003865 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003866 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003867 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3868 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003869 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003870 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003871 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3872 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003873 *
3874 * @param request {@link NetworkRequest} describing this request.
3875 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3876 * the callback must not be shared - it uniquely specifies this request.
3877 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003878 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003879 public void requestNetwork(@NonNull NetworkRequest request,
3880 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003881 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08003882 NetworkCapabilities nc = request.networkCapabilities;
3883 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003884 }
3885
3886 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003887 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohen67e58a02017-03-01 12:47:28 -08003888 * by a timeout.
3889 *
3890 * This function behaves identically to the non-timed-out version
3891 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3892 * is not found within the given time (in milliseconds) the
3893 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3894 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3895 * not have to be released if timed-out (it is automatically released). Unregistering a
3896 * request that timed out is not an error.
3897 *
3898 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3899 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3900 * for that purpose. Calling this method will attempt to bring up the requested network.
3901 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003902 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003903 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3904 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08003905 *
3906 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003907 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3908 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003909 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3910 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3911 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08003912 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003913 public void requestNetwork(@NonNull NetworkRequest request,
3914 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003915 checkTimeout(timeoutMs);
markchien0fe11402020-03-18 21:16:15 +08003916 NetworkCapabilities nc = request.networkCapabilities;
3917 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3918 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003919 }
3920
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003921 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003922 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003923 * by a timeout.
3924 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003925 * This method behaves identically to
3926 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3927 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08003928 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003929 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003930 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3931 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003932 *
3933 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003934 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3935 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003936 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003937 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3938 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003939 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003940 public void requestNetwork(@NonNull NetworkRequest request,
3941 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003942 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003943 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08003944 NetworkCapabilities nc = request.networkCapabilities;
3945 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003946 }
3947
3948 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003949 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003950 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003951 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08003952 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04003953 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3954 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003955 */
Erik Klinefb087f12014-11-19 12:12:24 +09003956 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003957
3958 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003959 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003960 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003961 * {@link android.content.Intent#getParcelableExtra(String)}.
3962 */
Erik Klinefb087f12014-11-19 12:12:24 +09003963 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003964
3965
3966 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003967 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003968 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08003969 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003970 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003971 * the request may outlive the calling application and get called back when a suitable
3972 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003973 * <p>
3974 * The operation is an Intent broadcast that goes to a broadcast receiver that
3975 * you registered with {@link Context#registerReceiver} or through the
3976 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3977 * <p>
3978 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09003979 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3980 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003981 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003982 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003983 * Intent to reserve the network or it will be released shortly after the Intent
3984 * is processed.
3985 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04003986 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003987 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003988 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003989 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08003990 * The request may be released normally by calling
3991 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003992 * <p>It is presently unsupported to request a network with either
3993 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3994 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3995 * as these {@code NetworkCapabilities} represent states that a particular
3996 * network may never attain, and whether a network will attain these states
3997 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09003998 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003999 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004000 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4001 * number of outstanding requests to 100 per app (identified by their UID), shared with
4002 * all variants of this method, of {@link #registerNetworkCallback} as well as
4003 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4004 * Requesting a network with this method will count toward this limit. If this limit is
4005 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4006 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4007 * or {@link #releaseNetworkRequest(PendingIntent)}.
4008 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004009 * <p>This method requires the caller to hold either the
4010 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4011 * or the ability to modify system settings as determined by
4012 * {@link android.provider.Settings.System#canWrite}.</p>
4013 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004014 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004015 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004016 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08004017 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004018 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4019 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004020 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004021 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004022 public void requestNetwork(@NonNull NetworkRequest request,
4023 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004024 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004025 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004026 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004027 mService.pendingRequestForNetwork(
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07004028 request.networkCapabilities, operation, mContext.getOpPackageName(),
4029 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004030 } catch (RemoteException e) {
4031 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004032 } catch (ServiceSpecificException e) {
4033 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004034 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004035 }
4036
4037 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004038 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4039 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004040 * This method has the same behavior as
4041 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004042 * releasing network resources and disconnecting.
4043 *
4044 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4045 * PendingIntent passed to
4046 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4047 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4048 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004049 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004050 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004051 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004052 try {
4053 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004054 } catch (RemoteException e) {
4055 throw e.rethrowFromSystemServer();
4056 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004057 }
4058
Hugo Benichiff4bf602017-05-09 15:19:01 +09004059 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004060 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004061 }
4062
4063 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004064 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004065 }
4066
4067 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004068 if (timeoutMs <= 0) {
4069 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4070 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004071 }
4072
4073 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004074 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004075 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004076 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4077 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004078 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004079 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4080 * number of outstanding requests to 100 per app (identified by their UID), shared with
4081 * all variants of this method, of {@link #requestNetwork} as well as
4082 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4083 * Requesting a network with this method will count toward this limit. If this limit is
4084 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4085 * make sure to unregister the callbacks with
4086 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4087 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004088 * @param request {@link NetworkRequest} describing this request.
4089 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4090 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004091 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004092 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004093 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004094 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004095 public void registerNetworkCallback(@NonNull NetworkRequest request,
4096 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004097 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4098 }
4099
4100 /**
4101 * Registers to receive notifications about all networks which satisfy the given
4102 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004103 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4104 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004105 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004106 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4107 * number of outstanding requests to 100 per app (identified by their UID), shared with
4108 * all variants of this method, of {@link #requestNetwork} as well as
4109 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4110 * Requesting a network with this method will count toward this limit. If this limit is
4111 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4112 * make sure to unregister the callbacks with
4113 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4114 *
4115 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004116 * @param request {@link NetworkRequest} describing this request.
4117 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4118 * networks change state.
4119 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004120 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004121 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004122 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004123 public void registerNetworkCallback(@NonNull NetworkRequest request,
4124 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004125 CallbackHandler cbHandler = new CallbackHandler(handler);
4126 NetworkCapabilities nc = request.networkCapabilities;
4127 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004128 }
4129
4130 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004131 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4132 * {@link NetworkRequest}.
4133 *
4134 * This function behaves identically to the version that takes a NetworkCallback, but instead
4135 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4136 * the request may outlive the calling application and get called back when a suitable
4137 * network is found.
4138 * <p>
4139 * The operation is an Intent broadcast that goes to a broadcast receiver that
4140 * you registered with {@link Context#registerReceiver} or through the
4141 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4142 * <p>
4143 * The operation Intent is delivered with two extras, a {@link Network} typed
4144 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4145 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4146 * the original requests parameters.
4147 * <p>
4148 * If there is already a request for this Intent registered (with the equality of
4149 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4150 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4151 * <p>
4152 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004153 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004154 *
4155 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4156 * number of outstanding requests to 100 per app (identified by their UID), shared with
4157 * all variants of this method, of {@link #requestNetwork} as well as
4158 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4159 * Requesting a network with this method will count toward this limit. If this limit is
4160 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4161 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4162 * or {@link #releaseNetworkRequest(PendingIntent)}.
4163 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004164 * @param request {@link NetworkRequest} describing this request.
4165 * @param operation Action to perform when the network is available (corresponds
4166 * to the {@link NetworkCallback#onAvailable} call. Typically
4167 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004168 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004169 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004170 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004171 public void registerNetworkCallback(@NonNull NetworkRequest request,
4172 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004173 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004174 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004175 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004176 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004177 request.networkCapabilities, operation, mContext.getOpPackageName(),
4178 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004179 } catch (RemoteException e) {
4180 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004181 } catch (ServiceSpecificException e) {
4182 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004183 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004184 }
4185
4186 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004187 * Registers to receive notifications about changes in the application's default network. This
4188 * may be a physical network or a virtual network, such as a VPN that applies to the
4189 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004190 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004191 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004192 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4193 * number of outstanding requests to 100 per app (identified by their UID), shared with
4194 * all variants of this method, of {@link #requestNetwork} as well as
4195 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4196 * Requesting a network with this method will count toward this limit. If this limit is
4197 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4198 * make sure to unregister the callbacks with
4199 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4200 *
Erik Klinee0aed632016-03-16 15:31:39 +09004201 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004202 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004203 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004204 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004205 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004206 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004207 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004208 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4209 }
4210
4211 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004212 * Registers to receive notifications about changes in the application's default network. This
4213 * may be a physical network or a virtual network, such as a VPN that applies to the
4214 * application. The callbacks will continue to be called until either the application exits or
4215 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4216 *
4217 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4218 * number of outstanding requests to 100 per app (identified by their UID), shared with
4219 * all variants of this method, of {@link #requestNetwork} as well as
4220 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4221 * Requesting a network with this method will count toward this limit. If this limit is
4222 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4223 * make sure to unregister the callbacks with
4224 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4225 *
4226 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4227 * application's default network changes.
4228 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4229 * @throws RuntimeException if the app already has too many callbacks registered.
4230 */
4231 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4232 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4233 @NonNull Handler handler) {
4234 CallbackHandler cbHandler = new CallbackHandler(handler);
4235 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4236 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4237 }
4238
4239 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004240 * Registers to receive notifications about changes in the system default network. The callbacks
4241 * will continue to be called until either the application exits or
4242 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004243 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004244 * This method should not be used to determine networking state seen by applications, because in
4245 * many cases, most or even all application traffic may not use the default network directly,
4246 * and traffic from different applications may go on different networks by default. As an
4247 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4248 * and not onto the system default network. Applications or system components desiring to do
4249 * determine network state as seen by applications should use other methods such as
4250 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4251 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004252 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4253 * number of outstanding requests to 100 per app (identified by their UID), shared with
4254 * all variants of this method, of {@link #requestNetwork} as well as
4255 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4256 * Requesting a network with this method will count toward this limit. If this limit is
4257 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4258 * make sure to unregister the callbacks with
4259 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4260 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004261 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4262 * system default network changes.
4263 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004264 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004265 *
4266 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004267 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004268 @SystemApi(client = MODULE_LIBRARIES)
4269 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4270 @RequiresPermission(anyOf = {
4271 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4272 android.Manifest.permission.NETWORK_SETTINGS})
4273 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004274 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004275 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004276 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004277 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004278 }
4279
4280 /**
junyulaibd622262021-03-15 11:48:48 +08004281 * Registers to receive notifications about the best matching network which satisfy the given
4282 * {@link NetworkRequest}. The callbacks will continue to be called until
4283 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4284 * called.
4285 *
4286 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4287 * number of outstanding requests to 100 per app (identified by their UID), shared with
4288 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4289 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4290 * Requesting a network with this method will count toward this limit. If this limit is
4291 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4292 * make sure to unregister the callbacks with
4293 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4294 *
4295 *
4296 * @param request {@link NetworkRequest} describing this request.
4297 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4298 * networks change state.
4299 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4300 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai6b0a6a22021-03-05 15:51:17 +08004301 */
junyulai6b0a6a22021-03-05 15:51:17 +08004302 @SuppressLint("ExecutorRegistration")
4303 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4304 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4305 final NetworkCapabilities nc = request.networkCapabilities;
4306 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai8cae3c72021-03-12 20:05:08 +08004307 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai6b0a6a22021-03-05 15:51:17 +08004308 }
4309
4310 /**
fenglu73169332015-04-21 17:12:05 -07004311 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4312 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4313 * network connection for updated bandwidth information. The caller will be notified via
4314 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004315 * method assumes that the caller has previously called
4316 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4317 * changes.
fenglu76564332015-03-20 11:29:56 -07004318 *
fenglu41808e82015-04-27 14:28:04 -07004319 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004320 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004321 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004322 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004323 try {
fenglu73169332015-04-21 17:12:05 -07004324 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004325 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004326 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004327 }
4328 }
4329
4330 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004331 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004332 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4333 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4334 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004335 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4336 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004337 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004338 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4339 * triggering it as soon as this call returns.
4340 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004341 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004342 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004343 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004344 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004345 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004346 final List<NetworkRequest> reqs = new ArrayList<>();
4347 // Find all requests associated to this callback and stop callback triggers immediately.
4348 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4349 synchronized (sCallbacks) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004350 if (networkCallback.networkRequest == null) {
4351 throw new IllegalArgumentException("NetworkCallback was not registered");
4352 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07004353 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4354 Log.d(TAG, "NetworkCallback was already unregistered");
4355 return;
4356 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004357 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4358 if (e.getValue() == networkCallback) {
4359 reqs.add(e.getKey());
4360 }
4361 }
4362 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4363 for (NetworkRequest r : reqs) {
4364 try {
4365 mService.releaseNetworkRequest(r);
4366 } catch (RemoteException e) {
4367 throw e.rethrowFromSystemServer();
4368 }
4369 // Only remove mapping if rpc was successful.
4370 sCallbacks.remove(r);
4371 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004372 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004373 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004374 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004375
4376 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004377 * Unregisters a callback previously registered via
4378 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4379 *
4380 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4381 * PendingIntent passed to
4382 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4383 * Cannot be null.
4384 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004385 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004386 releaseNetworkRequest(operation);
4387 }
4388
4389 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004390 * Informs the system whether it should switch to {@code network} regardless of whether it is
4391 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4392 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4393 * the system default network regardless of any other network that's currently connected. If
4394 * {@code always} is true, then the choice is remembered, so that the next time the user
4395 * connects to this network, the system will switch to it.
4396 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004397 * @param network The network to accept.
4398 * @param accept Whether to accept the network even if unvalidated.
4399 * @param always Whether to remember this choice in the future.
4400 *
4401 * @hide
4402 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004403 @SystemApi(client = MODULE_LIBRARIES)
4404 @RequiresPermission(anyOf = {
4405 android.Manifest.permission.NETWORK_SETTINGS,
4406 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4407 android.Manifest.permission.NETWORK_STACK,
4408 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4409 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004410 try {
4411 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004412 } catch (RemoteException e) {
4413 throw e.rethrowFromSystemServer();
4414 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004415 }
4416
4417 /**
lucaslin25a50472019-03-12 13:08:03 +08004418 * Informs the system whether it should consider the network as validated even if it only has
4419 * partial connectivity. If {@code accept} is true, then the network will be considered as
4420 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4421 * is remembered, so that the next time the user connects to this network, the system will
4422 * switch to it.
4423 *
4424 * @param network The network to accept.
4425 * @param accept Whether to consider the network as validated even if it has partial
4426 * connectivity.
4427 * @param always Whether to remember this choice in the future.
4428 *
4429 * @hide
4430 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004431 @SystemApi(client = MODULE_LIBRARIES)
4432 @RequiresPermission(anyOf = {
4433 android.Manifest.permission.NETWORK_SETTINGS,
4434 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4435 android.Manifest.permission.NETWORK_STACK,
4436 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4437 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4438 boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004439 try {
4440 mService.setAcceptPartialConnectivity(network, accept, always);
4441 } catch (RemoteException e) {
4442 throw e.rethrowFromSystemServer();
4443 }
4444 }
4445
4446 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004447 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4448 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4449 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4450 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4451 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004452 * @param network The network to accept.
4453 *
4454 * @hide
4455 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004456 @SystemApi(client = MODULE_LIBRARIES)
4457 @RequiresPermission(anyOf = {
4458 android.Manifest.permission.NETWORK_SETTINGS,
4459 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4460 android.Manifest.permission.NETWORK_STACK,
4461 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4462 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004463 try {
4464 mService.setAvoidUnvalidated(network);
4465 } catch (RemoteException e) {
4466 throw e.rethrowFromSystemServer();
4467 }
4468 }
4469
4470 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004471 * Requests that the system open the captive portal app on the specified network.
4472 *
4473 * @param network The network to log into.
4474 *
4475 * @hide
4476 */
paulhuec0a9632019-08-12 16:25:11 +08004477 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004478 public void startCaptivePortalApp(Network network) {
4479 try {
4480 mService.startCaptivePortalApp(network);
4481 } catch (RemoteException e) {
4482 throw e.rethrowFromSystemServer();
4483 }
4484 }
4485
4486 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004487 * Requests that the system open the captive portal app with the specified extras.
4488 *
4489 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4490 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004491 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004492 * @param appExtras Extras to include in the app start intent.
4493 * @hide
4494 */
4495 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004496 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004497 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004498 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004499 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004500 } catch (RemoteException e) {
4501 throw e.rethrowFromSystemServer();
4502 }
4503 }
4504
4505 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004506 * Determine whether the device is configured to avoid bad wifi.
4507 * @hide
4508 */
4509 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004510 @RequiresPermission(anyOf = {
4511 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4512 android.Manifest.permission.NETWORK_STACK})
4513 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004514 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004515 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004516 } catch (RemoteException e) {
4517 throw e.rethrowFromSystemServer();
4518 }
4519 }
4520
4521 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004522 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4523 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004524 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4525 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004526 *
4527 * An example of such an operation might be a time-sensitive foreground activity, such as a
4528 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4529 */
4530 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4531
4532 /**
4533 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4534 * a backup channel for traffic that is primarily going over another network.
4535 *
4536 * An example might be maintaining backup connections to peers or servers for the purpose of
4537 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4538 * on backup paths should be negligible compared to the traffic on the main path.
4539 */
4540 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4541
4542 /**
4543 * It is acceptable to use metered data to improve network latency and performance.
4544 */
4545 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4546
4547 /**
4548 * Return value to use for unmetered networks. On such networks we currently set all the flags
4549 * to true.
4550 * @hide
4551 */
4552 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4553 MULTIPATH_PREFERENCE_HANDOVER |
4554 MULTIPATH_PREFERENCE_RELIABILITY |
4555 MULTIPATH_PREFERENCE_PERFORMANCE;
4556
4557 /** @hide */
4558 @Retention(RetentionPolicy.SOURCE)
4559 @IntDef(flag = true, value = {
4560 MULTIPATH_PREFERENCE_HANDOVER,
4561 MULTIPATH_PREFERENCE_RELIABILITY,
4562 MULTIPATH_PREFERENCE_PERFORMANCE,
4563 })
4564 public @interface MultipathPreference {
4565 }
4566
4567 /**
4568 * Provides a hint to the calling application on whether it is desirable to use the
4569 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4570 * for multipath data transfer on this network when it is not the system default network.
4571 * Applications desiring to use multipath network protocols should call this method before
4572 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004573 *
4574 * @param network The network on which the application desires to use multipath data.
4575 * If {@code null}, this method will return the a preference that will generally
4576 * apply to metered networks.
4577 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4578 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004579 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004580 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004581 try {
4582 return mService.getMultipathPreference(network);
4583 } catch (RemoteException e) {
4584 throw e.rethrowFromSystemServer();
4585 }
4586 }
4587
4588 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004589 * Resets all connectivity manager settings back to factory defaults.
4590 * @hide
4591 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004592 @SystemApi(client = MODULE_LIBRARIES)
4593 @RequiresPermission(anyOf = {
4594 android.Manifest.permission.NETWORK_SETTINGS,
4595 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scottd3bb5082015-03-30 13:17:11 -07004596 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004597 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004598 mService.factoryReset();
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00004599 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004600 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004601 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004602 }
4603 }
4604
4605 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004606 * Binds the current process to {@code network}. All Sockets created in the future
4607 * (and not explicitly bound via a bound SocketFactory from
4608 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4609 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4610 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4611 * work and all host name resolutions will fail. This is by design so an application doesn't
4612 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4613 * To clear binding pass {@code null} for {@code network}. Using individually bound
4614 * Sockets created by Network.getSocketFactory().createSocket() and
4615 * performing network-specific host name resolutions via
4616 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004617 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004618 *
4619 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4620 * the current binding.
4621 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4622 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004623 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004624 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004625 // instantiated.
4626 return setProcessDefaultNetwork(network);
4627 }
4628
4629 /**
4630 * Binds the current process to {@code network}. All Sockets created in the future
4631 * (and not explicitly bound via a bound SocketFactory from
4632 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4633 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4634 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4635 * work and all host name resolutions will fail. This is by design so an application doesn't
4636 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4637 * To clear binding pass {@code null} for {@code network}. Using individually bound
4638 * Sockets created by Network.getSocketFactory().createSocket() and
4639 * performing network-specific host name resolutions via
4640 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4641 * {@code setProcessDefaultNetwork}.
4642 *
4643 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4644 * the current binding.
4645 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4646 * @deprecated This function can throw {@link IllegalStateException}. Use
4647 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4648 * is a direct replacement.
4649 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004650 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004651 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004652 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004653 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4654
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004655 if (netId != NETID_UNSET) {
4656 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004657 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004658
4659 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4660 return false;
4661 }
4662
4663 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004664 // Set HTTP proxy system properties to match network.
4665 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004666 try {
Remi NGUYEN VANa1860ff2021-02-03 10:18:20 +09004667 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004668 } catch (SecurityException e) {
4669 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4670 Log.e(TAG, "Can't set proxy properties", e);
4671 }
Paul Jensen99c36662014-08-27 12:38:45 -04004672 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN33e3abb2021-03-18 23:27:19 +09004673 InetAddressCompat.clearDnsCache();
Paul Jensen99c36662014-08-27 12:38:45 -04004674 // Must flush socket pool as idle sockets will be bound to previous network and may
4675 // cause subsequent fetches to be performed on old network.
4676 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004677 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004678
4679 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004680 }
4681
4682 /**
4683 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004684 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004685 *
4686 * @return {@code Network} to which this process is bound, or {@code null}.
4687 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004688 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004689 public Network getBoundNetworkForProcess() {
4690 // Forcing callers to call thru non-static function ensures ConnectivityManager
4691 // instantiated.
4692 return getProcessDefaultNetwork();
4693 }
4694
4695 /**
4696 * Returns the {@link Network} currently bound to this process via
4697 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4698 *
4699 * @return {@code Network} to which this process is bound, or {@code null}.
4700 * @deprecated Using this function can lead to other functions throwing
4701 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4702 * {@code getBoundNetworkForProcess} is a direct replacement.
4703 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004704 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004705 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004706 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004707 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004708 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004709 return new Network(netId);
4710 }
4711
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004712 private void unsupportedStartingFrom(int version) {
4713 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004714 // The getApplicationInfo() call we make below is not supported in system context. Let
4715 // the call through here, and rely on the fact that ConnectivityService will refuse to
4716 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004717 return;
4718 }
4719
4720 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4721 throw new UnsupportedOperationException(
4722 "This method is not supported in target SDK version " + version + " and above");
4723 }
4724 }
4725
4726 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4727 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004728 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004729 // remove these exemptions. Note that this check is not secure, and apps can still access these
4730 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4731 // so is unsupported and may break in the future. http://b/22728205
4732 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07004733 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004734 }
4735
Paul Jensene98c6e02014-05-29 10:12:39 -04004736 /**
4737 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04004738 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04004739 *
4740 * @param network The {@link Network} to bind host resolutions from the current process to, or
4741 * {@code null} to clear the current binding.
4742 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4743 * @hide
4744 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4745 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004746 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00004747 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04004748 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04004749 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09004750 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04004751 }
Felipe Lemed16384b2016-01-22 09:44:57 -08004752
4753 /**
4754 * Device is not restricting metered network activity while application is running on
4755 * background.
4756 */
4757 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4758
4759 /**
4760 * Device is restricting metered network activity while application is running on background,
4761 * but application is allowed to bypass it.
4762 * <p>
4763 * In this state, application should take action to mitigate metered network access.
4764 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4765 */
4766 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4767
4768 /**
4769 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08004770 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08004771 * In this state, application should not try to use the network while running on background,
4772 * because it would be denied.
4773 */
4774 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4775
Felipe Leme6a5b7692016-01-27 14:46:39 -08004776 /**
4777 * A change in the background metered network activity restriction has occurred.
4778 * <p>
4779 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4780 * applies to them.
4781 * <p>
4782 * This is only sent to registered receivers, not manifest receivers.
4783 */
4784 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4785 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4786 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4787
Felipe Leme1b42ef92016-01-25 11:48:04 -08004788 /** @hide */
4789 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08004790 @IntDef(flag = false, value = {
4791 RESTRICT_BACKGROUND_STATUS_DISABLED,
4792 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4793 RESTRICT_BACKGROUND_STATUS_ENABLED,
4794 })
Felipe Lemed16384b2016-01-22 09:44:57 -08004795 public @interface RestrictBackgroundStatus {
4796 }
4797
Felipe Lemed16384b2016-01-22 09:44:57 -08004798 /**
4799 * Determines if the calling application is subject to metered network restrictions while
4800 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07004801 *
4802 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4803 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4804 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08004805 */
4806 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4807 try {
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09004808 return mService.getRestrictBackgroundStatusByCaller();
Felipe Lemed16384b2016-01-22 09:44:57 -08004809 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004810 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08004811 }
4812 }
Ricky Waid53cf002018-01-23 04:09:45 +00004813
4814 /**
4815 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00004816 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4817 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00004818 *
4819 * @return Hash of network watchlist config file. Null if config does not exist.
4820 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004821 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00004822 public byte[] getNetworkWatchlistConfigHash() {
4823 try {
4824 return mService.getNetworkWatchlistConfigHash();
4825 } catch (RemoteException e) {
4826 Log.e(TAG, "Unable to get watchlist config hash");
4827 throw e.rethrowFromSystemServer();
4828 }
4829 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004830
4831 /**
4832 * Returns the {@code uid} of the owner of a network connection.
4833 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08004834 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4835 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004836 * @param local The local {@link InetSocketAddress} of a connection.
4837 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004838 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08004839 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4840 * android.os.Process#INVALID_UID} if the connection is not found.
4841 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4842 * user.
4843 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004844 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08004845 public int getConnectionOwnerUid(
4846 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004847 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4848 try {
4849 return mService.getConnectionOwnerUid(connectionInfo);
4850 } catch (RemoteException e) {
4851 throw e.rethrowFromSystemServer();
4852 }
4853 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004854
4855 private void printStackTrace() {
4856 if (DEBUG) {
4857 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4858 final StringBuffer sb = new StringBuffer();
4859 for (int i = 3; i < callStack.length; i++) {
4860 final String stackTrace = callStack[i].toString();
4861 if (stackTrace == null || stackTrace.contains("android.os")) {
4862 break;
4863 }
4864 sb.append(" [").append(stackTrace).append("]");
4865 }
4866 Log.d(TAG, "StackLog:" + sb.toString());
4867 }
4868 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004869
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004870 /** @hide */
4871 public TestNetworkManager startOrGetTestNetworkManager() {
4872 final IBinder tnBinder;
4873 try {
4874 tnBinder = mService.startOrGetTestNetworkService();
4875 } catch (RemoteException e) {
4876 throw e.rethrowFromSystemServer();
4877 }
4878
4879 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4880 }
4881
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004882 /** @hide */
4883 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4884 return new ConnectivityDiagnosticsManager(mContext, mService);
4885 }
4886
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004887 /**
4888 * Simulates a Data Stall for the specified Network.
4889 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004890 * <p>This method should only be used for tests.
4891 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004892 * <p>The caller must be the owner of the specified Network.
4893 *
4894 * @param detectionMethod The detection method used to identify the Data Stall.
4895 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4896 * @param network The Network for which a Data Stall is being simluated.
4897 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4898 * @throws SecurityException if the caller is not the owner of the given network.
4899 * @hide
4900 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004901 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004902 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4903 android.Manifest.permission.NETWORK_STACK})
4904 public void simulateDataStall(int detectionMethod, long timestampMillis,
4905 @NonNull Network network, @NonNull PersistableBundle extras) {
4906 try {
4907 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4908 } catch (RemoteException e) {
4909 e.rethrowFromSystemServer();
4910 }
4911 }
James Mattisdcea9fb2020-10-28 21:48:54 -07004912
Daniel Bright60f02ed2020-06-15 16:10:01 -07004913 @NonNull
4914 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4915
4916 /**
4917 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4918 * receive available QoS events related to the {@link Network} and local ip + port
4919 * specified within socketInfo.
4920 * <p/>
4921 * The same {@link QosCallback} must be unregistered before being registered a second time,
4922 * otherwise {@link QosCallbackRegistrationException} is thrown.
4923 * <p/>
4924 * This API does not, in itself, require any permission if called with a network that is not
4925 * restricted. However, the underlying implementation currently only supports the IMS network,
4926 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4927 * useful, because they'd never be called back on networks that they would have access to.
4928 *
4929 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4930 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4931 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4932 * @throws RuntimeException if the app already has too many callbacks registered.
4933 *
4934 * Exceptions after the time of registration is passed through
4935 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4936 *
4937 * @param socketInfo the socket information used to match QoS events
4938 * @param callback receives qos events that satisfy socketInfo
4939 * @param executor The executor on which the callback will be invoked. The provided
4940 * {@link Executor} must run callback sequentially, otherwise the order of
4941 * callbacks cannot be guaranteed.
4942 *
4943 * @hide
4944 */
4945 @SystemApi
4946 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4947 @NonNull final QosCallback callback,
4948 @CallbackExecutor @NonNull final Executor executor) {
4949 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4950 Objects.requireNonNull(callback, "callback must be non-null");
4951 Objects.requireNonNull(executor, "executor must be non-null");
4952
4953 try {
4954 synchronized (mQosCallbackConnections) {
4955 if (getQosCallbackConnection(callback) == null) {
4956 final QosCallbackConnection connection =
4957 new QosCallbackConnection(this, callback, executor);
4958 mQosCallbackConnections.add(connection);
4959 mService.registerQosSocketCallback(socketInfo, connection);
4960 } else {
4961 Log.e(TAG, "registerQosCallback: Callback already registered");
4962 throw new QosCallbackRegistrationException();
4963 }
4964 }
4965 } catch (final RemoteException e) {
4966 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4967
4968 // The same unregister method method is called for consistency even though nothing
4969 // will be sent to the ConnectivityService since the callback was never successfully
4970 // registered.
4971 unregisterQosCallback(callback);
4972 e.rethrowFromSystemServer();
4973 } catch (final ServiceSpecificException e) {
4974 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4975 unregisterQosCallback(callback);
4976 throw convertServiceException(e);
4977 }
4978 }
4979
4980 /**
4981 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4982 * events once unregistered and can be registered a second time.
4983 * <p/>
4984 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4985 *
4986 * @param callback the callback being unregistered
4987 *
4988 * @hide
4989 */
4990 @SystemApi
4991 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4992 Objects.requireNonNull(callback, "The callback must be non-null");
4993 try {
4994 synchronized (mQosCallbackConnections) {
4995 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4996 if (connection != null) {
4997 connection.stopReceivingMessages();
4998 mService.unregisterQosCallback(connection);
4999 mQosCallbackConnections.remove(connection);
5000 } else {
5001 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5002 }
5003 }
5004 } catch (final RemoteException e) {
5005 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5006 e.rethrowFromSystemServer();
5007 }
5008 }
5009
5010 /**
5011 * Gets the connection related to the callback.
5012 *
5013 * @param callback the callback to look up
5014 * @return the related connection
5015 */
5016 @Nullable
5017 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5018 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5019 // Checking by reference here is intentional
5020 if (connection.getCallback() == callback) {
5021 return connection;
5022 }
5023 }
5024 return null;
5025 }
Junyu Lai23568a42021-01-19 11:10:56 +00005026
5027 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08005028 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Lai23568a42021-01-19 11:10:56 +00005029 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5030 * be used to request that the system provide a network without causing the network to be
5031 * in the foreground.
5032 *
5033 * <p>This method will attempt to find the best network that matches the passed
5034 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5035 * criteria. The platform will evaluate which network is the best at its own discretion.
5036 * Throughput, latency, cost per byte, policy, user preference and other considerations
5037 * may be factored in the decision of what is considered the best network.
5038 *
5039 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5040 * matching this request, while always attempting to match the request to a better network if
5041 * possible. If a better match is found, the platform will switch this request to the now-best
5042 * network and inform the app of the newly best network by invoking
5043 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5044 * will not try to maintain any other network than the best one currently matching the request:
5045 * a network not matching any network request may be disconnected at any time.
5046 *
5047 * <p>For example, an application could use this method to obtain a connected cellular network
5048 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5049 * radio to consume additional power. Or, an application could inform the system that it wants
5050 * a network supporting sending MMSes and have the system let it know about the currently best
5051 * MMS-supporting network through the provided {@link NetworkCallback}.
5052 *
5053 * <p>The status of the request can be followed by listening to the various callbacks described
5054 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5055 * used to direct traffic to the network (although accessing some networks may be subject to
5056 * holding specific permissions). Callers will learn about the specific characteristics of the
5057 * network through
5058 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5059 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5060 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5061 * matching the request at any given time; therefore when a better network matching the request
5062 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5063 * with the new network after which no further updates are given about the previously-best
5064 * network, unless it becomes the best again at some later time. All callbacks are invoked
5065 * in order on the same thread, which by default is a thread created by the framework running
5066 * in the app.
5067 *
5068 * <p>This{@link NetworkRequest} will live until released via
5069 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5070 * which point the system may let go of the network at any time.
5071 *
5072 * <p>It is presently unsupported to request a network with mutable
5073 * {@link NetworkCapabilities} such as
5074 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5075 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5076 * as these {@code NetworkCapabilities} represent states that a particular
5077 * network may never attain, and whether a network will attain these states
5078 * is unknown prior to bringing up the network so the framework does not
5079 * know how to go about satisfying a request with these capabilities.
5080 *
5081 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5082 * number of outstanding requests to 100 per app (identified by their UID), shared with
5083 * all variants of this method, of {@link #registerNetworkCallback} as well as
5084 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5085 * Requesting a network with this method will count toward this limit. If this limit is
5086 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5087 * make sure to unregister the callbacks with
5088 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5089 *
5090 * @param request {@link NetworkRequest} describing this request.
5091 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5092 * If null, the callback is invoked on the default internal Handler.
5093 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5094 * the callback must not be shared - it uniquely specifies this request.
5095 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5096 * @throws SecurityException if missing the appropriate permissions.
5097 * @throws RuntimeException if the app already has too many callbacks registered.
5098 *
5099 * @hide
5100 */
5101 @SystemApi(client = MODULE_LIBRARIES)
5102 @SuppressLint("ExecutorRegistration")
5103 @RequiresPermission(anyOf = {
5104 android.Manifest.permission.NETWORK_SETTINGS,
5105 android.Manifest.permission.NETWORK_STACK,
5106 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5107 })
5108 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaif4bc12f2021-03-09 20:49:48 +08005109 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Lai23568a42021-01-19 11:10:56 +00005110 final NetworkCapabilities nc = request.networkCapabilities;
5111 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaif4bc12f2021-03-09 20:49:48 +08005112 TYPE_NONE, new CallbackHandler(handler));
Junyu Lai23568a42021-01-19 11:10:56 +00005113 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005114
5115 /**
James Mattis6e6fabf2021-01-10 14:24:24 -08005116 * Used by automotive devices to set the network preferences used to direct traffic at an
5117 * application level as per the given OemNetworkPreferences. An example use-case would be an
5118 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5119 * vehicle via a particular network.
5120 *
5121 * Calling this will overwrite the existing preference.
5122 *
5123 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5124 * @param executor the executor on which listener will be invoked.
5125 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5126 * communicate completion of setOemNetworkPreference(). This will only be
5127 * called once upon successful completion of setOemNetworkPreference().
5128 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5129 * @throws SecurityException if missing the appropriate permissions.
5130 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005131 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005132 */
James Mattis7a253542021-01-26 16:23:52 -08005133 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005134 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005135 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005136 @Nullable @CallbackExecutor final Executor executor,
Chalard Jeancc9ad152021-03-03 16:37:13 +09005137 @Nullable final Runnable listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08005138 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5139 if (null != listener) {
5140 Objects.requireNonNull(executor, "Executor must be non-null");
5141 }
Chalard Jeancc9ad152021-03-03 16:37:13 +09005142 final IOnCompleteListener listenerInternal = listener == null ? null :
5143 new IOnCompleteListener.Stub() {
James Mattis6e6fabf2021-01-10 14:24:24 -08005144 @Override
5145 public void onComplete() {
Chalard Jeancc9ad152021-03-03 16:37:13 +09005146 executor.execute(listener::run);
James Mattis6e6fabf2021-01-10 14:24:24 -08005147 }
5148 };
5149
5150 try {
5151 mService.setOemNetworkPreference(preference, listenerInternal);
5152 } catch (RemoteException e) {
5153 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5154 throw e.rethrowFromSystemServer();
5155 }
5156 }
lucaslin1a6095c2021-03-12 00:46:33 +08005157
Chalard Jean03433052021-02-25 17:23:40 +09005158 /**
5159 * Request that a user profile is put by default on a network matching a given preference.
5160 *
5161 * See the documentation for the individual preferences for a description of the supported
5162 * behaviors.
5163 *
5164 * @param profile the profile concerned.
5165 * @param preference the preference for this profile.
5166 * @param executor an executor to execute the listener on. Optional if listener is null.
5167 * @param listener an optional listener to listen for completion of the operation.
5168 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5169 * @throws SecurityException if missing the appropriate permissions.
5170 * @hide
5171 */
Chalard Jeancc9ad152021-03-03 16:37:13 +09005172 // This function is for establishing per-profile default networking and can only be called by
5173 // the device policy manager, running as the system server. It would make no sense to call it
5174 // on a context for a user because it does not establish a setting on behalf of a user, rather
5175 // it establishes a setting for a user on behalf of the DPM.
5176 @SuppressLint({"UserHandle"})
5177 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09005178 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5179 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5180 @ProfileNetworkPreference final int preference,
5181 @Nullable @CallbackExecutor final Executor executor,
5182 @Nullable final Runnable listener) {
5183 if (null != listener) {
5184 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5185 }
5186 final IOnCompleteListener proxy;
5187 if (null == listener) {
5188 proxy = null;
5189 } else {
5190 proxy = new IOnCompleteListener.Stub() {
5191 @Override
5192 public void onComplete() {
5193 executor.execute(listener::run);
5194 }
5195 };
5196 }
5197 try {
5198 mService.setProfileNetworkPreference(profile, preference, proxy);
5199 } catch (RemoteException e) {
5200 throw e.rethrowFromSystemServer();
5201 }
5202 }
5203
lucaslin1a6095c2021-03-12 00:46:33 +08005204 // The first network ID of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005205 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin1a6095c2021-03-12 00:46:33 +08005206 // The network ID range of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005207 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin1a6095c2021-03-12 00:46:33 +08005208
5209 /**
5210 * Get the network ID range reserved for IPSec tunnel interfaces.
5211 *
5212 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5213 * @hide
5214 */
5215 @SystemApi(client = MODULE_LIBRARIES)
5216 @NonNull
5217 public static Range<Integer> getIpSecNetIdRange() {
5218 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5219 }
lucaslin50205af2021-03-12 16:11:27 +08005220
5221 /**
5222 * Get private DNS mode from settings.
5223 *
lucaslin73c98602021-03-17 14:53:35 +08005224 * @param context The Context to query the private DNS mode from settings.
lucaslin50205af2021-03-12 16:11:27 +08005225 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5226 *
5227 * @hide
5228 */
5229 @SystemApi(client = MODULE_LIBRARIES)
5230 @NonNull
5231 @PrivateDnsMode
lucaslinacd3ded2021-03-16 17:11:14 +08005232 public static String getPrivateDnsMode(@NonNull Context context) {
5233 final ContentResolver cr = context.getContentResolver();
lucaslin50205af2021-03-12 16:11:27 +08005234 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5235 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5236 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5237 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5238 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5239 return mode;
5240 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005241}