blob: f2078307a59af56ac10e12597b369744c09c2bdd [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
markchien75721e42020-01-21 13:11:06 +080076import com.android.internal.annotations.GuardedBy;
Robert Greenwalt3d6c9582014-05-21 20:04:36 -070077
Paul Jensen99c36662014-08-27 12:38:45 -040078import libcore.net.event.NetworkEventDispatcher;
79
junyulai61143782019-03-04 22:45:36 +080080import java.io.IOException;
81import java.io.UncheckedIOException;
Felipe Lemed16384b2016-01-22 09:44:57 -080082import java.lang.annotation.Retention;
83import java.lang.annotation.RetentionPolicy;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090084import java.net.DatagramSocket;
Jeremy Klein04863332015-12-28 15:11:58 -080085import java.net.InetAddress;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -070086import java.net.InetSocketAddress;
junyulaic7ea1242019-01-08 20:04:33 +080087import java.net.Socket;
Hugo Benichi45a49542017-03-06 09:17:06 +090088import java.util.ArrayList;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090089import java.util.Collection;
Jeremy Klein04863332015-12-28 15:11:58 -080090import java.util.HashMap;
Hugo Benichi45a49542017-03-06 09:17:06 +090091import java.util.List;
92import java.util.Map;
markchien75721e42020-01-21 13:11:06 +080093import java.util.Objects;
junyulaia86defc2018-12-27 17:25:29 +080094import java.util.concurrent.Executor;
junyulai9f872232019-01-16 20:23:34 +080095import java.util.concurrent.ExecutorService;
96import java.util.concurrent.Executors;
97import java.util.concurrent.RejectedExecutionException;
Jeremy Klein04863332015-12-28 15:11:58 -080098
The Android Open Source Project28527d22009-03-03 19:31:44 -080099/**
100 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600101 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800102 * <p>
103 * The primary responsibilities of this class are to:
104 * <ol>
105 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
106 * <li>Send broadcast intents when network connectivity changes</li>
107 * <li>Attempt to "fail over" to another network when connectivity to a network
108 * is lost</li>
109 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
110 * state of the available networks</li>
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700111 * <li>Provide an API that allows applications to request and select networks for their data
112 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800113 * </ol>
114 */
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600115@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700116public class ConnectivityManager {
117 private static final String TAG = "ConnectivityManager";
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +0900118 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700119
The Android Open Source Project28527d22009-03-03 19:31:44 -0800120 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700121 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122 * been established or lost. The NetworkInfo for the affected network is
123 * sent as an extra; it should be consulted to see what kind of
124 * connectivity event occurred.
125 * <p/>
Mark Lue1682a02016-12-05 10:57:55 -0800126 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
127 * broadcast if they declare the broadcast receiver in their manifest. Apps
128 * will still receive broadcasts if they register their
129 * {@link android.content.BroadcastReceiver} with
130 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
131 * and that context is still valid.
132 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133 * If this is a connection that was the result of failing over from a
134 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
135 * set to true.
136 * <p/>
137 * For a loss of connectivity, if the connectivity manager is attempting
138 * to connect (or has already connected) to another network, the
139 * NetworkInfo for the new network is also passed as an extra. This lets
140 * any receivers of the broadcast know that they should not necessarily
141 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt26744a52013-02-15 10:56:35 -0800142 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800143 * the failover attempt succeeded (and so there is still overall data
144 * connectivity), or that the failover attempt failed, meaning that all
145 * connectivity has been lost.
146 * <p/>
147 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
148 * is set to {@code true} if there are no connected networks at all.
Chalard Jeanae2424a2018-02-10 05:33:50 +0900149 *
150 * @deprecated apps should use the more versatile {@link #requestNetwork},
151 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
152 * functions instead for faster and more detailed updates about the network
153 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800154 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800155 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jeanae2424a2018-02-10 05:33:50 +0900156 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700158
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159 /**
Paul Jensened4d55c2015-02-27 22:55:47 -0500160 * The device has connected to a network that has presented a captive
161 * portal, which is blocking Internet connectivity. The user was presented
162 * with a notification that network sign in is required,
163 * and the user invoked the notification's action indicating they
Paul Jensen4173cce2015-05-22 10:50:39 -0400164 * desire to sign in to the network. Apps handling this activity should
Paul Jensened4d55c2015-02-27 22:55:47 -0500165 * facilitate signing in to the network. This action includes a
166 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
167 * the network presenting the captive portal; all communication with the
168 * captive portal must be done using this {@code Network} object.
169 * <p/>
Paul Jensen4173cce2015-05-22 10:50:39 -0400170 * This activity includes a {@link CaptivePortal} extra named
171 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
172 * outcomes of the captive portal sign in to the system:
173 * <ul>
174 * <li> When the app handling this action believes the user has signed in to
175 * the network and the captive portal has been dismissed, the app should
176 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
177 * reevaluate the network. If reevaluation finds the network no longer
178 * subject to a captive portal, the network may become the default active
Chalard Jean73d9db72018-06-04 16:52:49 +0900179 * data network.</li>
Paul Jensen4173cce2015-05-22 10:50:39 -0400180 * <li> When the app handling this action believes the user explicitly wants
Paul Jensened4d55c2015-02-27 22:55:47 -0500181 * to ignore the captive portal and the network, the app should call
Paul Jensen4173cce2015-05-22 10:50:39 -0400182 * {@link CaptivePortal#ignoreNetwork}. </li>
183 * </ul>
Paul Jensened4d55c2015-02-27 22:55:47 -0500184 */
185 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
186 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
187
188 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800189 * The lookup key for a {@link NetworkInfo} object. Retrieve with
190 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700191 *
Chalard Jeancc47b522019-01-11 16:47:53 +0900192 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
193 * can't accurately represent modern network characteristics.
194 * Please obtain information about networks from the {@link NetworkCapabilities}
195 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800196 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700197 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700199
The Android Open Source Project28527d22009-03-03 19:31:44 -0800200 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700201 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700202 *
203 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeancc47b522019-01-11 16:47:53 +0900204 * @deprecated The network type is not rich enough to represent the characteristics
205 * of modern networks. Please use {@link NetworkCapabilities} instead,
206 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700207 */
Chalard Jeancc47b522019-01-11 16:47:53 +0900208 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700209 public static final String EXTRA_NETWORK_TYPE = "networkType";
210
211 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800212 * The lookup key for a boolean that indicates whether a connect event
213 * is for a network to which the connectivity manager was failing over
214 * following a disconnect on another network.
215 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai5c2f6262018-12-13 12:47:51 +0800216 *
217 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800218 */
junyulai5c2f6262018-12-13 12:47:51 +0800219 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220 public static final String EXTRA_IS_FAILOVER = "isFailover";
221 /**
222 * The lookup key for a {@link NetworkInfo} object. This is supplied when
223 * there is another network that it may be possible to connect to. Retrieve with
224 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800225 *
226 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800227 */
junyulai5c2f6262018-12-13 12:47:51 +0800228 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
230 /**
231 * The lookup key for a boolean that indicates whether there is a
232 * complete lack of connectivity, i.e., no network is available.
233 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
234 */
235 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
236 /**
237 * The lookup key for a string that indicates why an attempt to connect
238 * to a network failed. The string has no particular structure. It is
239 * intended to be used in notifications presented to users. Retrieve
240 * it with {@link android.content.Intent#getStringExtra(String)}.
241 */
242 public static final String EXTRA_REASON = "reason";
243 /**
244 * The lookup key for a string that provides optionally supplied
245 * extra information about the network state. The information
246 * may be passed up from the lower networking layers, and its
247 * meaning may be specific to a particular network type. Retrieve
248 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800249 *
250 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800251 */
junyulai5c2f6262018-12-13 12:47:51 +0800252 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800253 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700254 /**
255 * The lookup key for an int that provides information about
256 * our connection to the internet at large. 0 indicates no connection,
257 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700258 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700259 * {@hide}
260 */
261 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800262 /**
Paul Jensen4173cce2015-05-22 10:50:39 -0400263 * The lookup key for a {@link CaptivePortal} object included with the
264 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
265 * object can be used to either indicate to the system that the captive
266 * portal has been dismissed or that the user does not want to pursue
267 * signing in to captive portal. Retrieve it with
268 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensened4d55c2015-02-27 22:55:47 -0500269 */
Paul Jensen4173cce2015-05-22 10:50:39 -0400270 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist0f3b4442015-09-22 15:54:32 -0700271
272 /**
273 * Key for passing a URL to the captive portal login activity.
274 */
275 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
276
Paul Jensened4d55c2015-02-27 22:55:47 -0500277 /**
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900278 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
279 * portal login activity.
280 * {@hide}
281 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900282 @SystemApi
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900283 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
284 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
285
286 /**
Hugo Benichidce21c52016-12-14 08:23:40 +0900287 * Key for passing a user agent string to the captive portal login activity.
288 * {@hide}
289 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900290 @SystemApi
Hugo Benichidce21c52016-12-14 08:23:40 +0900291 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
292 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
293
294 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700295 * Broadcast action to indicate the change of data activity status
296 * (idle or active) on a network in a recent period.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800297 * The network becomes active when data transmission is started, or
298 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700299 * {@hide}
300 */
301 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean73d9db72018-06-04 16:52:49 +0900302 public static final String ACTION_DATA_ACTIVITY_CHANGE =
303 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700304 /**
305 * The lookup key for an enum that indicates the network device type on which this data activity
306 * change happens.
307 * {@hide}
308 */
309 public static final String EXTRA_DEVICE_TYPE = "deviceType";
310 /**
311 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
312 * it is actively sending or receiving data and {@code false} means it is idle.
313 * {@hide}
314 */
315 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma601fba92014-03-12 18:42:23 -0700316 /**
317 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
318 * {@hide}
319 */
320 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700321
322 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800323 * Broadcast Action: The setting for background data usage has changed
324 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
325 * <p>
326 * If an application uses the network in the background, it should listen
327 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700328 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800329 * <p>
330 *
331 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
332 * of background data depends on several combined factors, and
333 * this broadcast is no longer sent. Instead, when background
334 * data is unavailable, {@link #getActiveNetworkInfo()} will now
335 * appear disconnected. During first boot after a platform
336 * upgrade, this broadcast will be sent once if
337 * {@link #getBackgroundDataSetting()} was {@code false} before
338 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800339 */
340 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800341 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800342 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
343 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
344
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700345 /**
346 * Broadcast Action: The network connection may not be good
347 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
348 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
349 * the network and it's condition.
350 * @hide
351 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800352 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100353 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700354 public static final String INET_CONDITION_ACTION =
355 "android.net.conn.INET_CONDITION_ACTION";
356
Robert Greenwalt2034b912009-08-12 16:08:25 -0700357 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800358 * Broadcast Action: A tetherable connection has come or gone.
359 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline449ccfe2017-04-17 16:47:23 +0900360 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
361 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt26744a52013-02-15 10:56:35 -0800362 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
363 * the current state of tethering. Each include a list of
364 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800365 * @hide
366 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800367 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000368 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800369 public static final String ACTION_TETHER_STATE_CHANGED =
markchien1f523702019-12-25 19:40:32 +0800370 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800371
372 /**
373 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800374 * gives a String[] listing all the interfaces configured for
375 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800376 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000377 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800378 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800379
380 /**
381 * @hide
Erik Kline449ccfe2017-04-17 16:47:23 +0900382 * gives a String[] listing all the interfaces currently in local-only
383 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800384 */
markchien1f523702019-12-25 19:40:32 +0800385 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline449ccfe2017-04-17 16:47:23 +0900386
387 /**
388 * @hide
389 * gives a String[] listing all the interfaces currently tethered
390 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
391 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000392 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800393 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800394
395 /**
396 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800397 * gives a String[] listing all the interfaces we tried to tether and
398 * failed. Use {@link #getLastTetherError} to find the error code
399 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800400 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000401 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800402 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800403
404 /**
Russell Brenner4774b022013-02-12 10:03:14 -0800405 * Broadcast Action: The captive portal tracker has finished its test.
406 * Sent only while running Setup Wizard, in lieu of showing a user
407 * notification.
408 * @hide
409 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800410 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner4774b022013-02-12 10:03:14 -0800411 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
412 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
413 /**
414 * The lookup key for a boolean that indicates whether a captive portal was detected.
415 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
416 * @hide
417 */
418 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
419
420 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900421 * Action used to display a dialog that asks the user whether to connect to a network that is
422 * not validated. This intent is used to start the dialog in settings via startActivity.
423 *
424 * @hide
425 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800426 @SystemApi(client = MODULE_LIBRARIES)
427 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900428
429 /**
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900430 * Action used to display a dialog that asks the user whether to avoid a network that is no
431 * longer validated. This intent is used to start the dialog in settings via startActivity.
432 *
433 * @hide
434 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800435 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900436 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslin1a0ca5f2021-03-04 17:09:51 +0800437 "android.net.action.PROMPT_LOST_VALIDATION";
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900438
439 /**
lucaslin25a50472019-03-12 13:08:03 +0800440 * Action used to display a dialog that asks the user whether to stay connected to a network
441 * that has not validated. This intent is used to start the dialog in settings via
442 * startActivity.
443 *
444 * @hide
445 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800446 @SystemApi(client = MODULE_LIBRARIES)
lucaslin25a50472019-03-12 13:08:03 +0800447 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslin1a0ca5f2021-03-04 17:09:51 +0800448 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
lucaslin25a50472019-03-12 13:08:03 +0800449
450 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800451 * Invalid tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900452 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800453 * @hide
454 */
markchien1f523702019-12-25 19:40:32 +0800455 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800456
457 /**
458 * Wifi tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900459 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800460 * @hide
461 */
462 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900463 public static final int TETHERING_WIFI = 0;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800464
465 /**
466 * USB tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900467 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800468 * @hide
469 */
470 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900471 public static final int TETHERING_USB = 1;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800472
473 /**
474 * Bluetooth tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900475 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800476 * @hide
477 */
478 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900479 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800480
481 /**
Jimmy Chen87db1542019-07-15 18:03:23 +0800482 * Wifi P2p tethering type.
483 * Wifi P2p tethering is set through events automatically, and don't
484 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
485 * @hide
486 */
markchien1f523702019-12-25 19:40:32 +0800487 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chen87db1542019-07-15 18:03:23 +0800488
489 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800490 * Extra used for communicating with the TetherService. Includes the type of tethering to
491 * enable if any.
492 * @hide
493 */
markchien75721e42020-01-21 13:11:06 +0800494 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800495
496 /**
497 * Extra used for communicating with the TetherService. Includes the type of tethering for
498 * which to cancel provisioning.
499 * @hide
500 */
markchien75721e42020-01-21 13:11:06 +0800501 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800502
503 /**
504 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
505 * provisioning.
506 * @hide
507 */
markchien75721e42020-01-21 13:11:06 +0800508 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800509
510 /**
511 * Tells the TetherService to run a provision check now.
512 * @hide
513 */
markchien75721e42020-01-21 13:11:06 +0800514 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800515
516 /**
517 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
518 * which will receive provisioning results. Can be left empty.
519 * @hide
520 */
markchien75721e42020-01-21 13:11:06 +0800521 public static final String EXTRA_PROVISION_CALLBACK =
522 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800523
524 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800525 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700526 * @hide
527 */
paulhu62af6122020-01-13 16:46:45 +0800528 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700529 public static final int TYPE_NONE = -1;
530
531 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900532 * A Mobile data connection. Devices may support more than one.
533 *
534 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
535 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
536 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700537 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900538 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700539 public static final int TYPE_MOBILE = 0;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900540
Robert Greenwalt2034b912009-08-12 16:08:25 -0700541 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900542 * A WIFI data connection. Devices may support more than one.
543 *
544 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
545 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
546 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700547 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900548 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700549 public static final int TYPE_WIFI = 1;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900550
Robert Greenwalt2034b912009-08-12 16:08:25 -0700551 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800552 * An MMS-specific Mobile data connection. This network type may use the
553 * same network interface as {@link #TYPE_MOBILE} or it may use a different
554 * one. This is used by applications needing to talk to the carrier's
555 * Multimedia Messaging Service servers.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900556 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900557 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900558 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900559 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700560 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700561 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900563
Robert Greenwalt2034b912009-08-12 16:08:25 -0700564 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800565 * A SUPL-specific Mobile data connection. This network type may use the
566 * same network interface as {@link #TYPE_MOBILE} or it may use a different
567 * one. This is used by applications needing to talk to the carrier's
568 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900569 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900570 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900571 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900572 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700573 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700574 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700575 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900576
Robert Greenwalt2034b912009-08-12 16:08:25 -0700577 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800578 * A DUN-specific Mobile data connection. This network type may use the
579 * same network interface as {@link #TYPE_MOBILE} or it may use a different
580 * one. This is sometimes by the system when setting up an upstream connection
581 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900582 *
583 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
584 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
585 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700586 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900587 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700588 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900589
Robert Greenwalt2034b912009-08-12 16:08:25 -0700590 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800591 * A High Priority Mobile data connection. This network type uses the
592 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900593 * is different.
594 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900595 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
596 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
597 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700598 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700599 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700600 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900601
jshbfa81722010-03-11 15:04:43 -0800602 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900603 * A WiMAX data connection.
604 *
605 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
606 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
607 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800608 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900609 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800610 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800611
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800612 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900613 * A Bluetooth data connection.
614 *
615 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
616 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
617 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800618 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900619 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800620 public static final int TYPE_BLUETOOTH = 7;
621
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700622 /**
Chiachang Wang7d5f3782020-07-28 13:53:09 +0800623 * Fake data connection. This should not be used on shipping devices.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900624 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700625 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900626 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800627 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800628
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700629 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900630 * An Ethernet data connection.
631 *
632 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
633 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
634 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700635 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900636 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800637 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700638
Wink Savilleb7c92c72011-03-12 14:52:01 -0800639 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800640 * Over the air Administration.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900641 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800642 * {@hide}
643 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900644 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900645 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800646 public static final int TYPE_MOBILE_FOTA = 10;
647
648 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800649 * IP Multimedia Subsystem.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900650 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800651 * {@hide}
652 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900653 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100654 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800655 public static final int TYPE_MOBILE_IMS = 11;
656
657 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800658 * Carrier Branded Services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900659 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800660 * {@hide}
661 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900662 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900663 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800664 public static final int TYPE_MOBILE_CBS = 12;
665
repo syncf5de5572011-07-29 23:55:49 -0700666 /**
667 * A Wi-Fi p2p connection. Only requesting processes will have access to
668 * the peers connected.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900669 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700670 * {@hide}
671 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900672 @Deprecated
paulhu028732e2020-01-15 15:38:23 +0800673 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700674 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800675
Wink Saville70dbdcc2013-07-29 15:00:57 -0700676 /**
677 * The network to use for initially attaching to the network
Chalard Jean5acb7b72018-03-08 13:54:53 +0900678 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville70dbdcc2013-07-29 15:00:57 -0700679 * {@hide}
680 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900681 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100682 @UnsupportedAppUsage
Wink Saville70dbdcc2013-07-29 15:00:57 -0700683 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700684
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900685 /**
Robert Greenwalt9db5f3c2015-07-09 14:49:35 -0700686 * Emergency PDN connection for emergency services. This
687 * may include IMS and MMS in emergency situations.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900688 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram201d45f2014-06-26 11:03:44 -0700689 * {@hide}
690 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900691 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900692 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram201d45f2014-06-26 11:03:44 -0700693 public static final int TYPE_MOBILE_EMERGENCY = 15;
694
Hui Lu07f29332014-01-15 11:05:36 -0500695 /**
696 * The network that uses proxy to achieve connectivity.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900697 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu07f29332014-01-15 11:05:36 -0500698 * {@hide}
699 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900700 @Deprecated
Remi NGUYEN VANdaeafee2020-11-30 19:23:45 +0900701 @SystemApi
Hui Lu07f29332014-01-15 11:05:36 -0500702 public static final int TYPE_PROXY = 16;
Wink Saville70dbdcc2013-07-29 15:00:57 -0700703
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700704 /**
705 * A virtual network using one or more native bearers.
706 * It may or may not be providing security services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900707 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700708 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900709 @Deprecated
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700710 public static final int TYPE_VPN = 17;
Hui Lu07f29332014-01-15 11:05:36 -0500711
Benedict Wong80156022018-11-14 17:40:55 -0800712 /**
713 * A network that is exclusively meant to be used for testing
714 *
715 * @deprecated Use {@link NetworkCapabilities} instead.
716 * @hide
717 */
718 @Deprecated
719 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700720
Chalard Jean74fe1c72020-03-25 01:24:04 +0900721 /**
722 * @deprecated Use {@link NetworkCapabilities} instead.
723 * @hide
724 */
725 @Deprecated
726 @Retention(RetentionPolicy.SOURCE)
727 @IntDef(prefix = { "TYPE_" }, value = {
728 TYPE_NONE,
729 TYPE_MOBILE,
730 TYPE_WIFI,
731 TYPE_MOBILE_MMS,
732 TYPE_MOBILE_SUPL,
733 TYPE_MOBILE_DUN,
734 TYPE_MOBILE_HIPRI,
735 TYPE_WIMAX,
736 TYPE_BLUETOOTH,
737 TYPE_DUMMY,
738 TYPE_ETHERNET,
739 TYPE_MOBILE_FOTA,
740 TYPE_MOBILE_IMS,
741 TYPE_MOBILE_CBS,
742 TYPE_WIFI_P2P,
743 TYPE_MOBILE_IA,
744 TYPE_MOBILE_EMERGENCY,
745 TYPE_PROXY,
746 TYPE_VPN,
747 TYPE_TEST
748 })
749 public @interface LegacyNetworkType {}
750
Chalard Jean1f42df12019-11-21 14:48:00 +0900751 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
752 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
753 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
754 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
755 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
756
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700757 /** {@hide} */
Benedict Wong80156022018-11-14 17:40:55 -0800758 public static final int MAX_RADIO_TYPE = TYPE_TEST;
759
760 /** {@hide} */
761 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800762
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900763 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
764
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800765 /**
766 * If you want to set the default network preference,you can directly
767 * change the networkAttributes array in framework's config.xml.
768 *
769 * @deprecated Since we support so many more networks now, the single
770 * network default network preference can't really express
Robert Greenwalt26744a52013-02-15 10:56:35 -0800771 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800772 * networkAttributes in config.xml. You can determine
Robert Greenwalt1ee3d2c2012-12-07 09:56:50 -0800773 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800774 * from an App.
775 */
776 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800777 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
778
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700779 /**
Robert Greenwalta1402df2014-03-19 17:56:12 -0700780 * @hide
781 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900782 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltc34f83b2014-06-08 16:42:59 -0700783
Paul Jensen0478ace2014-07-11 12:28:19 -0400784 /**
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900785 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
786 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean73d9db72018-06-04 16:52:49 +0900787 * registered from those that were already unregistered.
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900788 * @hide
789 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900790 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900791 new NetworkRequest.Builder().clearCapabilities().build();
792
793 /**
Paul Jensen0478ace2014-07-11 12:28:19 -0400794 * A NetID indicating no Network is selected.
795 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
796 * @hide
797 */
798 public static final int NETID_UNSET = 0;
799
Erik Kline1ecdd962017-10-30 15:29:44 +0900800 /**
801 * Private DNS Mode values.
802 *
803 * The "private_dns_mode" global setting stores a String value which is
804 * expected to be one of the following.
805 */
806
807 /**
808 * @hide
809 */
lucaslin50205af2021-03-12 16:11:27 +0800810 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900811 public static final String PRIVATE_DNS_MODE_OFF = "off";
812 /**
813 * @hide
814 */
lucaslin50205af2021-03-12 16:11:27 +0800815 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900816 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
817 /**
818 * @hide
819 */
lucaslin50205af2021-03-12 16:11:27 +0800820 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900821 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin50205af2021-03-12 16:11:27 +0800822
823 /** @hide */
824 @Retention(RetentionPolicy.SOURCE)
825 @StringDef(value = {
826 PRIVATE_DNS_MODE_OFF,
827 PRIVATE_DNS_MODE_OPPORTUNISTIC,
828 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
829 })
830 public @interface PrivateDnsMode {}
Erik Kline1ecdd962017-10-30 15:29:44 +0900831
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900832 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700833 private final IConnectivityManager mService;
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +0900834
Paul Jensen12131352014-12-10 15:12:18 -0500835 /**
836 * A kludge to facilitate static access where a Context pointer isn't available, like in the
837 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
838 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
839 * methods that take a Context argument.
840 */
841 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800842
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +0900843 private final Context mContext;
844
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +0000845 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800846
Robert Greenwalt26744a52013-02-15 10:56:35 -0800847 /**
848 * Tests if a given integer represents a valid network type.
849 * @param networkType the type to be tested
850 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen1c9f2e42015-05-06 10:42:25 -0400851 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
852 * validate a network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800853 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700854 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700855 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900856 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800857 }
858
Robert Greenwalt26744a52013-02-15 10:56:35 -0800859 /**
860 * Returns a non-localized string representing a given network type.
861 * ONLY used for debugging output.
862 * @param type the type needing naming
863 * @return a String for the given type, or a string version of the type ("87")
864 * if no name is known.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900865 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800866 * {@hide}
867 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900868 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000869 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700870 public static String getNetworkTypeName(int type) {
871 switch (type) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900872 case TYPE_NONE:
873 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700874 case TYPE_MOBILE:
875 return "MOBILE";
876 case TYPE_WIFI:
877 return "WIFI";
878 case TYPE_MOBILE_MMS:
879 return "MOBILE_MMS";
880 case TYPE_MOBILE_SUPL:
881 return "MOBILE_SUPL";
882 case TYPE_MOBILE_DUN:
883 return "MOBILE_DUN";
884 case TYPE_MOBILE_HIPRI:
885 return "MOBILE_HIPRI";
886 case TYPE_WIMAX:
887 return "WIMAX";
888 case TYPE_BLUETOOTH:
889 return "BLUETOOTH";
890 case TYPE_DUMMY:
891 return "DUMMY";
892 case TYPE_ETHERNET:
893 return "ETHERNET";
894 case TYPE_MOBILE_FOTA:
895 return "MOBILE_FOTA";
896 case TYPE_MOBILE_IMS:
897 return "MOBILE_IMS";
898 case TYPE_MOBILE_CBS:
899 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700900 case TYPE_WIFI_P2P:
901 return "WIFI_P2P";
Wink Saville70dbdcc2013-07-29 15:00:57 -0700902 case TYPE_MOBILE_IA:
903 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -0700904 case TYPE_MOBILE_EMERGENCY:
905 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -0500906 case TYPE_PROXY:
907 return "PROXY";
Erik Klineb1ff7002014-11-19 17:23:41 +0900908 case TYPE_VPN:
909 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700910 default:
911 return Integer.toString(type);
912 }
913 }
914
Robert Greenwalt26744a52013-02-15 10:56:35 -0800915 /**
Aaron Huangdfba5d12020-06-27 07:18:23 +0800916 * @hide
Aaron Huangdfba5d12020-06-27 07:18:23 +0800917 */
lucaslin8c121bf2021-03-17 14:16:01 +0800918 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huangdfba5d12020-06-27 07:18:23 +0800919 public void systemReady() {
920 try {
921 mService.systemReady();
922 } catch (RemoteException e) {
923 throw e.rethrowFromSystemServer();
924 }
925 }
926
927 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800928 * Checks if a given type uses the cellular data connection.
929 * This should be replaced in the future by a network property.
930 * @param networkType the type to check
931 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +0900932 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800933 * {@hide}
934 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900935 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900936 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700937 public static boolean isNetworkTypeMobile(int networkType) {
938 switch (networkType) {
939 case TYPE_MOBILE:
940 case TYPE_MOBILE_MMS:
941 case TYPE_MOBILE_SUPL:
942 case TYPE_MOBILE_DUN:
943 case TYPE_MOBILE_HIPRI:
944 case TYPE_MOBILE_FOTA:
945 case TYPE_MOBILE_IMS:
946 case TYPE_MOBILE_CBS:
Wink Saville70dbdcc2013-07-29 15:00:57 -0700947 case TYPE_MOBILE_IA:
Ram201d45f2014-06-26 11:03:44 -0700948 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700949 return true;
950 default:
951 return false;
952 }
953 }
954
Robert Greenwalt26744a52013-02-15 10:56:35 -0800955 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700956 * Checks if the given network type is backed by a Wi-Fi radio.
957 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900958 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700959 * @hide
960 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900961 @Deprecated
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700962 public static boolean isNetworkTypeWifi(int networkType) {
963 switch (networkType) {
964 case TYPE_WIFI:
965 case TYPE_WIFI_P2P:
966 return true;
967 default:
968 return false;
969 }
970 }
971
972 /**
Chalard Jean03433052021-02-25 17:23:40 +0900973 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
974 * Specify that the traffic for this user should by follow the default rules.
975 * @hide
976 */
Chalard Jean560d4032021-03-17 14:33:24 +0900977 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +0900978 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
979
980 /**
981 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
982 * Specify that the traffic for this user should by default go on a network with
983 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
984 * if no such network is available.
985 * @hide
986 */
Chalard Jean560d4032021-03-17 14:33:24 +0900987 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +0900988 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
989
990 /** @hide */
991 @Retention(RetentionPolicy.SOURCE)
992 @IntDef(value = {
993 PROFILE_NETWORK_PREFERENCE_DEFAULT,
994 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
995 })
996 public @interface ProfileNetworkPreference {
997 }
998
999 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001000 * Specifies the preferred network type. When the device has more
1001 * than one type available the preferred network type will be used.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001002 *
1003 * @param preference the network type to prefer over all others. It is
1004 * unspecified what happens to the old preferred network in the
1005 * overall ordering.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001006 * @deprecated Functionality has been removed as it no longer makes sense,
1007 * with many more than two networks - we'd need an array to express
1008 * preference. Instead we use dynamic network properties of
1009 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001010 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001011 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001012 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001013 }
1014
Robert Greenwalt26744a52013-02-15 10:56:35 -08001015 /**
1016 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001017 *
1018 * @return an integer representing the preferred network type
1019 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001020 * @deprecated Functionality has been removed as it no longer makes sense,
1021 * with many more than two networks - we'd need an array to express
1022 * preference. Instead we use dynamic network properties of
1023 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001024 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001025 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001026 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001027 public int getNetworkPreference() {
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001028 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001029 }
1030
Scott Mainf58b7d82011-10-06 19:02:28 -07001031 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001032 * Returns details about the currently active default data network. When
1033 * connected, this network is the default route for outgoing connections.
1034 * You should always check {@link NetworkInfo#isConnected()} before initiating
1035 * network traffic. This may return {@code null} when there is no default
1036 * network.
Chalard Jean7c85ba42018-03-29 17:45:24 +09001037 * Note that if the default network is a VPN, this method will return the
1038 * NetworkInfo for one of its underlying networks instead, or null if the
1039 * VPN agent did not specify any. Apps interested in learning about VPNs
1040 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001041 *
1042 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001043 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001044 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001045 */
junyulai5c2f6262018-12-13 12:47:51 +08001046 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001047 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001048 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001049 public NetworkInfo getActiveNetworkInfo() {
1050 try {
1051 return mService.getActiveNetworkInfo();
1052 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001053 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001054 }
1055 }
1056
Robert Greenwalt26744a52013-02-15 10:56:35 -08001057 /**
Paul Jensenc2569432015-02-13 14:18:39 -05001058 * Returns a {@link Network} object corresponding to the currently active
1059 * default data network. In the event that the current active default data
1060 * network disconnects, the returned {@code Network} object will no longer
1061 * be usable. This will return {@code null} when there is no default
1062 * network.
1063 *
1064 * @return a {@link Network} object for the current default network or
1065 * {@code null} if no default network is currently active
Paul Jensenc2569432015-02-13 14:18:39 -05001066 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001067 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001068 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001069 public Network getActiveNetwork() {
1070 try {
1071 return mService.getActiveNetwork();
1072 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001073 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001074 }
1075 }
1076
1077 /**
Robin Leeda4d2e22016-03-24 12:07:00 +00001078 * Returns a {@link Network} object corresponding to the currently active
1079 * default data network for a specific UID. In the event that the default data
1080 * network disconnects, the returned {@code Network} object will no longer
1081 * be usable. This will return {@code null} when there is no default
1082 * network for the UID.
Robin Leeda4d2e22016-03-24 12:07:00 +00001083 *
1084 * @return a {@link Network} object for the current default network for the
1085 * given UID or {@code null} if no default network is currently active
1086 *
1087 * @hide
1088 */
paulhuec0a9632019-08-12 16:25:11 +08001089 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001090 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001091 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001092 return getActiveNetworkForUid(uid, false);
1093 }
1094
1095 /** {@hide} */
1096 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001097 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001098 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001099 } catch (RemoteException e) {
1100 throw e.rethrowFromSystemServer();
1101 }
1102 }
1103
1104 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001105 * Adds or removes a requirement for given UID ranges to use the VPN.
1106 *
1107 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1108 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1109 * otherwise have permission to bypass the VPN (e.g., because they have the
1110 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1111 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1112 * set to {@code false}, a previously-added restriction is removed.
1113 * <p>
1114 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1115 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1116 * remove a previously-added range, the exact range must be removed as is.
1117 * <p>
1118 * The changes are applied asynchronously and may not have been applied by the time the method
1119 * returns. Apps will be notified about any changes that apply to them via
1120 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1121 * effect.
1122 * <p>
1123 * This method should be called only by the VPN code.
1124 *
1125 * @param ranges the UID ranges to restrict
1126 * @param requireVpn whether the specified UID ranges must use a VPN
1127 *
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001128 * @hide
1129 */
1130 @RequiresPermission(anyOf = {
1131 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001132 android.Manifest.permission.NETWORK_STACK,
1133 android.Manifest.permission.NETWORK_SETTINGS})
1134 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001135 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 *
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001178 * @hide
1179 */
1180 @RequiresPermission(anyOf = {
1181 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001182 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001183 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin5140e482021-03-22 11:51:27 +08001184 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001185 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
lucaslin5140e482021-03-22 11:51:27 +08002131 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002132 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002133 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134 try {
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002135 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2136 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002138 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002139 }
2140 }
2141
2142 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002143 * @return the context's attribution tag
2144 */
2145 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2146 private @Nullable String getAttributionTag() {
2147 return mContext.getAttributionTag();
2148 }
2149
2150 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002151 * Returns the value of the setting for background data usage. If false,
2152 * applications should not use the network if the application is not in the
2153 * foreground. Developers should respect this setting, and check the value
2154 * of this before performing any background data operations.
2155 * <p>
2156 * All applications that have background services that use the network
2157 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002158 * <p>
Scott Main50589142011-10-06 18:32:43 -07002159 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002160 * background data depends on several combined factors, and this method will
2161 * always return {@code true}. Instead, when background data is unavailable,
2162 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002163 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002164 * @return Whether background data usage is allowed.
2165 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002166 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002167 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002168 // assume that background data is allowed; final authority is
2169 // NetworkInfo which may be blocked.
2170 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002171 }
2172
2173 /**
2174 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002175 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002176 * @param allowBackgroundData Whether an application should use data while
2177 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002178 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002179 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2180 * @see #getBackgroundDataSetting()
2181 * @hide
2182 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002183 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002184 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002185 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002186 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002187 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002188
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002189 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002190 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002191 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002192 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002193 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002194 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002195 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002196 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2197 if (tm != null) {
2198 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2199 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2200 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2201 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2202 + " retVal=" + retVal);
2203 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002204 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002205 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002206 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002207 }
2208
The Android Open Source Project28527d22009-03-03 19:31:44 -08002209 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002210 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002211 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002212 */
2213 public interface OnNetworkActiveListener {
2214 /**
2215 * Called on the main thread of the process to report that the current data network
2216 * has become active, and it is now a good time to perform any pending network
2217 * operations. Note that this listener only tells you when the network becomes
2218 * active; if at any other time you want to know whether it is active (and thus okay
2219 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002220 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002221 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002222 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002223 }
2224
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002225 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002226 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002227
2228 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002229 * Start listening to reports when the system's default data network is active, meaning it is
2230 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2231 * to determine the current state of the system's default network after registering the
2232 * listener.
2233 * <p>
2234 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002235 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002236 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002237 *
2238 * @param l The listener to be told when the network is active.
2239 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002240 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002241 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2242 @Override
2243 public void onNetworkActive() throws RemoteException {
2244 l.onNetworkActive();
2245 }
2246 };
2247
2248 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002249 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002250 mNetworkActivityListeners.put(l, rl);
2251 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002252 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002253 }
2254 }
2255
2256 /**
2257 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002258 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002259 *
2260 * @param l Previously registered listener.
2261 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002262 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002263 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002264 if (rl == null) {
2265 throw new IllegalArgumentException("Listener was not registered.");
2266 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002267 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002268 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002269 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002270 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002271 }
2272 }
2273
2274 /**
2275 * Return whether the data network is currently active. An active network means that
2276 * it is currently in a high power state for performing data transmission. On some
2277 * types of networks, it may be expensive to move and stay in such a state, so it is
2278 * more power efficient to batch network traffic together when the radio is already in
2279 * this state. This method tells you whether right now is currently a good time to
2280 * initiate network traffic, as the network is already active.
2281 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002282 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002283 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002284 return mService.isDefaultNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002285 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002286 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002287 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002288 }
2289
2290 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002291 * {@hide}
2292 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002293 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002294 mContext = Objects.requireNonNull(context, "missing context");
2295 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002296 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002297 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002298 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002299
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002300 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002301 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002302 public static ConnectivityManager from(Context context) {
2303 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2304 }
2305
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002306 /** @hide */
2307 public NetworkRequest getDefaultRequest() {
2308 try {
2309 // This is not racy as the default request is final in ConnectivityService.
2310 return mService.getDefaultRequest();
2311 } catch (RemoteException e) {
2312 throw e.rethrowFromSystemServer();
2313 }
2314 }
2315
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002316 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002317 * Check if the package is a allowed to write settings. This also accounts that such an access
2318 * happened.
2319 *
2320 * @return {@code true} iff the package is allowed to write settings.
2321 */
2322 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2323 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2324 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2325 boolean throwException) {
2326 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2327 callingAttributionTag, throwException);
2328 }
2329
2330 /**
Paul Jensen12131352014-12-10 15:12:18 -05002331 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2332 * situations where a Context pointer is unavailable.
2333 * @hide
2334 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002335 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002336 static ConnectivityManager getInstanceOrNull() {
2337 return sInstance;
2338 }
2339
2340 /**
2341 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2342 * situations where a Context pointer is unavailable.
2343 * @hide
2344 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002345 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002346 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002347 private static ConnectivityManager getInstance() {
2348 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002349 throw new IllegalStateException("No ConnectivityManager yet constructed");
2350 }
Paul Jensen895c3942015-03-10 10:54:12 -04002351 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002352 }
2353
2354 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002355 * Get the set of tetherable, available interfaces. This list is limited by
2356 * device configuration and current interface existence.
2357 *
2358 * @return an array of 0 or more Strings of tetherable interface names.
2359 *
markchien75721e42020-01-21 13:11:06 +08002360 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002361 * {@hide}
2362 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002363 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002364 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002365 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002366 public String[] getTetherableIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002367 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002368 }
2369
2370 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002371 * Get the set of tethered interfaces.
2372 *
2373 * @return an array of 0 or more String of currently tethered interface names.
2374 *
markchien75721e42020-01-21 13:11:06 +08002375 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002376 * {@hide}
2377 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002378 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002379 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002380 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002381 public String[] getTetheredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002382 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002383 }
2384
2385 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002386 * Get the set of interface names which attempted to tether but
2387 * failed. Re-attempting to tether may cause them to reset to the Tethered
2388 * state. Alternatively, causing the interface to be destroyed and recreated
2389 * may cause them to reset to the available state.
2390 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2391 * information on the cause of the errors.
2392 *
2393 * @return an array of 0 or more String indicating the interface names
2394 * which failed to tether.
2395 *
markchien75721e42020-01-21 13:11:06 +08002396 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002397 * {@hide}
2398 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002399 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002400 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002401 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002402 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002403 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002404 }
2405
2406 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002407 * Get the set of tethered dhcp ranges.
2408 *
markchien9e046242020-02-06 19:23:26 +08002409 * @deprecated This method is not supported.
2410 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002411 * {@hide}
2412 */
paulhuec0a9632019-08-12 16:25:11 +08002413 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien75721e42020-01-21 13:11:06 +08002414 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002415 public String[] getTetheredDhcpRanges() {
markchien9e046242020-02-06 19:23:26 +08002416 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002417 }
2418
2419 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002420 * Attempt to tether the named interface. This will setup a dhcp server
2421 * on the interface, forward and NAT IP packets and forward DNS requests
2422 * to the best active upstream network interface. Note that if no upstream
2423 * IP network interface is available, dhcp will still run and traffic will be
2424 * allowed between the tethered devices and this device, though upstream net
2425 * access will of course fail until an upstream network interface becomes
2426 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002427 *
2428 * <p>This method requires the caller to hold either the
2429 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2430 * or the ability to modify system settings as determined by
2431 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002432 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002433 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2434 * and WifiStateMachine which need direct access. All other clients should use
2435 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2436 * logic.</p>
2437 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002438 * @param iface the interface name to tether.
2439 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002440 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002441 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002442 * {@hide}
2443 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002444 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien10ddd022020-01-20 19:31:56 +08002445 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002446 public int tether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002447 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002448 }
2449
2450 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002451 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002452 *
2453 * <p>This method requires the caller to hold either the
2454 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2455 * or the ability to modify system settings as determined by
2456 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002457 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002458 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2459 * and WifiStateMachine which need direct access. All other clients should use
2460 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2461 * logic.</p>
2462 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002463 * @param iface the interface name to untether.
2464 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2465 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002466 * {@hide}
2467 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002468 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002469 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002470 public int untether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002471 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002472 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002473
2474 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002475 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002476 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002477 * due to device configuration.
2478 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002479 * <p>If this app does not have permission to use this API, it will always
2480 * return false rather than throw an exception.</p>
2481 *
2482 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2483 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2484 *
2485 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2486 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2487 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002488 * @return a boolean - {@code true} indicating Tethering is supported.
2489 *
markchien75721e42020-01-21 13:11:06 +08002490 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002491 * {@hide}
2492 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002493 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002494 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2495 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002496 public boolean isTetheringSupported() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002497 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002498 }
2499
2500 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002501 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien10ddd022020-01-20 19:31:56 +08002502 *
2503 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002504 * @hide
2505 */
2506 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002507 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002508 public static abstract class OnStartTetheringCallback {
2509 /**
2510 * Called when tethering has been successfully started.
2511 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002512 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002513
2514 /**
2515 * Called when starting tethering failed.
2516 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002517 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002518 }
2519
2520 /**
2521 * Convenient overload for
2522 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2523 * handler to run on the current thread's {@link Looper}.
markchien10ddd022020-01-20 19:31:56 +08002524 *
2525 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002526 * @hide
2527 */
2528 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002529 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002530 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002531 public void startTethering(int type, boolean showProvisioningUi,
2532 final OnStartTetheringCallback callback) {
2533 startTethering(type, showProvisioningUi, callback, null);
2534 }
2535
2536 /**
2537 * Runs tether provisioning for the given type if needed and then starts tethering if
2538 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2539 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2540 * schedules tether provisioning re-checks if appropriate.
2541 *
2542 * @param type The type of tethering to start. Must be one of
2543 * {@link ConnectivityManager.TETHERING_WIFI},
2544 * {@link ConnectivityManager.TETHERING_USB}, or
2545 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2546 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2547 * is one. This should be true the first time this function is called and also any time
2548 * the user can see this UI. It gives users information from their carrier about the
2549 * check failing and how they can sign up for tethering if possible.
2550 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2551 * of the result of trying to tether.
2552 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien10ddd022020-01-20 19:31:56 +08002553 *
2554 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002555 * @hide
2556 */
2557 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002558 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002559 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002560 public void startTethering(int type, boolean showProvisioningUi,
2561 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002562 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002563
markchien10ddd022020-01-20 19:31:56 +08002564 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002565 @Override
markchien10ddd022020-01-20 19:31:56 +08002566 public void execute(Runnable command) {
2567 if (handler == null) {
2568 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002569 } else {
markchien10ddd022020-01-20 19:31:56 +08002570 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002571 }
2572 }
2573 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002574
markchien10ddd022020-01-20 19:31:56 +08002575 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2576 @Override
2577 public void onTetheringStarted() {
2578 callback.onTetheringStarted();
2579 }
2580
2581 @Override
markchien68b67842020-03-19 13:37:43 +08002582 public void onTetheringFailed(final int error) {
markchien10ddd022020-01-20 19:31:56 +08002583 callback.onTetheringFailed();
2584 }
2585 };
2586
2587 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien68b67842020-03-19 13:37:43 +08002588 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien10ddd022020-01-20 19:31:56 +08002589
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002590 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002591 }
2592
2593 /**
2594 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2595 * applicable.
2596 *
2597 * @param type The type of tethering to stop. Must be one of
2598 * {@link ConnectivityManager.TETHERING_WIFI},
2599 * {@link ConnectivityManager.TETHERING_USB}, or
2600 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien75721e42020-01-21 13:11:06 +08002601 *
2602 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002603 * @hide
2604 */
2605 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002606 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002607 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002608 public void stopTethering(int type) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002609 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002610 }
2611
2612 /**
markchiena005c992019-02-27 14:56:11 +08002613 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2614 * upstream status.
2615 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002616 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien75721e42020-01-21 13:11:06 +08002617 * @hide
markchiena005c992019-02-27 14:56:11 +08002618 */
2619 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002620 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002621 public abstract static class OnTetheringEventCallback {
2622
2623 /**
2624 * Called when tethering upstream changed. This can be called multiple times and can be
2625 * called any time.
2626 *
2627 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2628 * have any upstream.
2629 */
2630 public void onUpstreamChanged(@Nullable Network network) {}
2631 }
2632
markchien75721e42020-01-21 13:11:06 +08002633 @GuardedBy("mTetheringEventCallbacks")
2634 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2635 mTetheringEventCallbacks = new ArrayMap<>();
2636
markchiena005c992019-02-27 14:56:11 +08002637 /**
2638 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002639 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002640 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2641 * with a null argument. The same callback object cannot be registered twice.
2642 *
2643 * @param executor the executor on which callback will be invoked.
2644 * @param callback the callback to be called when tethering has change events.
markchien75721e42020-01-21 13:11:06 +08002645 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002646 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002647 * @hide
2648 */
2649 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002650 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002651 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2652 public void registerTetheringEventCallback(
2653 @NonNull @CallbackExecutor Executor executor,
2654 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002655 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchiena005c992019-02-27 14:56:11 +08002656
markchien75721e42020-01-21 13:11:06 +08002657 final TetheringEventCallback tetherCallback =
2658 new TetheringEventCallback() {
2659 @Override
2660 public void onUpstreamChanged(@Nullable Network network) {
2661 callback.onUpstreamChanged(network);
2662 }
2663 };
2664
2665 synchronized (mTetheringEventCallbacks) {
2666 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002667 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002668 }
markchiena005c992019-02-27 14:56:11 +08002669 }
2670
2671 /**
2672 * Remove tethering event callback previously registered with
2673 * {@link #registerTetheringEventCallback}.
2674 *
2675 * @param callback previously registered callback.
markchien75721e42020-01-21 13:11:06 +08002676 *
2677 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002678 * @hide
2679 */
2680 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002681 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002682 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2683 public void unregisterTetheringEventCallback(
2684 @NonNull final OnTetheringEventCallback callback) {
markchien75721e42020-01-21 13:11:06 +08002685 Objects.requireNonNull(callback, "The callback must be non-null");
2686 synchronized (mTetheringEventCallbacks) {
2687 final TetheringEventCallback tetherCallback =
2688 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002689 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002690 }
markchiena005c992019-02-27 14:56:11 +08002691 }
2692
2693
2694 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002695 * Get the list of regular expressions that define any tetherable
2696 * USB network interfaces. If USB tethering is not supported by the
2697 * device, this list should be empty.
2698 *
2699 * @return an array of 0 or more regular expression Strings defining
2700 * what interfaces are considered tetherable usb interfaces.
2701 *
markchien75721e42020-01-21 13:11:06 +08002702 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002703 * {@hide}
2704 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002705 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002706 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002707 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002708 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002709 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002710 }
2711
2712 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002713 * Get the list of regular expressions that define any tetherable
2714 * Wifi network interfaces. If Wifi tethering is not supported by the
2715 * device, this list should be empty.
2716 *
2717 * @return an array of 0 or more regular expression Strings defining
2718 * what interfaces are considered tetherable wifi interfaces.
2719 *
markchien75721e42020-01-21 13:11:06 +08002720 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002721 * {@hide}
2722 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002723 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002724 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002725 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002726 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002727 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002728 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002729
Danica Chang96567052010-08-11 14:54:43 -07002730 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002731 * Get the list of regular expressions that define any tetherable
2732 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2733 * device, this list should be empty.
2734 *
2735 * @return an array of 0 or more regular expression Strings defining
2736 * what interfaces are considered tetherable bluetooth interfaces.
2737 *
markchien75721e42020-01-21 13:11:06 +08002738 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2739 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002740 * {@hide}
2741 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002742 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002743 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002744 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002745 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002746 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002747 }
2748
Mike Lockwooded4a1742011-07-19 13:04:47 -07002749 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002750 * Attempt to both alter the mode of USB and Tethering of USB. A
2751 * utility method to deal with some of the complexity of USB - will
2752 * attempt to switch to Rndis and subsequently tether the resulting
2753 * interface on {@code true} or turn off tethering and switch off
2754 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002755 *
2756 * <p>This method requires the caller to hold either the
2757 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2758 * or the ability to modify system settings as determined by
2759 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002760 *
2761 * @param enable a boolean - {@code true} to enable tethering
2762 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002763 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002764 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002765 * {@hide}
2766 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002767 @UnsupportedAppUsage
markchien10ddd022020-01-20 19:31:56 +08002768 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002769 public int setUsbTethering(boolean enable) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002770 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002771 }
2772
markchien75721e42020-01-21 13:11:06 +08002773 /**
2774 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2775 * {@hide}
2776 */
markchien5bd499c2019-01-16 17:44:13 +08002777 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002778 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002779 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien75721e42020-01-21 13:11:06 +08002780 /**
2781 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2782 * {@hide}
2783 */
2784 @Deprecated
2785 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2786 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2787 /**
2788 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2789 * {@hide}
2790 */
2791 @Deprecated
2792 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2793 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2794 /**
2795 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2796 * {@hide}
2797 */
2798 @Deprecated
2799 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2800 /**
2801 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2802 * {@hide}
2803 */
2804 @Deprecated
2805 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2806 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2807 /**
markchien68b67842020-03-19 13:37:43 +08002808 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002809 * {@hide}
2810 */
2811 @Deprecated
markchien68b67842020-03-19 13:37:43 +08002812 public static final int TETHER_ERROR_MASTER_ERROR =
2813 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien75721e42020-01-21 13:11:06 +08002814 /**
2815 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2816 * {@hide}
2817 */
2818 @Deprecated
2819 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2820 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2821 /**
2822 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2823 * {@hide}
2824 */
2825 @Deprecated
2826 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2827 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2828 /**
markchien68b67842020-03-19 13:37:43 +08002829 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002830 * {@hide}
2831 */
2832 @Deprecated
2833 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002834 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002835 /**
markchien68b67842020-03-19 13:37:43 +08002836 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002837 * {@hide}
2838 */
2839 @Deprecated
2840 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002841 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002842 /**
2843 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2844 * {@hide}
2845 */
2846 @Deprecated
2847 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2848 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2849 /**
markchien68b67842020-03-19 13:37:43 +08002850 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien75721e42020-01-21 13:11:06 +08002851 * {@hide}
2852 */
markchien5bd499c2019-01-16 17:44:13 +08002853 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002854 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002855 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien75721e42020-01-21 13:11:06 +08002856 /**
2857 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2858 * {@hide}
2859 */
2860 @Deprecated
2861 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2862 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2863 /**
2864 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2865 * {@hide}
2866 */
markchien5bd499c2019-01-16 17:44:13 +08002867 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002868 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002869 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002870
2871 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002872 * Get a more detailed error code after a Tethering or Untethering
2873 * request asynchronously failed.
2874 *
2875 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002876 * @return error The error code of the last error tethering or untethering the named
2877 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002878 *
markchien75721e42020-01-21 13:11:06 +08002879 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002880 * {@hide}
2881 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002882 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002883 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien75721e42020-01-21 13:11:06 +08002884 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002885 public int getLastTetherError(String iface) {
markchien68b67842020-03-19 13:37:43 +08002886 int error = mTetheringManager.getLastTetherError(iface);
2887 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2888 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2889 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2890 // instead.
2891 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2892 }
2893 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002894 }
2895
markchiendd41c822019-03-06 16:25:00 +08002896 /** @hide */
2897 @Retention(RetentionPolicy.SOURCE)
2898 @IntDef(value = {
2899 TETHER_ERROR_NO_ERROR,
2900 TETHER_ERROR_PROVISION_FAILED,
2901 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2902 })
2903 public @interface EntitlementResultCode {
2904 }
2905
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002906 /**
markchiendd41c822019-03-06 16:25:00 +08002907 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08002908 * entitlement succeeded.
markchien75721e42020-01-21 13:11:06 +08002909 *
2910 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08002911 * @hide
2912 */
2913 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002914 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08002915 public interface OnTetheringEntitlementResultListener {
2916 /**
2917 * Called to notify entitlement result.
2918 *
2919 * @param resultCode an int value of entitlement result. It may be one of
2920 * {@link #TETHER_ERROR_NO_ERROR},
2921 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2922 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2923 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07002924 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08002925 }
2926
2927 /**
markchien5bd499c2019-01-16 17:44:13 +08002928 * Get the last value of the entitlement check on this downstream. If the cached value is
2929 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2930 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2931 * guaranteed that the UI-based entitlement check will complete in any specific time period
2932 * and may in fact never complete. Any successful entitlement check the platform performs for
2933 * any reason will update the cached value.
2934 *
2935 * @param type the downstream type of tethering. Must be one of
2936 * {@link #TETHERING_WIFI},
2937 * {@link #TETHERING_USB}, or
2938 * {@link #TETHERING_BLUETOOTH}.
2939 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08002940 * @param executor the executor on which callback will be invoked.
2941 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2942 * notify the caller of the result of entitlement check. The listener may be called zero
2943 * or one time.
markchien75721e42020-01-21 13:11:06 +08002944 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08002945 * {@hide}
2946 */
2947 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002948 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08002949 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08002950 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2951 @NonNull @CallbackExecutor Executor executor,
2952 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002953 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchiendd41c822019-03-06 16:25:00 +08002954 ResultReceiver wrappedListener = new ResultReceiver(null) {
2955 @Override
2956 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslin9cc04192021-03-04 09:38:21 +08002957 final long token = Binder.clearCallingIdentity();
2958 try {
2959 executor.execute(() -> {
2960 listener.onTetheringEntitlementResult(resultCode);
2961 });
2962 } finally {
2963 Binder.restoreCallingIdentity(token);
2964 }
markchiendd41c822019-03-06 16:25:00 +08002965 }
2966 };
2967
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002968 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienb0bb7862019-12-16 20:15:20 +08002969 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08002970 }
2971
2972 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002973 * Report network connectivity status. This is currently used only
2974 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04002975 * <p>This method requires the caller to hold the permission
2976 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08002977 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002978 * @param networkType The type of network you want to report on
2979 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09002980 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002981 * {@hide}
2982 */
2983 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09002984 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002985 try {
2986 mService.reportInetCondition(networkType, percentage);
2987 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002988 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002989 }
2990 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002991
2992 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002993 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07002994 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002995 * the framework to re-evaluate network connectivity and/or switch to another
2996 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002997 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002998 * @param network The {@link Network} the application was attempting to use
2999 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04003000 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3001 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003002 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003003 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09003004 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003005 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003006 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04003007 // One of these will be ignored because it matches system's current state.
3008 // The other will trigger the necessary reevaluation.
3009 mService.reportNetworkConnectivity(network, true);
3010 mService.reportNetworkConnectivity(network, false);
3011 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003012 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003013 }
3014 }
3015
3016 /**
3017 * Report to the framework whether a network has working connectivity.
3018 * This provides a hint to the system that a particular network is providing
3019 * working connectivity or not. In response the framework may re-evaluate
3020 * the network's connectivity and might take further action thereafter.
3021 *
3022 * @param network The {@link Network} the application was attempting to use
3023 * or {@code null} to indicate the current default network.
3024 * @param hasConnectivity {@code true} if the application was able to successfully access the
3025 * Internet using {@code network} or {@code false} if not.
3026 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003027 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003028 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003029 try {
3030 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003031 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003032 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003033 }
3034 }
3035
3036 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003037 * Set a network-independent global http proxy. This is not normally what you want
3038 * for typical HTTP proxies - they are general network dependent. However if you're
3039 * doing something unusual like general internal filtering this may be useful. On
3040 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003041 *
3042 * @param p A {@link ProxyInfo} object defining the new global
3043 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003044 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003045 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003046 @SystemApi(client = MODULE_LIBRARIES)
paulhuec0a9632019-08-12 16:25:11 +08003047 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003048 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003049 try {
3050 mService.setGlobalProxy(p);
3051 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003052 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003053 }
3054 }
3055
3056 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003057 * Retrieve any network-independent global HTTP proxy.
3058 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003059 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003060 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003061 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003062 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003063 @SystemApi(client = MODULE_LIBRARIES)
3064 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04003065 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003066 try {
3067 return mService.getGlobalProxy();
3068 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003069 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003070 }
3071 }
3072
3073 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003074 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3075 * network-specific HTTP proxy. If {@code network} is null, the
3076 * network-specific proxy returned is the proxy of the default active
3077 * network.
3078 *
3079 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3080 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3081 * or when {@code network} is {@code null},
3082 * the {@code ProxyInfo} for the default active network. Returns
3083 * {@code null} when no proxy applies or the caller doesn't have
3084 * permission to use {@code network}.
3085 * @hide
3086 */
3087 public ProxyInfo getProxyForNetwork(Network network) {
3088 try {
3089 return mService.getProxyForNetwork(network);
3090 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003091 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003092 }
3093 }
3094
3095 /**
Paul Jensen12131352014-12-10 15:12:18 -05003096 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3097 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003098 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003099 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003100 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003101 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003102 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003103 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003104 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003105 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003106 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003107 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003108
3109 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003110 * Returns true if the hardware supports the given network type
3111 * else it returns false. This doesn't indicate we have coverage
3112 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003113 * hardware supports it. For example a GSM phone without a SIM
3114 * should still return {@code true} for mobile data, but a wifi only
3115 * tablet would return {@code false}.
3116 *
3117 * @param networkType The network type we'd like to check
3118 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003119 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003120 * @hide
3121 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003122 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003123 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003124 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003125 public boolean isNetworkSupported(int networkType) {
3126 try {
3127 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003128 } catch (RemoteException e) {
3129 throw e.rethrowFromSystemServer();
3130 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003131 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003132
3133 /**
3134 * Returns if the currently active data network is metered. A network is
3135 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003136 * that connection due to monetary costs, data limitations or
3137 * battery/performance issues. You should check this before doing large
3138 * data transfers, and warn the user or delay the operation until another
3139 * network is available.
3140 *
3141 * @return {@code true} if large transfers should be avoided, otherwise
3142 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003143 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003144 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003145 public boolean isActiveNetworkMetered() {
3146 try {
3147 return mService.isActiveNetworkMetered();
3148 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003149 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003150 }
3151 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003152
Robert Greenwalt26744a52013-02-15 10:56:35 -08003153 /**
Sarah Chincab74db2020-11-25 12:15:14 -08003154 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003155 *
Sarah Chincab74db2020-11-25 12:15:14 -08003156 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003157 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003158 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003159 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003160 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003161 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003162 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003163 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003164 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003165 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003166 }
3167 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003168
3169 /**
3170 * Set the value for enabling/disabling airplane mode
3171 *
3172 * @param enable whether to enable airplane mode or not
3173 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003174 * @hide
3175 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003176 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003177 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003178 android.Manifest.permission.NETWORK_SETTINGS,
3179 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3180 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003181 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003182 public void setAirplaneMode(boolean enable) {
3183 try {
3184 mService.setAirplaneMode(enable);
3185 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003186 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003187 }
3188 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003189
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003190 /**
3191 * Registers the specified {@link NetworkProvider}.
3192 * Each listener must only be registered once. The listener can be unregistered with
3193 * {@link #unregisterNetworkProvider}.
3194 *
3195 * @param provider the provider to register
3196 * @return the ID of the provider. This ID must be used by the provider when registering
3197 * {@link android.net.NetworkAgent}s.
3198 * @hide
3199 */
3200 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003201 @RequiresPermission(anyOf = {
3202 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3203 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003204 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3205 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003206 throw new IllegalStateException("NetworkProviders can only be registered once");
3207 }
3208
3209 try {
3210 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3211 provider.getName());
3212 provider.setProviderId(providerId);
3213 } catch (RemoteException e) {
3214 throw e.rethrowFromSystemServer();
3215 }
3216 return provider.getProviderId();
3217 }
3218
3219 /**
3220 * Unregisters the specified NetworkProvider.
3221 *
3222 * @param provider the provider to unregister
3223 * @hide
3224 */
3225 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003226 @RequiresPermission(anyOf = {
3227 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3228 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003229 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3230 try {
3231 mService.unregisterNetworkProvider(provider.getMessenger());
3232 } catch (RemoteException e) {
3233 throw e.rethrowFromSystemServer();
3234 }
3235 provider.setProviderId(NetworkProvider.ID_NONE);
3236 }
3237
3238
3239 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003240 @RequiresPermission(anyOf = {
3241 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3242 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003243 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3244 try {
3245 mService.declareNetworkRequestUnfulfillable(request);
3246 } catch (RemoteException e) {
3247 throw e.rethrowFromSystemServer();
3248 }
3249 }
3250
Paul Jensenc2569432015-02-13 14:18:39 -05003251 /**
3252 * @hide
3253 * Register a NetworkAgent with ConnectivityService.
Chalard Jean1aea87a2019-12-13 19:47:12 +09003254 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003255 */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003256 @RequiresPermission(anyOf = {
3257 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3258 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003259 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeandd753522020-12-21 18:36:52 +09003260 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3261 int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003262 try {
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003263 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003264 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003265 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003266 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003267 }
3268
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003269 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003270 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3271 * changes. Should be extended by applications wanting notifications.
3272 *
3273 * A {@code NetworkCallback} is registered by calling
3274 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3275 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003276 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003277 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3278 * A {@code NetworkCallback} should be registered at most once at any time.
3279 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003280 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003281 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003282 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003283 * No flags associated with this callback.
3284 * @hide
3285 */
3286 public static final int FLAG_NONE = 0;
3287 /**
3288 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3289 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3290 * <p>
3291 * These include:
3292 * <li> Some transport info instances (retrieved via
3293 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3294 * contain location sensitive information.
3295 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3296 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3297 * </p>
3298 * <p>
3299 * Note:
3300 * <li> Retrieving this location sensitive information (subject to app's location
3301 * permissions) will be noted by system. </li>
3302 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3303 * not include location sensitive info.
3304 * </p>
3305 */
3306 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3307
3308 /** @hide */
3309 @Retention(RetentionPolicy.SOURCE)
3310 @IntDef(flag = true, prefix = "FLAG_", value = {
3311 FLAG_NONE,
3312 FLAG_INCLUDE_LOCATION_INFO
3313 })
3314 public @interface Flag { }
3315
3316 /**
3317 * All the valid flags for error checking.
3318 */
3319 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3320
3321 public NetworkCallback() {
3322 this(FLAG_NONE);
3323 }
3324
3325 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003326 if ((flags & VALID_FLAGS) != flags) {
3327 throw new IllegalArgumentException("Invalid flags");
3328 }
Roshan Pius7992afd2020-12-22 15:10:42 -08003329 mFlags = flags;
3330 }
3331
3332 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003333 * Called when the framework connects to a new network to evaluate whether it satisfies this
3334 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3335 * callback. There is no guarantee that this new network will satisfy any requests, or that
3336 * the network will stay connected for longer than the time necessary to evaluate it.
3337 * <p>
3338 * Most applications <b>should not</b> act on this callback, and should instead use
3339 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3340 * the framework in properly evaluating the network &mdash; for example, an application that
3341 * can automatically log in to a captive portal without user intervention.
3342 *
3343 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003344 *
3345 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003346 */
paulhua9a6e2a2019-03-22 16:35:06 +08003347 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003348
3349 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003350 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003351 * This callback may be called more than once if the {@link Network} that is
3352 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003353 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003354 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003355 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3356 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003357 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003358 * @hide
3359 */
paulhua9a6e2a2019-03-22 16:35:06 +08003360 public void onAvailable(@NonNull Network network,
3361 @NonNull NetworkCapabilities networkCapabilities,
3362 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003363 // Internally only this method is called when a new network is available, and
3364 // it calls the callback in the same way and order that older versions used
3365 // to call so as not to change the behavior.
3366 onAvailable(network);
3367 if (!networkCapabilities.hasCapability(
3368 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3369 onNetworkSuspended(network);
3370 }
3371 onCapabilitiesChanged(network, networkCapabilities);
3372 onLinkPropertiesChanged(network, linkProperties);
junyulai5ab727b2018-08-07 19:50:45 +08003373 onBlockedStatusChanged(network, blocked);
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003374 }
3375
3376 /**
3377 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003378 *
3379 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3380 * be available at the same time, and onAvailable will be called for each of these as they
3381 * appear.
3382 *
3383 * <p>For callbacks registered with {@link #requestNetwork} and
3384 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3385 * is the new best network for this request and is now tracked by this callback ; this
3386 * callback will no longer receive method calls about other networks that may have been
3387 * passed to this method previously. The previously-best network may have disconnected, or
3388 * it may still be around and the newly-best network may simply be better.
3389 *
3390 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3391 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3392 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3393 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3394 *
3395 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3396 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3397 * this callback as this is prone to race conditions (there is no guarantee the objects
3398 * returned by these methods will be current). Instead, wait for a call to
3399 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3400 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3401 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003402 *
3403 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003404 */
paulhua9a6e2a2019-03-22 16:35:06 +08003405 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003406
3407 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003408 * Called when the network is about to be lost, typically because there are no outstanding
3409 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3410 * with the new replacement network for graceful handover. This method is not guaranteed
3411 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3412 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003413 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003414 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3415 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3416 * this callback as this is prone to race conditions ; calling these methods while in a
3417 * callback may return an outdated or even a null object.
3418 *
3419 * @param network The {@link Network} that is about to be lost.
3420 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3421 * connected for graceful handover; note that the network may still
3422 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003423 */
paulhua9a6e2a2019-03-22 16:35:06 +08003424 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003425
3426 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003427 * Called when a network disconnects or otherwise no longer satisfies this request or
3428 * callback.
3429 *
3430 * <p>If the callback was registered with requestNetwork() or
3431 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3432 * returned by onAvailable() when that network is lost and no other network satisfies
3433 * the criteria of the request.
3434 *
3435 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3436 * each network which no longer satisfies the criteria of the callback.
3437 *
3438 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3439 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3440 * this callback as this is prone to race conditions ; calling these methods while in a
3441 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003442 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003443 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003444 */
paulhua9a6e2a2019-03-22 16:35:06 +08003445 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003446
3447 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003448 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003449 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3450 * requested network request cannot be fulfilled (whether or not a timeout was
3451 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003452 * {@link NetworkRequest} will have already been removed and released, as if
3453 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003454 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003455 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003456
3457 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003458 * Called when the network corresponding to this request changes capabilities but still
3459 * satisfies the requested criteria.
3460 *
3461 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3462 * to be called immediately after {@link #onAvailable}.
3463 *
3464 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3465 * ConnectivityManager methods in this callback as this is prone to race conditions :
3466 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003467 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003468 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius7992afd2020-12-22 15:10:42 -08003469 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003470 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003471 */
paulhua9a6e2a2019-03-22 16:35:06 +08003472 public void onCapabilitiesChanged(@NonNull Network network,
3473 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003474
3475 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003476 * Called when the network corresponding to this request changes {@link LinkProperties}.
3477 *
3478 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3479 * to be called immediately after {@link #onAvailable}.
3480 *
3481 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3482 * ConnectivityManager methods in this callback as this is prone to race conditions :
3483 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003484 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003485 * @param network The {@link Network} whose link properties have changed.
3486 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003487 */
paulhua9a6e2a2019-03-22 16:35:06 +08003488 public void onLinkPropertiesChanged(@NonNull Network network,
3489 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003490
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003491 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003492 * Called when the network the framework connected to for this request suspends data
3493 * transmission temporarily.
3494 *
3495 * <p>This generally means that while the TCP connections are still live temporarily
3496 * network data fails to transfer. To give a specific example, this is used on cellular
3497 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3498 * means read operations on sockets on this network will block once the buffers are
3499 * drained, and write operations will block once the buffers are full.
3500 *
3501 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3502 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3503 * this callback as this is prone to race conditions (there is no guarantee the objects
3504 * returned by these methods will be current).
3505 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003506 * @hide
3507 */
paulhua9a6e2a2019-03-22 16:35:06 +08003508 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003509
3510 /**
3511 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003512 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3513 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003514
3515 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3516 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3517 * this callback as this is prone to race conditions : calling these methods while in a
3518 * callback may return an outdated or even a null object.
3519 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003520 * @hide
3521 */
paulhua9a6e2a2019-03-22 16:35:06 +08003522 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003523
junyulai5ab727b2018-08-07 19:50:45 +08003524 /**
3525 * Called when access to the specified network is blocked or unblocked.
3526 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003527 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3528 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3529 * this callback as this is prone to race conditions : calling these methods while in a
3530 * callback may return an outdated or even a null object.
3531 *
junyulai5ab727b2018-08-07 19:50:45 +08003532 * @param network The {@link Network} whose blocked status has changed.
3533 * @param blocked The blocked status of this {@link Network}.
3534 */
junyulai61143782019-03-04 22:45:36 +08003535 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003536
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003537 private NetworkRequest networkRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -08003538 private final int mFlags;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003539 }
3540
Hugo Benichi145e3792017-05-11 13:16:17 +09003541 /**
3542 * Constant error codes used by ConnectivityService to communicate about failures and errors
3543 * across a Binder boundary.
3544 * @hide
3545 */
3546 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003547 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003548 }
3549
3550 /** @hide */
3551 public static class TooManyRequestsException extends RuntimeException {}
3552
3553 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3554 switch (e.errorCode) {
3555 case Errors.TOO_MANY_REQUESTS:
3556 return new TooManyRequestsException();
3557 default:
3558 Log.w(TAG, "Unknown service error code " + e.errorCode);
3559 return new RuntimeException(e);
3560 }
3561 }
3562
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003563 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003564 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003565 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003566 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003567 /** @hide arg1 = TTL */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003568 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003569 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003570 public static final int CALLBACK_LOST = 4;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003571 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003572 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003573 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003574 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003575 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003576 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003577 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003578 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003579 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003580 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003581 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003582 public static final int CALLBACK_RESUMED = 10;
junyulai5ab727b2018-08-07 19:50:45 +08003583 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003584 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003585
Erik Kline66721822015-11-25 12:49:38 +09003586 /** @hide */
3587 public static String getCallbackName(int whichCallback) {
3588 switch (whichCallback) {
3589 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3590 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3591 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3592 case CALLBACK_LOST: return "CALLBACK_LOST";
3593 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3594 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3595 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003596 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3597 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3598 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003599 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003600 default:
3601 return Integer.toString(whichCallback);
3602 }
3603 }
3604
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003605 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003606 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003607 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003608
Hugo Benichife3325f2016-07-06 22:53:17 +09003609 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003610 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003611 }
3612
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003613 CallbackHandler(Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003614 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003615 }
3616
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003617 @Override
3618 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003619 if (message.what == EXPIRE_LEGACY_REQUEST) {
3620 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3621 return;
3622 }
3623
3624 final NetworkRequest request = getObject(message, NetworkRequest.class);
3625 final Network network = getObject(message, Network.class);
3626 final NetworkCallback callback;
3627 synchronized (sCallbacks) {
3628 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003629 if (callback == null) {
3630 Log.w(TAG,
3631 "callback not found for " + getCallbackName(message.what) + " message");
3632 return;
3633 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003634 if (message.what == CALLBACK_UNAVAIL) {
3635 sCallbacks.remove(request);
3636 callback.networkRequest = ALREADY_UNREGISTERED;
3637 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003638 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003639 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003640 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003641 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003642
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003643 switch (message.what) {
3644 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003645 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003646 break;
3647 }
3648 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003649 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3650 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai5ab727b2018-08-07 19:50:45 +08003651 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003652 break;
3653 }
3654 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003655 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003656 break;
3657 }
3658 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003659 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003660 break;
3661 }
3662 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003663 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003664 break;
3665 }
3666 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003667 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3668 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003669 break;
3670 }
3671 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003672 LinkProperties lp = getObject(message, LinkProperties.class);
3673 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003674 break;
3675 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003676 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003677 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003678 break;
3679 }
3680 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003681 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003682 break;
3683 }
junyulai5ab727b2018-08-07 19:50:45 +08003684 case CALLBACK_BLK_CHANGED: {
3685 boolean blocked = message.arg1 != 0;
3686 callback.onBlockedStatusChanged(network, blocked);
3687 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003688 }
3689 }
3690
Hugo Benichife3325f2016-07-06 22:53:17 +09003691 private <T> T getObject(Message msg, Class<T> c) {
3692 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003693 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003694 }
3695
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003696 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003697 synchronized (sCallbacks) {
3698 if (sCallbackHandler == null) {
3699 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003700 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003701 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003702 }
3703 }
3704
Hugo Benichiec180d52017-02-03 14:18:44 +09003705 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3706 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003707
Hugo Benichiec180d52017-02-03 14:18:44 +09003708 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaid1a78162021-01-11 16:53:38 +08003709 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003710 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003711 checkCallbackNotNull(callback);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003712 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3713 throw new IllegalArgumentException("null NetworkCapabilities");
3714 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003715 final NetworkRequest request;
Roshan Piusd26ae412020-01-16 12:17:17 -08003716 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003717 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003718 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003719 if (callback.networkRequest != null
3720 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003721 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3722 // and requests (http://b/20701525).
3723 Log.e(TAG, "NetworkCallback was already registered");
3724 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003725 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003726 Binder binder = new Binder();
Roshan Pius7992afd2020-12-22 15:10:42 -08003727 final int callbackFlags = callback.mFlags;
junyulaid1a78162021-01-11 16:53:38 +08003728 if (reqType == LISTEN) {
Roshan Piusd26ae412020-01-16 12:17:17 -08003729 request = mService.listenForNetwork(
Roshan Pius7992afd2020-12-22 15:10:42 -08003730 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08003731 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003732 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003733 request = mService.requestNetwork(
junyulaid1a78162021-01-11 16:53:38 +08003734 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
Roshan Pius7992afd2020-12-22 15:10:42 -08003735 callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003736 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003737 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003738 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003739 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003740 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003741 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003742 } catch (RemoteException e) {
3743 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003744 } catch (ServiceSpecificException e) {
3745 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003746 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003747 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003748 }
3749
3750 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003751 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003752 *
markchien0fe11402020-03-18 21:16:15 +08003753 * This API is only for use in internal system code that requests networks with legacy type and
3754 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchien769c5752020-01-14 12:54:40 +08003755 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003756 *
markchien769c5752020-01-14 12:54:40 +08003757 * @param request {@link NetworkRequest} describing this request.
markchien769c5752020-01-14 12:54:40 +08003758 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3759 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3760 * be a positive value (i.e. >0).
3761 * @param legacyType to specify the network type(#TYPE_*).
3762 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien0fe11402020-03-18 21:16:15 +08003763 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3764 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003765 *
3766 * @hide
3767 */
markchien769c5752020-01-14 12:54:40 +08003768 @SystemApi
markchien0fe11402020-03-18 21:16:15 +08003769 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003770 public void requestNetwork(@NonNull NetworkRequest request,
markchien0fe11402020-03-18 21:16:15 +08003771 int timeoutMs, int legacyType, @NonNull Handler handler,
3772 @NonNull NetworkCallback networkCallback) {
3773 if (legacyType == TYPE_NONE) {
3774 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3775 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003776 CallbackHandler cbHandler = new CallbackHandler(handler);
3777 NetworkCapabilities nc = request.networkCapabilities;
3778 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003779 }
3780
3781 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003782 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003783 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003784 * <p>This method will attempt to find the best network that matches the passed
3785 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3786 * criteria. The platform will evaluate which network is the best at its own discretion.
3787 * Throughput, latency, cost per byte, policy, user preference and other considerations
3788 * may be factored in the decision of what is considered the best network.
3789 *
3790 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3791 * matching this request, while always attempting to match the request to a better network if
3792 * possible. If a better match is found, the platform will switch this request to the now-best
3793 * network and inform the app of the newly best network by invoking
3794 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3795 * will not try to maintain any other network than the best one currently matching the request:
3796 * a network not matching any network request may be disconnected at any time.
3797 *
3798 * <p>For example, an application could use this method to obtain a connected cellular network
3799 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3800 * radio to consume additional power. Or, an application could inform the system that it wants
3801 * a network supporting sending MMSes and have the system let it know about the currently best
3802 * MMS-supporting network through the provided {@link NetworkCallback}.
3803 *
3804 * <p>The status of the request can be followed by listening to the various callbacks described
3805 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3806 * used to direct traffic to the network (although accessing some networks may be subject to
3807 * holding specific permissions). Callers will learn about the specific characteristics of the
3808 * network through
3809 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3810 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3811 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3812 * matching the request at any given time; therefore when a better network matching the request
3813 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3814 * with the new network after which no further updates are given about the previously-best
3815 * network, unless it becomes the best again at some later time. All callbacks are invoked
3816 * in order on the same thread, which by default is a thread created by the framework running
3817 * in the app.
3818 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3819 * callbacks are invoked.
3820 *
3821 * <p>This{@link NetworkRequest} will live until released via
3822 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3823 * which point the system may let go of the network at any time.
3824 *
3825 * <p>A version of this method which takes a timeout is
3826 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3827 * wait for a limited amount of time for the network to become unavailable.
3828 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003829 * <p>It is presently unsupported to request a network with mutable
3830 * {@link NetworkCapabilities} such as
3831 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3832 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3833 * as these {@code NetworkCapabilities} represent states that a particular
3834 * network may never attain, and whether a network will attain these states
3835 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09003836 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003837 *
3838 * <p>This method requires the caller to hold either the
3839 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3840 * or the ability to modify system settings as determined by
3841 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003842 *
Chalard Jean7f06b342020-05-20 16:11:50 +09003843 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3844 * number of outstanding requests to 100 per app (identified by their UID), shared with
3845 * all variants of this method, of {@link #registerNetworkCallback} as well as
3846 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3847 * Requesting a network with this method will count toward this limit. If this limit is
3848 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3849 * make sure to unregister the callbacks with
3850 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3851 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003852 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003853 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3854 * the callback must not be shared - it uniquely specifies this request.
3855 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09003856 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3857 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09003858 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003859 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003860 public void requestNetwork(@NonNull NetworkRequest request,
3861 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003862 requestNetwork(request, networkCallback, getDefaultHandler());
3863 }
3864
3865 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003866 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003867 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003868 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3869 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003870 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003871 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003872 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3873 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003874 *
3875 * @param request {@link NetworkRequest} describing this request.
3876 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3877 * the callback must not be shared - it uniquely specifies this request.
3878 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003879 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003880 public void requestNetwork(@NonNull NetworkRequest request,
3881 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003882 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08003883 NetworkCapabilities nc = request.networkCapabilities;
3884 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003885 }
3886
3887 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003888 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohen67e58a02017-03-01 12:47:28 -08003889 * by a timeout.
3890 *
3891 * This function behaves identically to the non-timed-out version
3892 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3893 * is not found within the given time (in milliseconds) the
3894 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3895 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3896 * not have to be released if timed-out (it is automatically released). Unregistering a
3897 * request that timed out is not an error.
3898 *
3899 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3900 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3901 * for that purpose. Calling this method will attempt to bring up the requested network.
3902 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003903 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003904 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3905 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08003906 *
3907 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003908 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3909 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003910 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3911 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3912 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08003913 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003914 public void requestNetwork(@NonNull NetworkRequest request,
3915 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003916 checkTimeout(timeoutMs);
markchien0fe11402020-03-18 21:16:15 +08003917 NetworkCapabilities nc = request.networkCapabilities;
3918 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3919 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003920 }
3921
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003922 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003923 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003924 * by a timeout.
3925 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003926 * This method behaves identically to
3927 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3928 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08003929 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003930 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003931 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3932 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003933 *
3934 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003935 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3936 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003937 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003938 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3939 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003940 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003941 public void requestNetwork(@NonNull NetworkRequest request,
3942 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003943 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003944 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08003945 NetworkCapabilities nc = request.networkCapabilities;
3946 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003947 }
3948
3949 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003950 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003951 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003952 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08003953 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04003954 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3955 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003956 */
Erik Klinefb087f12014-11-19 12:12:24 +09003957 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003958
3959 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003960 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003961 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003962 * {@link android.content.Intent#getParcelableExtra(String)}.
3963 */
Erik Klinefb087f12014-11-19 12:12:24 +09003964 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003965
3966
3967 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003968 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003969 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08003970 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003971 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003972 * the request may outlive the calling application and get called back when a suitable
3973 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003974 * <p>
3975 * The operation is an Intent broadcast that goes to a broadcast receiver that
3976 * you registered with {@link Context#registerReceiver} or through the
3977 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3978 * <p>
3979 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09003980 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3981 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003982 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003983 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003984 * Intent to reserve the network or it will be released shortly after the Intent
3985 * is processed.
3986 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04003987 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003988 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003989 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003990 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08003991 * The request may be released normally by calling
3992 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003993 * <p>It is presently unsupported to request a network with either
3994 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3995 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3996 * as these {@code NetworkCapabilities} represent states that a particular
3997 * network may never attain, and whether a network will attain these states
3998 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09003999 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004000 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004001 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4002 * number of outstanding requests to 100 per app (identified by their UID), shared with
4003 * all variants of this method, of {@link #registerNetworkCallback} as well as
4004 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4005 * Requesting a network with this method will count toward this limit. If this limit is
4006 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4007 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4008 * or {@link #releaseNetworkRequest(PendingIntent)}.
4009 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004010 * <p>This method requires the caller to hold either the
4011 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4012 * or the ability to modify system settings as determined by
4013 * {@link android.provider.Settings.System#canWrite}.</p>
4014 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004015 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004016 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004017 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08004018 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004019 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4020 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004021 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004022 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004023 public void requestNetwork(@NonNull NetworkRequest request,
4024 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004025 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004026 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004027 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004028 mService.pendingRequestForNetwork(
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07004029 request.networkCapabilities, operation, mContext.getOpPackageName(),
4030 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004031 } catch (RemoteException e) {
4032 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004033 } catch (ServiceSpecificException e) {
4034 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004035 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004036 }
4037
4038 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004039 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4040 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004041 * This method has the same behavior as
4042 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004043 * releasing network resources and disconnecting.
4044 *
4045 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4046 * PendingIntent passed to
4047 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4048 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4049 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004050 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004051 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004052 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004053 try {
4054 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004055 } catch (RemoteException e) {
4056 throw e.rethrowFromSystemServer();
4057 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004058 }
4059
Hugo Benichiff4bf602017-05-09 15:19:01 +09004060 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004061 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004062 }
4063
4064 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004065 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004066 }
4067
4068 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004069 if (timeoutMs <= 0) {
4070 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4071 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004072 }
4073
4074 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004075 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004076 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004077 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4078 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004079 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004080 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4081 * number of outstanding requests to 100 per app (identified by their UID), shared with
4082 * all variants of this method, of {@link #requestNetwork} as well as
4083 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4084 * Requesting a network with this method will count toward this limit. If this limit is
4085 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4086 * make sure to unregister the callbacks with
4087 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4088 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004089 * @param request {@link NetworkRequest} describing this request.
4090 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4091 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004092 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004093 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004094 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004095 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004096 public void registerNetworkCallback(@NonNull NetworkRequest request,
4097 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004098 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4099 }
4100
4101 /**
4102 * Registers to receive notifications about all networks which satisfy the given
4103 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004104 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4105 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004106 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004107 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4108 * number of outstanding requests to 100 per app (identified by their UID), shared with
4109 * all variants of this method, of {@link #requestNetwork} as well as
4110 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4111 * Requesting a network with this method will count toward this limit. If this limit is
4112 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4113 * make sure to unregister the callbacks with
4114 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4115 *
4116 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004117 * @param request {@link NetworkRequest} describing this request.
4118 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4119 * networks change state.
4120 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004121 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004122 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004123 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004124 public void registerNetworkCallback(@NonNull NetworkRequest request,
4125 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004126 CallbackHandler cbHandler = new CallbackHandler(handler);
4127 NetworkCapabilities nc = request.networkCapabilities;
4128 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004129 }
4130
4131 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004132 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4133 * {@link NetworkRequest}.
4134 *
4135 * This function behaves identically to the version that takes a NetworkCallback, but instead
4136 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4137 * the request may outlive the calling application and get called back when a suitable
4138 * network is found.
4139 * <p>
4140 * The operation is an Intent broadcast that goes to a broadcast receiver that
4141 * you registered with {@link Context#registerReceiver} or through the
4142 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4143 * <p>
4144 * The operation Intent is delivered with two extras, a {@link Network} typed
4145 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4146 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4147 * the original requests parameters.
4148 * <p>
4149 * If there is already a request for this Intent registered (with the equality of
4150 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4151 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4152 * <p>
4153 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004154 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004155 *
4156 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4157 * number of outstanding requests to 100 per app (identified by their UID), shared with
4158 * all variants of this method, of {@link #requestNetwork} as well as
4159 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4160 * Requesting a network with this method will count toward this limit. If this limit is
4161 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4162 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4163 * or {@link #releaseNetworkRequest(PendingIntent)}.
4164 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004165 * @param request {@link NetworkRequest} describing this request.
4166 * @param operation Action to perform when the network is available (corresponds
4167 * to the {@link NetworkCallback#onAvailable} call. Typically
4168 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004169 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004170 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004171 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004172 public void registerNetworkCallback(@NonNull NetworkRequest request,
4173 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004174 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004175 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004176 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004177 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004178 request.networkCapabilities, operation, mContext.getOpPackageName(),
4179 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004180 } catch (RemoteException e) {
4181 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004182 } catch (ServiceSpecificException e) {
4183 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004184 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004185 }
4186
4187 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004188 * Registers to receive notifications about changes in the application's default network. This
4189 * may be a physical network or a virtual network, such as a VPN that applies to the
4190 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004191 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004192 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004193 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4194 * number of outstanding requests to 100 per app (identified by their UID), shared with
4195 * all variants of this method, of {@link #requestNetwork} as well as
4196 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4197 * Requesting a network with this method will count toward this limit. If this limit is
4198 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4199 * make sure to unregister the callbacks with
4200 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4201 *
Erik Klinee0aed632016-03-16 15:31:39 +09004202 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004203 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004204 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004205 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004206 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004207 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004208 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004209 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4210 }
4211
4212 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004213 * Registers to receive notifications about changes in the application's default network. This
4214 * may be a physical network or a virtual network, such as a VPN that applies to the
4215 * application. The callbacks will continue to be called until either the application exits or
4216 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4217 *
4218 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4219 * number of outstanding requests to 100 per app (identified by their UID), shared with
4220 * all variants of this method, of {@link #requestNetwork} as well as
4221 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4222 * Requesting a network with this method will count toward this limit. If this limit is
4223 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4224 * make sure to unregister the callbacks with
4225 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4226 *
4227 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4228 * application's default network changes.
4229 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4230 * @throws RuntimeException if the app already has too many callbacks registered.
4231 */
4232 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4233 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4234 @NonNull Handler handler) {
4235 CallbackHandler cbHandler = new CallbackHandler(handler);
4236 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4237 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4238 }
4239
4240 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004241 * Registers to receive notifications about changes in the system default network. The callbacks
4242 * will continue to be called until either the application exits or
4243 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004244 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004245 * This method should not be used to determine networking state seen by applications, because in
4246 * many cases, most or even all application traffic may not use the default network directly,
4247 * and traffic from different applications may go on different networks by default. As an
4248 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4249 * and not onto the system default network. Applications or system components desiring to do
4250 * determine network state as seen by applications should use other methods such as
4251 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4252 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004253 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4254 * number of outstanding requests to 100 per app (identified by their UID), shared with
4255 * all variants of this method, of {@link #requestNetwork} as well as
4256 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4257 * Requesting a network with this method will count toward this limit. If this limit is
4258 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4259 * make sure to unregister the callbacks with
4260 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4261 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004262 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4263 * system default network changes.
4264 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004265 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004266 *
4267 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004268 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004269 @SystemApi(client = MODULE_LIBRARIES)
4270 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4271 @RequiresPermission(anyOf = {
4272 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4273 android.Manifest.permission.NETWORK_SETTINGS})
4274 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004275 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004276 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004277 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004278 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004279 }
4280
4281 /**
junyulaibd622262021-03-15 11:48:48 +08004282 * Registers to receive notifications about the best matching network which satisfy the given
4283 * {@link NetworkRequest}. The callbacks will continue to be called until
4284 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4285 * called.
4286 *
4287 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4288 * number of outstanding requests to 100 per app (identified by their UID), shared with
4289 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4290 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4291 * Requesting a network with this method will count toward this limit. If this limit is
4292 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4293 * make sure to unregister the callbacks with
4294 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4295 *
4296 *
4297 * @param request {@link NetworkRequest} describing this request.
4298 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4299 * networks change state.
4300 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4301 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai6b0a6a22021-03-05 15:51:17 +08004302 */
junyulai6b0a6a22021-03-05 15:51:17 +08004303 @SuppressLint("ExecutorRegistration")
4304 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4305 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4306 final NetworkCapabilities nc = request.networkCapabilities;
4307 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai8cae3c72021-03-12 20:05:08 +08004308 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai6b0a6a22021-03-05 15:51:17 +08004309 }
4310
4311 /**
fenglu73169332015-04-21 17:12:05 -07004312 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4313 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4314 * network connection for updated bandwidth information. The caller will be notified via
4315 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004316 * method assumes that the caller has previously called
4317 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4318 * changes.
fenglu76564332015-03-20 11:29:56 -07004319 *
fenglu41808e82015-04-27 14:28:04 -07004320 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004321 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004322 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004323 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004324 try {
fenglu73169332015-04-21 17:12:05 -07004325 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004326 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004327 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004328 }
4329 }
4330
4331 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004332 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004333 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4334 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4335 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004336 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4337 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004338 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004339 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4340 * triggering it as soon as this call returns.
4341 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004342 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004343 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004344 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004345 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004346 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004347 final List<NetworkRequest> reqs = new ArrayList<>();
4348 // Find all requests associated to this callback and stop callback triggers immediately.
4349 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4350 synchronized (sCallbacks) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004351 if (networkCallback.networkRequest == null) {
4352 throw new IllegalArgumentException("NetworkCallback was not registered");
4353 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07004354 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4355 Log.d(TAG, "NetworkCallback was already unregistered");
4356 return;
4357 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004358 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4359 if (e.getValue() == networkCallback) {
4360 reqs.add(e.getKey());
4361 }
4362 }
4363 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4364 for (NetworkRequest r : reqs) {
4365 try {
4366 mService.releaseNetworkRequest(r);
4367 } catch (RemoteException e) {
4368 throw e.rethrowFromSystemServer();
4369 }
4370 // Only remove mapping if rpc was successful.
4371 sCallbacks.remove(r);
4372 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004373 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004374 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004375 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004376
4377 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004378 * Unregisters a callback previously registered via
4379 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4380 *
4381 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4382 * PendingIntent passed to
4383 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4384 * Cannot be null.
4385 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004386 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004387 releaseNetworkRequest(operation);
4388 }
4389
4390 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004391 * Informs the system whether it should switch to {@code network} regardless of whether it is
4392 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4393 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4394 * the system default network regardless of any other network that's currently connected. If
4395 * {@code always} is true, then the choice is remembered, so that the next time the user
4396 * connects to this network, the system will switch to it.
4397 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004398 * @param network The network to accept.
4399 * @param accept Whether to accept the network even if unvalidated.
4400 * @param always Whether to remember this choice in the future.
4401 *
4402 * @hide
4403 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004404 @SystemApi(client = MODULE_LIBRARIES)
4405 @RequiresPermission(anyOf = {
4406 android.Manifest.permission.NETWORK_SETTINGS,
4407 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4408 android.Manifest.permission.NETWORK_STACK,
4409 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4410 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004411 try {
4412 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004413 } catch (RemoteException e) {
4414 throw e.rethrowFromSystemServer();
4415 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004416 }
4417
4418 /**
lucaslin25a50472019-03-12 13:08:03 +08004419 * Informs the system whether it should consider the network as validated even if it only has
4420 * partial connectivity. If {@code accept} is true, then the network will be considered as
4421 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4422 * is remembered, so that the next time the user connects to this network, the system will
4423 * switch to it.
4424 *
4425 * @param network The network to accept.
4426 * @param accept Whether to consider the network as validated even if it has partial
4427 * connectivity.
4428 * @param always Whether to remember this choice in the future.
4429 *
4430 * @hide
4431 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004432 @SystemApi(client = MODULE_LIBRARIES)
4433 @RequiresPermission(anyOf = {
4434 android.Manifest.permission.NETWORK_SETTINGS,
4435 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4436 android.Manifest.permission.NETWORK_STACK,
4437 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4438 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4439 boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004440 try {
4441 mService.setAcceptPartialConnectivity(network, accept, always);
4442 } catch (RemoteException e) {
4443 throw e.rethrowFromSystemServer();
4444 }
4445 }
4446
4447 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004448 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4449 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4450 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4451 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4452 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004453 * @param network The network to accept.
4454 *
4455 * @hide
4456 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004457 @SystemApi(client = MODULE_LIBRARIES)
4458 @RequiresPermission(anyOf = {
4459 android.Manifest.permission.NETWORK_SETTINGS,
4460 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4461 android.Manifest.permission.NETWORK_STACK,
4462 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4463 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004464 try {
4465 mService.setAvoidUnvalidated(network);
4466 } catch (RemoteException e) {
4467 throw e.rethrowFromSystemServer();
4468 }
4469 }
4470
4471 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004472 * Requests that the system open the captive portal app on the specified network.
4473 *
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004474 * <p>This is to be used on networks where a captive portal was detected, as per
4475 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4476 *
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004477 * @param network The network to log into.
4478 *
4479 * @hide
4480 */
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004481 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4482 @RequiresPermission(anyOf = {
4483 android.Manifest.permission.NETWORK_SETTINGS,
4484 android.Manifest.permission.NETWORK_STACK,
4485 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4486 })
4487 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004488 try {
4489 mService.startCaptivePortalApp(network);
4490 } catch (RemoteException e) {
4491 throw e.rethrowFromSystemServer();
4492 }
4493 }
4494
4495 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004496 * Requests that the system open the captive portal app with the specified extras.
4497 *
4498 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4499 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004500 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004501 * @param appExtras Extras to include in the app start intent.
4502 * @hide
4503 */
4504 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004505 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004506 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004507 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004508 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004509 } catch (RemoteException e) {
4510 throw e.rethrowFromSystemServer();
4511 }
4512 }
4513
4514 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004515 * Determine whether the device is configured to avoid bad wifi.
4516 * @hide
4517 */
4518 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004519 @RequiresPermission(anyOf = {
4520 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4521 android.Manifest.permission.NETWORK_STACK})
4522 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004523 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004524 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004525 } catch (RemoteException e) {
4526 throw e.rethrowFromSystemServer();
4527 }
4528 }
4529
4530 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004531 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4532 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004533 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4534 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004535 *
4536 * An example of such an operation might be a time-sensitive foreground activity, such as a
4537 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4538 */
4539 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4540
4541 /**
4542 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4543 * a backup channel for traffic that is primarily going over another network.
4544 *
4545 * An example might be maintaining backup connections to peers or servers for the purpose of
4546 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4547 * on backup paths should be negligible compared to the traffic on the main path.
4548 */
4549 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4550
4551 /**
4552 * It is acceptable to use metered data to improve network latency and performance.
4553 */
4554 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4555
4556 /**
4557 * Return value to use for unmetered networks. On such networks we currently set all the flags
4558 * to true.
4559 * @hide
4560 */
4561 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4562 MULTIPATH_PREFERENCE_HANDOVER |
4563 MULTIPATH_PREFERENCE_RELIABILITY |
4564 MULTIPATH_PREFERENCE_PERFORMANCE;
4565
4566 /** @hide */
4567 @Retention(RetentionPolicy.SOURCE)
4568 @IntDef(flag = true, value = {
4569 MULTIPATH_PREFERENCE_HANDOVER,
4570 MULTIPATH_PREFERENCE_RELIABILITY,
4571 MULTIPATH_PREFERENCE_PERFORMANCE,
4572 })
4573 public @interface MultipathPreference {
4574 }
4575
4576 /**
4577 * Provides a hint to the calling application on whether it is desirable to use the
4578 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4579 * for multipath data transfer on this network when it is not the system default network.
4580 * Applications desiring to use multipath network protocols should call this method before
4581 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004582 *
4583 * @param network The network on which the application desires to use multipath data.
4584 * If {@code null}, this method will return the a preference that will generally
4585 * apply to metered networks.
4586 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4587 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004588 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004589 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004590 try {
4591 return mService.getMultipathPreference(network);
4592 } catch (RemoteException e) {
4593 throw e.rethrowFromSystemServer();
4594 }
4595 }
4596
4597 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004598 * Resets all connectivity manager settings back to factory defaults.
4599 * @hide
4600 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004601 @SystemApi(client = MODULE_LIBRARIES)
4602 @RequiresPermission(anyOf = {
4603 android.Manifest.permission.NETWORK_SETTINGS,
4604 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scottd3bb5082015-03-30 13:17:11 -07004605 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004606 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004607 mService.factoryReset();
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00004608 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004609 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004610 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004611 }
4612 }
4613
4614 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004615 * Binds the current process to {@code network}. All Sockets created in the future
4616 * (and not explicitly bound via a bound SocketFactory from
4617 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4618 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4619 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4620 * work and all host name resolutions will fail. This is by design so an application doesn't
4621 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4622 * To clear binding pass {@code null} for {@code network}. Using individually bound
4623 * Sockets created by Network.getSocketFactory().createSocket() and
4624 * performing network-specific host name resolutions via
4625 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004626 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004627 *
4628 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4629 * the current binding.
4630 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4631 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004632 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004633 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004634 // instantiated.
4635 return setProcessDefaultNetwork(network);
4636 }
4637
4638 /**
4639 * Binds the current process to {@code network}. All Sockets created in the future
4640 * (and not explicitly bound via a bound SocketFactory from
4641 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4642 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4643 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4644 * work and all host name resolutions will fail. This is by design so an application doesn't
4645 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4646 * To clear binding pass {@code null} for {@code network}. Using individually bound
4647 * Sockets created by Network.getSocketFactory().createSocket() and
4648 * performing network-specific host name resolutions via
4649 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4650 * {@code setProcessDefaultNetwork}.
4651 *
4652 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4653 * the current binding.
4654 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4655 * @deprecated This function can throw {@link IllegalStateException}. Use
4656 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4657 * is a direct replacement.
4658 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004659 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004660 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004661 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004662 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4663
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004664 if (netId != NETID_UNSET) {
4665 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004666 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004667
4668 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4669 return false;
4670 }
4671
4672 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004673 // Set HTTP proxy system properties to match network.
4674 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004675 try {
Remi NGUYEN VANa1860ff2021-02-03 10:18:20 +09004676 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004677 } catch (SecurityException e) {
4678 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4679 Log.e(TAG, "Can't set proxy properties", e);
4680 }
Paul Jensen99c36662014-08-27 12:38:45 -04004681 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN33e3abb2021-03-18 23:27:19 +09004682 InetAddressCompat.clearDnsCache();
Paul Jensen99c36662014-08-27 12:38:45 -04004683 // Must flush socket pool as idle sockets will be bound to previous network and may
4684 // cause subsequent fetches to be performed on old network.
4685 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004686 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004687
4688 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004689 }
4690
4691 /**
4692 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004693 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004694 *
4695 * @return {@code Network} to which this process is bound, or {@code null}.
4696 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004697 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004698 public Network getBoundNetworkForProcess() {
4699 // Forcing callers to call thru non-static function ensures ConnectivityManager
4700 // instantiated.
4701 return getProcessDefaultNetwork();
4702 }
4703
4704 /**
4705 * Returns the {@link Network} currently bound to this process via
4706 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4707 *
4708 * @return {@code Network} to which this process is bound, or {@code null}.
4709 * @deprecated Using this function can lead to other functions throwing
4710 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4711 * {@code getBoundNetworkForProcess} is a direct replacement.
4712 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004713 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004714 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004715 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004716 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004717 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004718 return new Network(netId);
4719 }
4720
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004721 private void unsupportedStartingFrom(int version) {
4722 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004723 // The getApplicationInfo() call we make below is not supported in system context. Let
4724 // the call through here, and rely on the fact that ConnectivityService will refuse to
4725 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004726 return;
4727 }
4728
4729 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4730 throw new UnsupportedOperationException(
4731 "This method is not supported in target SDK version " + version + " and above");
4732 }
4733 }
4734
4735 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4736 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004737 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004738 // remove these exemptions. Note that this check is not secure, and apps can still access these
4739 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4740 // so is unsupported and may break in the future. http://b/22728205
4741 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07004742 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004743 }
4744
Paul Jensene98c6e02014-05-29 10:12:39 -04004745 /**
4746 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04004747 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04004748 *
4749 * @param network The {@link Network} to bind host resolutions from the current process to, or
4750 * {@code null} to clear the current binding.
4751 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4752 * @hide
4753 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4754 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004755 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00004756 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04004757 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04004758 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09004759 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04004760 }
Felipe Lemed16384b2016-01-22 09:44:57 -08004761
4762 /**
4763 * Device is not restricting metered network activity while application is running on
4764 * background.
4765 */
4766 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4767
4768 /**
4769 * Device is restricting metered network activity while application is running on background,
4770 * but application is allowed to bypass it.
4771 * <p>
4772 * In this state, application should take action to mitigate metered network access.
4773 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4774 */
4775 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4776
4777 /**
4778 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08004779 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08004780 * In this state, application should not try to use the network while running on background,
4781 * because it would be denied.
4782 */
4783 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4784
Felipe Leme6a5b7692016-01-27 14:46:39 -08004785 /**
4786 * A change in the background metered network activity restriction has occurred.
4787 * <p>
4788 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4789 * applies to them.
4790 * <p>
4791 * This is only sent to registered receivers, not manifest receivers.
4792 */
4793 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4794 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4795 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4796
Felipe Leme1b42ef92016-01-25 11:48:04 -08004797 /** @hide */
4798 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08004799 @IntDef(flag = false, value = {
4800 RESTRICT_BACKGROUND_STATUS_DISABLED,
4801 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4802 RESTRICT_BACKGROUND_STATUS_ENABLED,
4803 })
Felipe Lemed16384b2016-01-22 09:44:57 -08004804 public @interface RestrictBackgroundStatus {
4805 }
4806
Felipe Lemed16384b2016-01-22 09:44:57 -08004807 /**
4808 * Determines if the calling application is subject to metered network restrictions while
4809 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07004810 *
4811 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4812 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4813 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08004814 */
4815 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4816 try {
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09004817 return mService.getRestrictBackgroundStatusByCaller();
Felipe Lemed16384b2016-01-22 09:44:57 -08004818 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004819 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08004820 }
4821 }
Ricky Waid53cf002018-01-23 04:09:45 +00004822
4823 /**
4824 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00004825 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4826 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00004827 *
4828 * @return Hash of network watchlist config file. Null if config does not exist.
4829 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004830 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00004831 public byte[] getNetworkWatchlistConfigHash() {
4832 try {
4833 return mService.getNetworkWatchlistConfigHash();
4834 } catch (RemoteException e) {
4835 Log.e(TAG, "Unable to get watchlist config hash");
4836 throw e.rethrowFromSystemServer();
4837 }
4838 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004839
4840 /**
4841 * Returns the {@code uid} of the owner of a network connection.
4842 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08004843 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4844 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004845 * @param local The local {@link InetSocketAddress} of a connection.
4846 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004847 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08004848 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4849 * android.os.Process#INVALID_UID} if the connection is not found.
4850 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4851 * user.
4852 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004853 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08004854 public int getConnectionOwnerUid(
4855 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004856 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4857 try {
4858 return mService.getConnectionOwnerUid(connectionInfo);
4859 } catch (RemoteException e) {
4860 throw e.rethrowFromSystemServer();
4861 }
4862 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004863
4864 private void printStackTrace() {
4865 if (DEBUG) {
4866 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4867 final StringBuffer sb = new StringBuffer();
4868 for (int i = 3; i < callStack.length; i++) {
4869 final String stackTrace = callStack[i].toString();
4870 if (stackTrace == null || stackTrace.contains("android.os")) {
4871 break;
4872 }
4873 sb.append(" [").append(stackTrace).append("]");
4874 }
4875 Log.d(TAG, "StackLog:" + sb.toString());
4876 }
4877 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004878
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004879 /** @hide */
4880 public TestNetworkManager startOrGetTestNetworkManager() {
4881 final IBinder tnBinder;
4882 try {
4883 tnBinder = mService.startOrGetTestNetworkService();
4884 } catch (RemoteException e) {
4885 throw e.rethrowFromSystemServer();
4886 }
4887
4888 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4889 }
4890
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004891 /** @hide */
4892 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4893 return new ConnectivityDiagnosticsManager(mContext, mService);
4894 }
4895
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004896 /**
4897 * Simulates a Data Stall for the specified Network.
4898 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004899 * <p>This method should only be used for tests.
4900 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004901 * <p>The caller must be the owner of the specified Network.
4902 *
4903 * @param detectionMethod The detection method used to identify the Data Stall.
4904 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4905 * @param network The Network for which a Data Stall is being simluated.
4906 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4907 * @throws SecurityException if the caller is not the owner of the given network.
4908 * @hide
4909 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004910 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004911 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4912 android.Manifest.permission.NETWORK_STACK})
4913 public void simulateDataStall(int detectionMethod, long timestampMillis,
4914 @NonNull Network network, @NonNull PersistableBundle extras) {
4915 try {
4916 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4917 } catch (RemoteException e) {
4918 e.rethrowFromSystemServer();
4919 }
4920 }
James Mattisdcea9fb2020-10-28 21:48:54 -07004921
Daniel Bright60f02ed2020-06-15 16:10:01 -07004922 @NonNull
4923 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4924
4925 /**
4926 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4927 * receive available QoS events related to the {@link Network} and local ip + port
4928 * specified within socketInfo.
4929 * <p/>
4930 * The same {@link QosCallback} must be unregistered before being registered a second time,
4931 * otherwise {@link QosCallbackRegistrationException} is thrown.
4932 * <p/>
4933 * This API does not, in itself, require any permission if called with a network that is not
4934 * restricted. However, the underlying implementation currently only supports the IMS network,
4935 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4936 * useful, because they'd never be called back on networks that they would have access to.
4937 *
4938 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4939 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4940 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4941 * @throws RuntimeException if the app already has too many callbacks registered.
4942 *
4943 * Exceptions after the time of registration is passed through
4944 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4945 *
4946 * @param socketInfo the socket information used to match QoS events
Daniel Bright60f02ed2020-06-15 16:10:01 -07004947 * @param executor The executor on which the callback will be invoked. The provided
4948 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Brightb953a3e2021-03-10 11:51:50 -08004949 * callbacks cannot be guaranteed.onQosCallbackRegistered
4950 * @param callback receives qos events that satisfy socketInfo
Daniel Bright60f02ed2020-06-15 16:10:01 -07004951 *
4952 * @hide
4953 */
4954 @SystemApi
4955 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Brightb953a3e2021-03-10 11:51:50 -08004956 @CallbackExecutor @NonNull final Executor executor,
4957 @NonNull final QosCallback callback) {
Daniel Bright60f02ed2020-06-15 16:10:01 -07004958 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07004959 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Brightb953a3e2021-03-10 11:51:50 -08004960 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07004961
4962 try {
4963 synchronized (mQosCallbackConnections) {
4964 if (getQosCallbackConnection(callback) == null) {
4965 final QosCallbackConnection connection =
4966 new QosCallbackConnection(this, callback, executor);
4967 mQosCallbackConnections.add(connection);
4968 mService.registerQosSocketCallback(socketInfo, connection);
4969 } else {
4970 Log.e(TAG, "registerQosCallback: Callback already registered");
4971 throw new QosCallbackRegistrationException();
4972 }
4973 }
4974 } catch (final RemoteException e) {
4975 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4976
4977 // The same unregister method method is called for consistency even though nothing
4978 // will be sent to the ConnectivityService since the callback was never successfully
4979 // registered.
4980 unregisterQosCallback(callback);
4981 e.rethrowFromSystemServer();
4982 } catch (final ServiceSpecificException e) {
4983 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4984 unregisterQosCallback(callback);
4985 throw convertServiceException(e);
4986 }
4987 }
4988
4989 /**
4990 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4991 * events once unregistered and can be registered a second time.
4992 * <p/>
4993 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4994 *
4995 * @param callback the callback being unregistered
4996 *
4997 * @hide
4998 */
4999 @SystemApi
5000 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5001 Objects.requireNonNull(callback, "The callback must be non-null");
5002 try {
5003 synchronized (mQosCallbackConnections) {
5004 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5005 if (connection != null) {
5006 connection.stopReceivingMessages();
5007 mService.unregisterQosCallback(connection);
5008 mQosCallbackConnections.remove(connection);
5009 } else {
5010 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5011 }
5012 }
5013 } catch (final RemoteException e) {
5014 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5015 e.rethrowFromSystemServer();
5016 }
5017 }
5018
5019 /**
5020 * Gets the connection related to the callback.
5021 *
5022 * @param callback the callback to look up
5023 * @return the related connection
5024 */
5025 @Nullable
5026 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5027 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5028 // Checking by reference here is intentional
5029 if (connection.getCallback() == callback) {
5030 return connection;
5031 }
5032 }
5033 return null;
5034 }
Junyu Lai23568a42021-01-19 11:10:56 +00005035
5036 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08005037 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Lai23568a42021-01-19 11:10:56 +00005038 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5039 * be used to request that the system provide a network without causing the network to be
5040 * in the foreground.
5041 *
5042 * <p>This method will attempt to find the best network that matches the passed
5043 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5044 * criteria. The platform will evaluate which network is the best at its own discretion.
5045 * Throughput, latency, cost per byte, policy, user preference and other considerations
5046 * may be factored in the decision of what is considered the best network.
5047 *
5048 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5049 * matching this request, while always attempting to match the request to a better network if
5050 * possible. If a better match is found, the platform will switch this request to the now-best
5051 * network and inform the app of the newly best network by invoking
5052 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5053 * will not try to maintain any other network than the best one currently matching the request:
5054 * a network not matching any network request may be disconnected at any time.
5055 *
5056 * <p>For example, an application could use this method to obtain a connected cellular network
5057 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5058 * radio to consume additional power. Or, an application could inform the system that it wants
5059 * a network supporting sending MMSes and have the system let it know about the currently best
5060 * MMS-supporting network through the provided {@link NetworkCallback}.
5061 *
5062 * <p>The status of the request can be followed by listening to the various callbacks described
5063 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5064 * used to direct traffic to the network (although accessing some networks may be subject to
5065 * holding specific permissions). Callers will learn about the specific characteristics of the
5066 * network through
5067 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5068 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5069 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5070 * matching the request at any given time; therefore when a better network matching the request
5071 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5072 * with the new network after which no further updates are given about the previously-best
5073 * network, unless it becomes the best again at some later time. All callbacks are invoked
5074 * in order on the same thread, which by default is a thread created by the framework running
5075 * in the app.
5076 *
5077 * <p>This{@link NetworkRequest} will live until released via
5078 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5079 * which point the system may let go of the network at any time.
5080 *
5081 * <p>It is presently unsupported to request a network with mutable
5082 * {@link NetworkCapabilities} such as
5083 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5084 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5085 * as these {@code NetworkCapabilities} represent states that a particular
5086 * network may never attain, and whether a network will attain these states
5087 * is unknown prior to bringing up the network so the framework does not
5088 * know how to go about satisfying a request with these capabilities.
5089 *
5090 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5091 * number of outstanding requests to 100 per app (identified by their UID), shared with
5092 * all variants of this method, of {@link #registerNetworkCallback} as well as
5093 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5094 * Requesting a network with this method will count toward this limit. If this limit is
5095 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5096 * make sure to unregister the callbacks with
5097 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5098 *
5099 * @param request {@link NetworkRequest} describing this request.
5100 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5101 * If null, the callback is invoked on the default internal Handler.
5102 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5103 * the callback must not be shared - it uniquely specifies this request.
5104 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5105 * @throws SecurityException if missing the appropriate permissions.
5106 * @throws RuntimeException if the app already has too many callbacks registered.
5107 *
5108 * @hide
5109 */
5110 @SystemApi(client = MODULE_LIBRARIES)
5111 @SuppressLint("ExecutorRegistration")
5112 @RequiresPermission(anyOf = {
5113 android.Manifest.permission.NETWORK_SETTINGS,
5114 android.Manifest.permission.NETWORK_STACK,
5115 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5116 })
5117 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaif4bc12f2021-03-09 20:49:48 +08005118 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Lai23568a42021-01-19 11:10:56 +00005119 final NetworkCapabilities nc = request.networkCapabilities;
5120 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaif4bc12f2021-03-09 20:49:48 +08005121 TYPE_NONE, new CallbackHandler(handler));
Junyu Lai23568a42021-01-19 11:10:56 +00005122 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005123
5124 /**
James Mattis6e6fabf2021-01-10 14:24:24 -08005125 * Used by automotive devices to set the network preferences used to direct traffic at an
5126 * application level as per the given OemNetworkPreferences. An example use-case would be an
5127 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5128 * vehicle via a particular network.
5129 *
5130 * Calling this will overwrite the existing preference.
5131 *
5132 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5133 * @param executor the executor on which listener will be invoked.
5134 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5135 * communicate completion of setOemNetworkPreference(). This will only be
5136 * called once upon successful completion of setOemNetworkPreference().
5137 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5138 * @throws SecurityException if missing the appropriate permissions.
5139 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005140 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005141 */
James Mattis7a253542021-01-26 16:23:52 -08005142 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005143 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005144 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005145 @Nullable @CallbackExecutor final Executor executor,
Chalard Jeancc9ad152021-03-03 16:37:13 +09005146 @Nullable final Runnable listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08005147 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5148 if (null != listener) {
5149 Objects.requireNonNull(executor, "Executor must be non-null");
5150 }
Chalard Jeancc9ad152021-03-03 16:37:13 +09005151 final IOnCompleteListener listenerInternal = listener == null ? null :
5152 new IOnCompleteListener.Stub() {
James Mattis6e6fabf2021-01-10 14:24:24 -08005153 @Override
5154 public void onComplete() {
Chalard Jeancc9ad152021-03-03 16:37:13 +09005155 executor.execute(listener::run);
James Mattis6e6fabf2021-01-10 14:24:24 -08005156 }
5157 };
5158
5159 try {
5160 mService.setOemNetworkPreference(preference, listenerInternal);
5161 } catch (RemoteException e) {
5162 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5163 throw e.rethrowFromSystemServer();
5164 }
5165 }
lucaslin1a6095c2021-03-12 00:46:33 +08005166
Chalard Jean03433052021-02-25 17:23:40 +09005167 /**
5168 * Request that a user profile is put by default on a network matching a given preference.
5169 *
5170 * See the documentation for the individual preferences for a description of the supported
5171 * behaviors.
5172 *
5173 * @param profile the profile concerned.
5174 * @param preference the preference for this profile.
5175 * @param executor an executor to execute the listener on. Optional if listener is null.
5176 * @param listener an optional listener to listen for completion of the operation.
5177 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5178 * @throws SecurityException if missing the appropriate permissions.
5179 * @hide
5180 */
Chalard Jeancc9ad152021-03-03 16:37:13 +09005181 // This function is for establishing per-profile default networking and can only be called by
5182 // the device policy manager, running as the system server. It would make no sense to call it
5183 // on a context for a user because it does not establish a setting on behalf of a user, rather
5184 // it establishes a setting for a user on behalf of the DPM.
5185 @SuppressLint({"UserHandle"})
5186 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09005187 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5188 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5189 @ProfileNetworkPreference final int preference,
5190 @Nullable @CallbackExecutor final Executor executor,
5191 @Nullable final Runnable listener) {
5192 if (null != listener) {
5193 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5194 }
5195 final IOnCompleteListener proxy;
5196 if (null == listener) {
5197 proxy = null;
5198 } else {
5199 proxy = new IOnCompleteListener.Stub() {
5200 @Override
5201 public void onComplete() {
5202 executor.execute(listener::run);
5203 }
5204 };
5205 }
5206 try {
5207 mService.setProfileNetworkPreference(profile, preference, proxy);
5208 } catch (RemoteException e) {
5209 throw e.rethrowFromSystemServer();
5210 }
5211 }
5212
lucaslin1a6095c2021-03-12 00:46:33 +08005213 // The first network ID of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005214 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin1a6095c2021-03-12 00:46:33 +08005215 // The network ID range of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005216 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin1a6095c2021-03-12 00:46:33 +08005217
5218 /**
5219 * Get the network ID range reserved for IPSec tunnel interfaces.
5220 *
5221 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5222 * @hide
5223 */
5224 @SystemApi(client = MODULE_LIBRARIES)
5225 @NonNull
5226 public static Range<Integer> getIpSecNetIdRange() {
5227 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5228 }
lucaslin50205af2021-03-12 16:11:27 +08005229
5230 /**
5231 * Get private DNS mode from settings.
5232 *
lucaslin73c98602021-03-17 14:53:35 +08005233 * @param context The Context to query the private DNS mode from settings.
lucaslin50205af2021-03-12 16:11:27 +08005234 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5235 *
5236 * @hide
5237 */
5238 @SystemApi(client = MODULE_LIBRARIES)
5239 @NonNull
5240 @PrivateDnsMode
lucaslinacd3ded2021-03-16 17:11:14 +08005241 public static String getPrivateDnsMode(@NonNull Context context) {
5242 final ContentResolver cr = context.getContentResolver();
lucaslin50205af2021-03-12 16:11:27 +08005243 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5244 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5245 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5246 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5247 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5248 return mode;
5249 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005250}