blob: 861dbbbafe1b11cf73b049c2c709a2baef0ac1b9 [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
Sudheer Shanka457dfd52021-03-23 08:12:28 +0000832 /**
833 * Flag to indicate that an app is not subject to any restrictions that could result in its
834 * network access blocked.
835 *
836 * @hide
837 */
838 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
839 public static final int BLOCKED_REASON_NONE = 0;
840
841 /**
842 * Flag to indicate that an app is subject to Battery saver restrictions that would
843 * result in its network access being blocked.
844 *
845 * @hide
846 */
847 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
848 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
849
850 /**
851 * Flag to indicate that an app is subject to Doze restrictions that would
852 * result in its network access being blocked.
853 *
854 * @hide
855 */
856 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
857 public static final int BLOCKED_REASON_DOZE = 1 << 1;
858
859 /**
860 * Flag to indicate that an app is subject to App Standby restrictions that would
861 * result in its network access being blocked.
862 *
863 * @hide
864 */
865 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
866 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
867
868 /**
869 * Flag to indicate that an app is subject to Restricted mode restrictions that would
870 * result in its network access being blocked.
871 *
872 * @hide
873 */
874 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
875 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
876
877 /**
878 * Flag to indicate that an app is subject to Data saver restrictions that would
879 * result in its metered network access being blocked.
880 *
881 * @hide
882 */
883 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
884 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
885
886 /**
887 * Flag to indicate that an app is subject to user restrictions that would
888 * result in its metered network access being blocked.
889 *
890 * @hide
891 */
892 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
893 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
894
895 /**
896 * Flag to indicate that an app is subject to Device admin restrictions that would
897 * result in its metered network access being blocked.
898 *
899 * @hide
900 */
901 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
902 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
903
904 /**
905 * @hide
906 */
907 @Retention(RetentionPolicy.SOURCE)
908 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
909 BLOCKED_REASON_NONE,
910 BLOCKED_REASON_BATTERY_SAVER,
911 BLOCKED_REASON_DOZE,
912 BLOCKED_REASON_APP_STANDBY,
913 BLOCKED_REASON_RESTRICTED_MODE,
914 BLOCKED_METERED_REASON_DATA_SAVER,
915 BLOCKED_METERED_REASON_USER_RESTRICTED,
916 BLOCKED_METERED_REASON_ADMIN_DISABLED,
917 })
918 public @interface BlockedReason {}
919
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900920 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700921 private final IConnectivityManager mService;
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +0900922
Paul Jensen12131352014-12-10 15:12:18 -0500923 /**
924 * A kludge to facilitate static access where a Context pointer isn't available, like in the
925 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
926 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
927 * methods that take a Context argument.
928 */
929 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800930
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +0900931 private final Context mContext;
932
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +0000933 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800934
Robert Greenwalt26744a52013-02-15 10:56:35 -0800935 /**
936 * Tests if a given integer represents a valid network type.
937 * @param networkType the type to be tested
938 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen1c9f2e42015-05-06 10:42:25 -0400939 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
940 * validate a network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800941 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700942 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700943 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900944 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800945 }
946
Robert Greenwalt26744a52013-02-15 10:56:35 -0800947 /**
948 * Returns a non-localized string representing a given network type.
949 * ONLY used for debugging output.
950 * @param type the type needing naming
951 * @return a String for the given type, or a string version of the type ("87")
952 * if no name is known.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900953 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800954 * {@hide}
955 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900956 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000957 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700958 public static String getNetworkTypeName(int type) {
959 switch (type) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900960 case TYPE_NONE:
961 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700962 case TYPE_MOBILE:
963 return "MOBILE";
964 case TYPE_WIFI:
965 return "WIFI";
966 case TYPE_MOBILE_MMS:
967 return "MOBILE_MMS";
968 case TYPE_MOBILE_SUPL:
969 return "MOBILE_SUPL";
970 case TYPE_MOBILE_DUN:
971 return "MOBILE_DUN";
972 case TYPE_MOBILE_HIPRI:
973 return "MOBILE_HIPRI";
974 case TYPE_WIMAX:
975 return "WIMAX";
976 case TYPE_BLUETOOTH:
977 return "BLUETOOTH";
978 case TYPE_DUMMY:
979 return "DUMMY";
980 case TYPE_ETHERNET:
981 return "ETHERNET";
982 case TYPE_MOBILE_FOTA:
983 return "MOBILE_FOTA";
984 case TYPE_MOBILE_IMS:
985 return "MOBILE_IMS";
986 case TYPE_MOBILE_CBS:
987 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700988 case TYPE_WIFI_P2P:
989 return "WIFI_P2P";
Wink Saville70dbdcc2013-07-29 15:00:57 -0700990 case TYPE_MOBILE_IA:
991 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -0700992 case TYPE_MOBILE_EMERGENCY:
993 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -0500994 case TYPE_PROXY:
995 return "PROXY";
Erik Klineb1ff7002014-11-19 17:23:41 +0900996 case TYPE_VPN:
997 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700998 default:
999 return Integer.toString(type);
1000 }
1001 }
1002
Robert Greenwalt26744a52013-02-15 10:56:35 -08001003 /**
Aaron Huangdfba5d12020-06-27 07:18:23 +08001004 * @hide
Aaron Huangdfba5d12020-06-27 07:18:23 +08001005 */
lucaslin8c121bf2021-03-17 14:16:01 +08001006 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huangdfba5d12020-06-27 07:18:23 +08001007 public void systemReady() {
1008 try {
1009 mService.systemReady();
1010 } catch (RemoteException e) {
1011 throw e.rethrowFromSystemServer();
1012 }
1013 }
1014
1015 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001016 * Checks if a given type uses the cellular data connection.
1017 * This should be replaced in the future by a network property.
1018 * @param networkType the type to check
1019 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09001020 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001021 * {@hide}
1022 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09001023 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001024 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001025 public static boolean isNetworkTypeMobile(int networkType) {
1026 switch (networkType) {
1027 case TYPE_MOBILE:
1028 case TYPE_MOBILE_MMS:
1029 case TYPE_MOBILE_SUPL:
1030 case TYPE_MOBILE_DUN:
1031 case TYPE_MOBILE_HIPRI:
1032 case TYPE_MOBILE_FOTA:
1033 case TYPE_MOBILE_IMS:
1034 case TYPE_MOBILE_CBS:
Wink Saville70dbdcc2013-07-29 15:00:57 -07001035 case TYPE_MOBILE_IA:
Ram201d45f2014-06-26 11:03:44 -07001036 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -07001037 return true;
1038 default:
1039 return false;
1040 }
1041 }
1042
Robert Greenwalt26744a52013-02-15 10:56:35 -08001043 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001044 * Checks if the given network type is backed by a Wi-Fi radio.
1045 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001046 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001047 * @hide
1048 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09001049 @Deprecated
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001050 public static boolean isNetworkTypeWifi(int networkType) {
1051 switch (networkType) {
1052 case TYPE_WIFI:
1053 case TYPE_WIFI_P2P:
1054 return true;
1055 default:
1056 return false;
1057 }
1058 }
1059
1060 /**
Chalard Jean03433052021-02-25 17:23:40 +09001061 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1062 * Specify that the traffic for this user should by follow the default rules.
1063 * @hide
1064 */
Chalard Jean560d4032021-03-17 14:33:24 +09001065 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09001066 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1067
1068 /**
1069 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1070 * Specify that the traffic for this user should by default go on a network with
1071 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1072 * if no such network is available.
1073 * @hide
1074 */
Chalard Jean560d4032021-03-17 14:33:24 +09001075 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09001076 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1077
1078 /** @hide */
1079 @Retention(RetentionPolicy.SOURCE)
1080 @IntDef(value = {
1081 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1082 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1083 })
1084 public @interface ProfileNetworkPreference {
1085 }
1086
1087 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001088 * Specifies the preferred network type. When the device has more
1089 * than one type available the preferred network type will be used.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001090 *
1091 * @param preference the network type to prefer over all others. It is
1092 * unspecified what happens to the old preferred network in the
1093 * overall ordering.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001094 * @deprecated Functionality has been removed as it no longer makes sense,
1095 * with many more than two networks - we'd need an array to express
1096 * preference. Instead we use dynamic network properties of
1097 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001098 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001099 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001100 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001101 }
1102
Robert Greenwalt26744a52013-02-15 10:56:35 -08001103 /**
1104 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001105 *
1106 * @return an integer representing the preferred network type
1107 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001108 * @deprecated Functionality has been removed as it no longer makes sense,
1109 * with many more than two networks - we'd need an array to express
1110 * preference. Instead we use dynamic network properties of
1111 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001112 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001113 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001114 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001115 public int getNetworkPreference() {
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001116 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001117 }
1118
Scott Mainf58b7d82011-10-06 19:02:28 -07001119 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001120 * Returns details about the currently active default data network. When
1121 * connected, this network is the default route for outgoing connections.
1122 * You should always check {@link NetworkInfo#isConnected()} before initiating
1123 * network traffic. This may return {@code null} when there is no default
1124 * network.
Chalard Jean7c85ba42018-03-29 17:45:24 +09001125 * Note that if the default network is a VPN, this method will return the
1126 * NetworkInfo for one of its underlying networks instead, or null if the
1127 * VPN agent did not specify any. Apps interested in learning about VPNs
1128 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001129 *
1130 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001131 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001132 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001133 */
junyulai5c2f6262018-12-13 12:47:51 +08001134 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001135 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001136 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001137 public NetworkInfo getActiveNetworkInfo() {
1138 try {
1139 return mService.getActiveNetworkInfo();
1140 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001141 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001142 }
1143 }
1144
Robert Greenwalt26744a52013-02-15 10:56:35 -08001145 /**
Paul Jensenc2569432015-02-13 14:18:39 -05001146 * Returns a {@link Network} object corresponding to the currently active
1147 * default data network. In the event that the current active default data
1148 * network disconnects, the returned {@code Network} object will no longer
1149 * be usable. This will return {@code null} when there is no default
1150 * network.
1151 *
1152 * @return a {@link Network} object for the current default network or
1153 * {@code null} if no default network is currently active
Paul Jensenc2569432015-02-13 14:18:39 -05001154 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001155 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001156 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001157 public Network getActiveNetwork() {
1158 try {
1159 return mService.getActiveNetwork();
1160 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001161 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001162 }
1163 }
1164
1165 /**
Robin Leeda4d2e22016-03-24 12:07:00 +00001166 * Returns a {@link Network} object corresponding to the currently active
1167 * default data network for a specific UID. In the event that the default data
1168 * network disconnects, the returned {@code Network} object will no longer
1169 * be usable. This will return {@code null} when there is no default
1170 * network for the UID.
Robin Leeda4d2e22016-03-24 12:07:00 +00001171 *
1172 * @return a {@link Network} object for the current default network for the
1173 * given UID or {@code null} if no default network is currently active
1174 *
1175 * @hide
1176 */
paulhuec0a9632019-08-12 16:25:11 +08001177 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001178 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001179 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001180 return getActiveNetworkForUid(uid, false);
1181 }
1182
1183 /** {@hide} */
1184 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001185 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001186 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001187 } catch (RemoteException e) {
1188 throw e.rethrowFromSystemServer();
1189 }
1190 }
1191
1192 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001193 * Adds or removes a requirement for given UID ranges to use the VPN.
1194 *
1195 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1196 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1197 * otherwise have permission to bypass the VPN (e.g., because they have the
1198 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1199 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1200 * set to {@code false}, a previously-added restriction is removed.
1201 * <p>
1202 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1203 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1204 * remove a previously-added range, the exact range must be removed as is.
1205 * <p>
1206 * The changes are applied asynchronously and may not have been applied by the time the method
1207 * returns. Apps will be notified about any changes that apply to them via
1208 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1209 * effect.
1210 * <p>
1211 * This method should be called only by the VPN code.
1212 *
1213 * @param ranges the UID ranges to restrict
1214 * @param requireVpn whether the specified UID ranges must use a VPN
1215 *
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001216 * @hide
1217 */
1218 @RequiresPermission(anyOf = {
1219 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001220 android.Manifest.permission.NETWORK_STACK,
1221 android.Manifest.permission.NETWORK_SETTINGS})
1222 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001223 public void setRequireVpnForUids(boolean requireVpn,
1224 @NonNull Collection<Range<Integer>> ranges) {
1225 Objects.requireNonNull(ranges);
1226 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1227 // This method is not necessarily expected to be used outside the system server, so
1228 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1229 // stack process, or by tests.
1230 UidRange[] rangesArray = new UidRange[ranges.size()];
1231 int index = 0;
1232 for (Range<Integer> range : ranges) {
1233 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1234 }
1235 try {
1236 mService.setRequireVpnForUids(requireVpn, rangesArray);
1237 } catch (RemoteException e) {
1238 throw e.rethrowFromSystemServer();
1239 }
1240 }
1241
1242 /**
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001243 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1244 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1245 * but is still supported for backwards compatibility.
1246 * <p>
1247 * This type of VPN is assumed always to use the system default network, and must always declare
1248 * exactly one underlying network, which is the network that was the default when the VPN
1249 * connected.
1250 * <p>
1251 * Calling this method with {@code true} enables legacy behaviour, specifically:
1252 * <ul>
1253 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1254 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1255 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1256 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1257 * underlying the VPN.</li>
1258 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1259 * similarly replaced by the VPN network state.</li>
1260 * <li>Information on current network interfaces passed to NetworkStatsService will not
1261 * include any VPN interfaces.</li>
1262 * </ul>
1263 *
1264 * @param enabled whether legacy lockdown VPN is enabled or disabled
1265 *
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001266 * @hide
1267 */
1268 @RequiresPermission(anyOf = {
1269 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001270 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001271 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin5140e482021-03-22 11:51:27 +08001272 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001273 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1274 try {
1275 mService.setLegacyLockdownVpnEnabled(enabled);
1276 } catch (RemoteException e) {
1277 throw e.rethrowFromSystemServer();
1278 }
1279 }
1280
1281 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001282 * Returns details about the currently active default data network
1283 * for a given uid. This is for internal use only to avoid spying
1284 * other apps.
1285 *
1286 * @return a {@link NetworkInfo} object for the current default network
1287 * for the given uid or {@code null} if no default network is
1288 * available for the specified uid.
1289 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001290 * {@hide}
1291 */
paulhuec0a9632019-08-12 16:25:11 +08001292 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001293 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001294 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001295 return getActiveNetworkInfoForUid(uid, false);
1296 }
1297
1298 /** {@hide} */
1299 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001300 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001301 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001302 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001303 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001304 }
1305 }
1306
Robert Greenwalt26744a52013-02-15 10:56:35 -08001307 /**
1308 * Returns connection status information about a particular
1309 * network type.
1310 *
1311 * @param networkType integer specifying which networkType in
1312 * which you're interested.
1313 * @return a {@link NetworkInfo} object for the requested
1314 * network type or {@code null} if the type is not
Chalard Jean7c85ba42018-03-29 17:45:24 +09001315 * supported by the device. If {@code networkType} is
1316 * TYPE_VPN and a VPN is active for the calling app,
1317 * then this method will try to return one of the
1318 * underlying networks for the VPN or null if the
1319 * VPN agent didn't specify any.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001320 *
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.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001324 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001325 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001326 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001327 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001328 public NetworkInfo getNetworkInfo(int networkType) {
1329 try {
1330 return mService.getNetworkInfo(networkType);
1331 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001332 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001333 }
1334 }
1335
Robert Greenwalt26744a52013-02-15 10:56:35 -08001336 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001337 * Returns connection status information about a particular
1338 * Network.
1339 *
1340 * @param network {@link Network} specifying which network
1341 * in which you're interested.
1342 * @return a {@link NetworkInfo} object for the requested
1343 * network or {@code null} if the {@code Network}
1344 * is not valid.
junyulai5c2f6262018-12-13 12:47:51 +08001345 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001346 */
junyulai5c2f6262018-12-13 12:47:51 +08001347 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001348 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001349 @Nullable
1350 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001351 return getNetworkInfoForUid(network, Process.myUid(), false);
1352 }
1353
1354 /** {@hide} */
1355 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001356 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001357 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001358 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001359 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001360 }
1361 }
1362
1363 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001364 * Returns connection status information about all network
1365 * types supported by the device.
1366 *
1367 * @return an array of {@link NetworkInfo} objects. Check each
1368 * {@link NetworkInfo#getType} for which type each applies.
1369 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001370 * @deprecated This method does not support multiple connected networks
1371 * of the same type. Use {@link #getAllNetworks} and
1372 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001373 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001374 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001375 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001376 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001377 public NetworkInfo[] getAllNetworkInfo() {
1378 try {
1379 return mService.getAllNetworkInfo();
1380 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001381 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001382 }
1383 }
1384
Robert Greenwalt26744a52013-02-15 10:56:35 -08001385 /**
junyulai57840802021-03-03 12:09:05 +08001386 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1387 * connected.
1388 * @hide
1389 */
1390 @SystemApi(client = MODULE_LIBRARIES)
1391 @RequiresPermission(anyOf = {
1392 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1393 android.Manifest.permission.NETWORK_STACK,
1394 android.Manifest.permission.NETWORK_SETTINGS})
1395 @NonNull
1396 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1397 try {
1398 return mService.getAllNetworkStateSnapshot();
1399 } catch (RemoteException e) {
1400 throw e.rethrowFromSystemServer();
1401 }
1402 }
1403
1404 /**
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001405 * Returns the {@link Network} object currently serving a given type, or
1406 * null if the given type is not connected.
1407 *
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001408 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04001409 * @deprecated This method does not support multiple connected networks
1410 * of the same type. Use {@link #getAllNetworks} and
1411 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001412 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001413 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001414 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001415 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001416 public Network getNetworkForType(int networkType) {
1417 try {
1418 return mService.getNetworkForType(networkType);
1419 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001420 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001421 }
1422 }
1423
1424 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001425 * Returns an array of all {@link Network} currently tracked by the
1426 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001427 *
1428 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001429 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001430 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001431 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001432 public Network[] getAllNetworks() {
1433 try {
1434 return mService.getAllNetworks();
1435 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001436 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001437 }
1438 }
1439
1440 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001441 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001442 * the Networks that applications run by the given user will use by default.
1443 * @hide
1444 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001445 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001446 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1447 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001448 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001449 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001450 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001451 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001452 }
1453 }
1454
1455 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001456 * Returns the IP information for the current default network.
1457 *
1458 * @return a {@link LinkProperties} object describing the IP info
1459 * for the current default network, or {@code null} if there
1460 * is no current default network.
1461 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001462 * {@hide}
Chalard Jeancc47b522019-01-11 16:47:53 +09001463 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1464 * value of {@link #getActiveNetwork()} instead. In particular,
1465 * this method will return non-null LinkProperties even if the
1466 * app is blocked by policy from using this network.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001467 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001468 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-01-11 16:47:53 +09001469 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001470 public LinkProperties getActiveLinkProperties() {
1471 try {
1472 return mService.getActiveLinkProperties();
1473 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001474 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001475 }
1476 }
1477
Robert Greenwalt26744a52013-02-15 10:56:35 -08001478 /**
1479 * Returns the IP information for a given network type.
1480 *
1481 * @param networkType the network type of interest.
1482 * @return a {@link LinkProperties} object describing the IP info
1483 * for the given networkType, or {@code null} if there is
1484 * no current default network.
1485 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001486 * {@hide}
Paul Jensena8e6dc62015-03-18 12:23:02 -04001487 * @deprecated This method does not support multiple connected networks
1488 * of the same type. Use {@link #getAllNetworks},
1489 * {@link #getNetworkInfo(android.net.Network)}, and
1490 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001491 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001492 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001493 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001494 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001495 public LinkProperties getLinkProperties(int networkType) {
1496 try {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001497 return mService.getLinkPropertiesForType(networkType);
1498 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001499 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001500 }
1501 }
1502
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001503 /**
1504 * Get the {@link LinkProperties} for the given {@link Network}. This
1505 * will return {@code null} if the network is unknown.
1506 *
1507 * @param network The {@link Network} object identifying the network in question.
1508 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001509 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001510 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001511 @Nullable
1512 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001513 try {
1514 return mService.getLinkProperties(network);
1515 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001516 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001517 }
1518 }
1519
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001520 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001521 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001522 * will return {@code null} if the network is unknown.
1523 *
Roshan Pius7992afd2020-12-22 15:10:42 -08001524 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1525 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1526 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1527 * this location sensitive information (subject to app's location permissions) will be
1528 * noted by system. To include any location sensitive data in {@link TransportInfo},
1529 * use a {@link NetworkCallback} with
1530 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1531 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001532 * @param network The {@link Network} object identifying the network in question.
Roshan Pius7992afd2020-12-22 15:10:42 -08001533 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001534 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001535 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001536 @Nullable
1537 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001538 try {
Roshan Piusc97d8062020-12-17 14:53:09 -08001539 return mService.getNetworkCapabilities(
1540 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001541 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001542 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001543 }
1544 }
1545
Robert Greenwalt26744a52013-02-15 10:56:35 -08001546 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001547 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001548 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1549 * portal is present.
1550 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1551 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1552 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001553 * The system network validation may be using different strategies to detect captive portals,
1554 * so this method does not necessarily return a URL used by the system. It only returns a URL
1555 * that may be relevant for other components trying to detect captive portals.
paulhuec0a9632019-08-12 16:25:11 +08001556 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001557 * @hide
paulhuec0a9632019-08-12 16:25:11 +08001558 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1559 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001560 */
paulhuec0a9632019-08-12 16:25:11 +08001561 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001562 @SystemApi
paulhuec0a9632019-08-12 16:25:11 +08001563 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001564 public String getCaptivePortalServerUrl() {
1565 try {
1566 return mService.getCaptivePortalServerUrl();
1567 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001568 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001569 }
1570 }
1571
1572 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001573 * Tells the underlying networking system that the caller wants to
1574 * begin using the named feature. The interpretation of {@code feature}
1575 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001576 *
1577 * <p>This method requires the caller to hold either the
1578 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1579 * or the ability to modify system settings as determined by
1580 * {@link android.provider.Settings.System#canWrite}.</p>
1581 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001582 * @param networkType specifies which network the request pertains to
1583 * @param feature the name of the feature to be used
1584 * @return an integer value representing the outcome of the request.
1585 * The interpretation of this value is specific to each networking
1586 * implementation+feature combination, except that the value {@code -1}
1587 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001588 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001589 * @deprecated Deprecated in favor of the cleaner
1590 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001591 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001592 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001593 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001594 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001595 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001596 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001597 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001598 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1599 if (netCap == null) {
1600 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1601 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001602 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001603 }
1604
1605 NetworkRequest request = null;
1606 synchronized (sLegacyRequests) {
1607 LegacyRequest l = sLegacyRequests.get(netCap);
1608 if (l != null) {
1609 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1610 renewRequestLocked(l);
1611 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001612 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001613 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001614 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001615 }
1616 }
1617
1618 request = requestNetworkForFeatureLocked(netCap);
1619 }
1620 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001621 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001622 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001623 } else {
1624 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001625 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001626 }
1627 }
1628
1629 /**
1630 * Tells the underlying networking system that the caller is finished
1631 * using the named feature. The interpretation of {@code feature}
1632 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001633 *
1634 * <p>This method requires the caller to hold either the
1635 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1636 * or the ability to modify system settings as determined by
1637 * {@link android.provider.Settings.System#canWrite}.</p>
1638 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001639 * @param networkType specifies which network the request pertains to
1640 * @param feature the name of the feature that is no longer needed
1641 * @return an integer value representing the outcome of the request.
1642 * The interpretation of this value is specific to each networking
1643 * implementation+feature combination, except that the value {@code -1}
1644 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001645 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001646 * @deprecated Deprecated in favor of the cleaner
1647 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001648 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001649 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001650 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001651 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001652 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001653 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001654 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001655 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1656 if (netCap == null) {
1657 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1658 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001659 return -1;
1660 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001661
Paul Jensen034dea32014-12-17 10:39:34 -05001662 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001663 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001664 }
1665 return 1;
1666 }
1667
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001668 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001669 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1670 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001671 switch (feature) {
1672 case "enableCBS":
1673 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1674 case "enableDUN":
1675 case "enableDUNAlways":
1676 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1677 case "enableFOTA":
1678 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1679 case "enableHIPRI":
1680 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1681 case "enableIMS":
1682 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1683 case "enableMMS":
1684 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1685 case "enableSUPL":
1686 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1687 default:
1688 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001689 }
Erik Kline50068e52017-01-26 18:08:28 +09001690 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1691 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001692 }
1693 return null;
1694 }
1695
Robert Greenwalt5a367872014-06-02 15:32:02 -07001696 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001697 if (netCap == null) return TYPE_NONE;
1698 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1699 return TYPE_MOBILE_CBS;
1700 }
1701 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1702 return TYPE_MOBILE_IMS;
1703 }
1704 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1705 return TYPE_MOBILE_FOTA;
1706 }
1707 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1708 return TYPE_MOBILE_DUN;
1709 }
1710 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1711 return TYPE_MOBILE_SUPL;
1712 }
1713 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1714 return TYPE_MOBILE_MMS;
1715 }
1716 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1717 return TYPE_MOBILE_HIPRI;
1718 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001719 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1720 return TYPE_WIFI_P2P;
1721 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001722 return TYPE_NONE;
1723 }
1724
1725 private static class LegacyRequest {
1726 NetworkCapabilities networkCapabilities;
1727 NetworkRequest networkRequest;
1728 int expireSequenceNumber;
1729 Network currentNetwork;
1730 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001731
1732 private void clearDnsBinding() {
1733 if (currentNetwork != null) {
1734 currentNetwork = null;
1735 setProcessDefaultNetworkForHostResolution(null);
1736 }
1737 }
1738
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001739 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001740 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001741 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001742 currentNetwork = network;
1743 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001744 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001745 }
1746 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001747 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001748 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001749 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1750 }
1751 };
1752 }
1753
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001754 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001755 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1756 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001757
1758 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1759 synchronized (sLegacyRequests) {
1760 LegacyRequest l = sLegacyRequests.get(netCap);
1761 if (l != null) return l.networkRequest;
1762 }
1763 return null;
1764 }
1765
1766 private void renewRequestLocked(LegacyRequest l) {
1767 l.expireSequenceNumber++;
1768 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1769 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1770 }
1771
1772 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1773 int ourSeqNum = -1;
1774 synchronized (sLegacyRequests) {
1775 LegacyRequest l = sLegacyRequests.get(netCap);
1776 if (l == null) return;
1777 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001778 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001779 }
1780 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1781 }
1782
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001783 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001784 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1785 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001786 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001787 try {
1788 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001789 } catch (RemoteException e) {
1790 throw e.rethrowFromSystemServer();
1791 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001792 LegacyRequest l = new LegacyRequest();
1793 l.networkCapabilities = netCap;
1794 l.delay = delay;
1795 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001796 l.networkRequest = sendRequestForNetwork(
1797 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001798 if (l.networkRequest == null) return null;
1799 sLegacyRequests.put(netCap, l);
1800 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1801 return l.networkRequest;
1802 }
1803
1804 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1805 if (delay >= 0) {
1806 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001807 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001808 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1809 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001810 }
1811 }
1812
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001813 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001814 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1815 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001816 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001817 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001818 }
Paul Jensen034dea32014-12-17 10:39:34 -05001819 if (l == null) return false;
1820 unregisterNetworkCallback(l.networkCallback);
1821 l.clearDnsBinding();
1822 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001823 }
1824
Erik Kline50068e52017-01-26 18:08:28 +09001825 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1826 static {
1827 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1828 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1829 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1830 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1831 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1832 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1833 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1834 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1835 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1836 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1837 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1838 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1839 }
1840
1841 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1842 static {
1843 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1844 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1845 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1846 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1847 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1848 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1849 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1850 }
1851
1852 /**
1853 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1854 * instance suitable for registering a request or callback. Throws an
1855 * IllegalArgumentException if no mapping from the legacy type to
1856 * NetworkCapabilities is known.
1857 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001858 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1859 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001860 * @hide
1861 */
1862 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1863 final NetworkCapabilities nc = new NetworkCapabilities();
1864
1865 // Map from type to transports.
1866 final int NOT_FOUND = -1;
1867 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001868 if (transport == NOT_FOUND) {
1869 throw new IllegalArgumentException("unknown legacy type: " + type);
1870 }
Erik Kline50068e52017-01-26 18:08:28 +09001871 nc.addTransportType(transport);
1872
1873 // Map from type to capabilities.
1874 nc.addCapability(sLegacyTypeToCapability.get(
1875 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1876 nc.maybeMarkCapabilitiesRestricted();
1877 return nc;
1878 }
1879
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001880 /** @hide */
1881 public static class PacketKeepaliveCallback {
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001882 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayevfc03a992019-11-15 19:12:49 +00001883 public PacketKeepaliveCallback() {
1884 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001885 /** The requested keepalive was successfully started. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001886 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001887 public void onStarted() {}
1888 /** The keepalive was successfully stopped. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001889 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001890 public void onStopped() {}
1891 /** An error occurred. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001892 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001893 public void onError(int error) {}
1894 }
1895
1896 /**
1897 * Allows applications to request that the system periodically send specific packets on their
1898 * behalf, using hardware offload to save battery power.
1899 *
1900 * To request that the system send keepalives, call one of the methods that return a
1901 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1902 * passing in a non-null callback. If the callback is successfully started, the callback's
1903 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1904 * specifying one of the {@code ERROR_*} constants in this class.
1905 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001906 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1907 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1908 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001909 *
junyulaia86defc2018-12-27 17:25:29 +08001910 * @deprecated Use {@link SocketKeepalive} instead.
1911 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001912 * @hide
1913 */
1914 public class PacketKeepalive {
1915
1916 private static final String TAG = "PacketKeepalive";
1917
1918 /** @hide */
1919 public static final int SUCCESS = 0;
1920
1921 /** @hide */
1922 public static final int NO_KEEPALIVE = -1;
1923
1924 /** @hide */
1925 public static final int BINDER_DIED = -10;
1926
1927 /** The specified {@code Network} is not connected. */
1928 public static final int ERROR_INVALID_NETWORK = -20;
1929 /** The specified IP addresses are invalid. For example, the specified source IP address is
1930 * not configured on the specified {@code Network}. */
1931 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1932 /** The requested port is invalid. */
1933 public static final int ERROR_INVALID_PORT = -22;
1934 /** The packet length is invalid (e.g., too long). */
1935 public static final int ERROR_INVALID_LENGTH = -23;
1936 /** The packet transmission interval is invalid (e.g., too short). */
1937 public static final int ERROR_INVALID_INTERVAL = -24;
1938
1939 /** The hardware does not support this request. */
1940 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001941 /** The hardware returned an error. */
1942 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001943
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001944 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001945 public static final int NATT_PORT = 4500;
1946
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001947 /** The minimum interval in seconds between keepalive packet transmissions */
1948 public static final int MIN_INTERVAL = 10;
1949
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001950 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001951 private final ISocketKeepaliveCallback mCallback;
1952 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001953
1954 private volatile Integer mSlot;
1955
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001956 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001957 public void stop() {
1958 try {
junyulai9f872232019-01-16 20:23:34 +08001959 mExecutor.execute(() -> {
1960 try {
1961 if (mSlot != null) {
1962 mService.stopKeepalive(mNetwork, mSlot);
1963 }
1964 } catch (RemoteException e) {
1965 Log.e(TAG, "Error stopping packet keepalive: ", e);
1966 throw e.rethrowFromSystemServer();
1967 }
1968 });
1969 } catch (RejectedExecutionException e) {
1970 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001971 }
1972 }
1973
1974 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001975 Objects.requireNonNull(network, "network cannot be null");
1976 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001977 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08001978 mExecutor = Executors.newSingleThreadExecutor();
1979 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001980 @Override
junyulai9f872232019-01-16 20:23:34 +08001981 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08001982 final long token = Binder.clearCallingIdentity();
1983 try {
1984 mExecutor.execute(() -> {
1985 mSlot = slot;
1986 callback.onStarted();
1987 });
1988 } finally {
1989 Binder.restoreCallingIdentity(token);
1990 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001991 }
junyulai9f872232019-01-16 20:23:34 +08001992
1993 @Override
1994 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08001995 final long token = Binder.clearCallingIdentity();
1996 try {
1997 mExecutor.execute(() -> {
1998 mSlot = null;
1999 callback.onStopped();
2000 });
2001 } finally {
2002 Binder.restoreCallingIdentity(token);
2003 }
junyulai9f872232019-01-16 20:23:34 +08002004 mExecutor.shutdown();
2005 }
2006
2007 @Override
2008 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08002009 final long token = Binder.clearCallingIdentity();
2010 try {
2011 mExecutor.execute(() -> {
2012 mSlot = null;
2013 callback.onError(error);
2014 });
2015 } finally {
2016 Binder.restoreCallingIdentity(token);
2017 }
junyulai9f872232019-01-16 20:23:34 +08002018 mExecutor.shutdown();
2019 }
2020
2021 @Override
2022 public void onDataReceived() {
2023 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2024 // this callback when data is received.
2025 }
2026 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002027 }
2028 }
2029
2030 /**
2031 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2032 *
junyulaia86defc2018-12-27 17:25:29 +08002033 * @deprecated Use {@link #createSocketKeepalive} instead.
2034 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002035 * @hide
2036 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002037 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002038 public PacketKeepalive startNattKeepalive(
2039 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2040 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2041 final PacketKeepalive k = new PacketKeepalive(network, callback);
2042 try {
junyulai9f872232019-01-16 20:23:34 +08002043 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002044 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2045 } catch (RemoteException e) {
2046 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08002047 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002048 }
2049 return k;
2050 }
2051
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002052 // Construct an invalid fd.
2053 private ParcelFileDescriptor createInvalidFd() {
2054 final int invalidFd = -1;
2055 return ParcelFileDescriptor.adoptFd(invalidFd);
2056 }
2057
The Android Open Source Project28527d22009-03-03 19:31:44 -08002058 /**
junyulaia86defc2018-12-27 17:25:29 +08002059 * Request that keepalives be started on a IPsec NAT-T socket.
2060 *
2061 * @param network The {@link Network} the socket is on.
2062 * @param socket The socket that needs to be kept alive.
2063 * @param source The source address of the {@link UdpEncapsulationSocket}.
2064 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2065 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2066 * must run callback sequentially, otherwise the order of callbacks cannot be
2067 * guaranteed.
2068 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2069 * changes. Must be extended by applications that use this API.
2070 *
junyulaic7ea1242019-01-08 20:04:33 +08002071 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2072 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08002073 **/
junyulai61143782019-03-04 22:45:36 +08002074 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08002075 @NonNull UdpEncapsulationSocket socket,
2076 @NonNull InetAddress source,
2077 @NonNull InetAddress destination,
2078 @NonNull @CallbackExecutor Executor executor,
2079 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002080 ParcelFileDescriptor dup;
2081 try {
junyulaic4fb2482019-03-27 11:00:37 +08002082 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2083 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08002084 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2085 } catch (IOException ignored) {
2086 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2087 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002088 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002089 }
2090 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2091 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08002092 }
2093
2094 /**
2095 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2096 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2097 *
2098 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08002099 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2100 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2101 * from that port.
junyulai48a59382019-01-15 11:32:44 +08002102 * @param source The source address of the {@link UdpEncapsulationSocket}.
2103 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2104 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2105 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2106 * must run callback sequentially, otherwise the order of callbacks cannot be
2107 * guaranteed.
2108 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2109 * changes. Must be extended by applications that use this API.
2110 *
junyulaic7ea1242019-01-08 20:04:33 +08002111 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2112 * given socket.
junyulai48a59382019-01-15 11:32:44 +08002113 * @hide
2114 */
2115 @SystemApi
2116 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002117 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2118 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08002119 @NonNull InetAddress source,
2120 @NonNull InetAddress destination,
2121 @NonNull @CallbackExecutor Executor executor,
2122 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002123 ParcelFileDescriptor dup;
2124 try {
junyulaic4fb2482019-03-27 11:00:37 +08002125 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08002126 dup = pfd.dup();
2127 } catch (IOException ignored) {
2128 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2129 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002130 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002131 }
2132 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VAN642d6ab2021-03-11 10:56:49 +00002133 -1 /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08002134 }
2135
2136 /**
junyulaic7ea1242019-01-08 20:04:33 +08002137 * Request that keepalives be started on a TCP socket.
2138 * The socket must be established.
2139 *
2140 * @param network The {@link Network} the socket is on.
2141 * @param socket The socket that needs to be kept alive.
2142 * @param executor The executor on which callback will be invoked. This implementation assumes
2143 * the provided {@link Executor} runs the callbacks in sequence with no
2144 * concurrency. Failing this, no guarantee of correctness can be made. It is
2145 * the responsibility of the caller to ensure the executor provides this
2146 * guarantee. A simple way of creating such an executor is with the standard
2147 * tool {@code Executors.newSingleThreadExecutor}.
2148 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2149 * changes. Must be extended by applications that use this API.
2150 *
2151 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2152 * given socket.
2153 * @hide
2154 */
2155 @SystemApi
2156 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002157 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002158 @NonNull Socket socket,
2159 @NonNull Executor executor,
2160 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002161 ParcelFileDescriptor dup;
2162 try {
2163 dup = ParcelFileDescriptor.fromSocket(socket);
2164 } catch (UncheckedIOException ignored) {
2165 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2166 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002167 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002168 }
2169 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002170 }
2171
2172 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002173 * Ensure that a network route exists to deliver traffic to the specified
2174 * host via the specified network interface. An attempt to add a route that
2175 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002176 *
2177 * <p>This method requires the caller to hold either the
2178 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2179 * or the ability to modify system settings as determined by
2180 * {@link android.provider.Settings.System#canWrite}.</p>
2181 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002182 * @param networkType the type of the network over which traffic to the specified
2183 * host is to be routed
2184 * @param hostAddress the IP address of the host to which the route is desired
2185 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002186 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002187 * @deprecated Deprecated in favor of the
2188 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2189 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002190 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002191 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002192 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002193 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002194 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002195 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002196 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002197 }
2198
2199 /**
2200 * Ensure that a network route exists to deliver traffic to the specified
2201 * host via the specified network interface. An attempt to add a route that
2202 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002203 *
2204 * <p>This method requires the caller to hold either the
2205 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2206 * or the ability to modify system settings as determined by
2207 * {@link android.provider.Settings.System#canWrite}.</p>
2208 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002209 * @param networkType the type of the network over which traffic to the specified
2210 * host is to be routed
2211 * @param hostAddress the IP address of the host to which the route is desired
2212 * @return {@code true} on success, {@code false} on failure
2213 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002214 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002215 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002216 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002217 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002218 @UnsupportedAppUsage
lucaslin5140e482021-03-22 11:51:27 +08002219 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002220 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002221 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002222 try {
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002223 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2224 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002225 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002226 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002227 }
2228 }
2229
2230 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002231 * @return the context's attribution tag
2232 */
2233 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2234 private @Nullable String getAttributionTag() {
2235 return mContext.getAttributionTag();
2236 }
2237
2238 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002239 * Returns the value of the setting for background data usage. If false,
2240 * applications should not use the network if the application is not in the
2241 * foreground. Developers should respect this setting, and check the value
2242 * of this before performing any background data operations.
2243 * <p>
2244 * All applications that have background services that use the network
2245 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002246 * <p>
Scott Main50589142011-10-06 18:32:43 -07002247 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002248 * background data depends on several combined factors, and this method will
2249 * always return {@code true}. Instead, when background data is unavailable,
2250 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002251 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002252 * @return Whether background data usage is allowed.
2253 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002254 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002255 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002256 // assume that background data is allowed; final authority is
2257 // NetworkInfo which may be blocked.
2258 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002259 }
2260
2261 /**
2262 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002263 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002264 * @param allowBackgroundData Whether an application should use data while
2265 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002266 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002267 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2268 * @see #getBackgroundDataSetting()
2269 * @hide
2270 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002271 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002272 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002273 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002274 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002275 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002276
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002277 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002278 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002279 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002280 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002281 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002282 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002283 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002284 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2285 if (tm != null) {
2286 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2287 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2288 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2289 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2290 + " retVal=" + retVal);
2291 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002292 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002293 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002294 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002295 }
2296
The Android Open Source Project28527d22009-03-03 19:31:44 -08002297 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002298 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002299 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002300 */
2301 public interface OnNetworkActiveListener {
2302 /**
2303 * Called on the main thread of the process to report that the current data network
2304 * has become active, and it is now a good time to perform any pending network
2305 * operations. Note that this listener only tells you when the network becomes
2306 * active; if at any other time you want to know whether it is active (and thus okay
2307 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002308 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002309 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002310 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002311 }
2312
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002313 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002314 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002315
2316 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002317 * Start listening to reports when the system's default data network is active, meaning it is
2318 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2319 * to determine the current state of the system's default network after registering the
2320 * listener.
2321 * <p>
2322 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002323 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002324 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002325 *
2326 * @param l The listener to be told when the network is active.
2327 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002328 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002329 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2330 @Override
2331 public void onNetworkActive() throws RemoteException {
2332 l.onNetworkActive();
2333 }
2334 };
2335
2336 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002337 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002338 mNetworkActivityListeners.put(l, rl);
2339 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002340 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002341 }
2342 }
2343
2344 /**
2345 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002346 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002347 *
2348 * @param l Previously registered listener.
2349 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002350 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002351 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002352 if (rl == null) {
2353 throw new IllegalArgumentException("Listener was not registered.");
2354 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002355 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002356 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002357 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002358 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002359 }
2360 }
2361
2362 /**
2363 * Return whether the data network is currently active. An active network means that
2364 * it is currently in a high power state for performing data transmission. On some
2365 * types of networks, it may be expensive to move and stay in such a state, so it is
2366 * more power efficient to batch network traffic together when the radio is already in
2367 * this state. This method tells you whether right now is currently a good time to
2368 * initiate network traffic, as the network is already active.
2369 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002370 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002371 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002372 return mService.isDefaultNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002373 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002374 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002375 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002376 }
2377
2378 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002379 * {@hide}
2380 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002381 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002382 mContext = Objects.requireNonNull(context, "missing context");
2383 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002384 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002385 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002386 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002387
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002388 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002389 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002390 public static ConnectivityManager from(Context context) {
2391 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2392 }
2393
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002394 /** @hide */
2395 public NetworkRequest getDefaultRequest() {
2396 try {
2397 // This is not racy as the default request is final in ConnectivityService.
2398 return mService.getDefaultRequest();
2399 } catch (RemoteException e) {
2400 throw e.rethrowFromSystemServer();
2401 }
2402 }
2403
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002404 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002405 * Check if the package is a allowed to write settings. This also accounts that such an access
2406 * happened.
2407 *
2408 * @return {@code true} iff the package is allowed to write settings.
2409 */
2410 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2411 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2412 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2413 boolean throwException) {
2414 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2415 callingAttributionTag, throwException);
2416 }
2417
2418 /**
Paul Jensen12131352014-12-10 15:12:18 -05002419 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2420 * situations where a Context pointer is unavailable.
2421 * @hide
2422 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002423 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002424 static ConnectivityManager getInstanceOrNull() {
2425 return sInstance;
2426 }
2427
2428 /**
2429 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2430 * situations where a Context pointer is unavailable.
2431 * @hide
2432 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002433 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002434 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002435 private static ConnectivityManager getInstance() {
2436 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002437 throw new IllegalStateException("No ConnectivityManager yet constructed");
2438 }
Paul Jensen895c3942015-03-10 10:54:12 -04002439 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002440 }
2441
2442 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002443 * Get the set of tetherable, available interfaces. This list is limited by
2444 * device configuration and current interface existence.
2445 *
2446 * @return an array of 0 or more Strings of tetherable interface names.
2447 *
markchien75721e42020-01-21 13:11:06 +08002448 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002449 * {@hide}
2450 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002451 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002452 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002453 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002454 public String[] getTetherableIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002455 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002456 }
2457
2458 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002459 * Get the set of tethered interfaces.
2460 *
2461 * @return an array of 0 or more String of currently tethered interface names.
2462 *
markchien75721e42020-01-21 13:11:06 +08002463 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002464 * {@hide}
2465 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002466 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002467 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002468 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002469 public String[] getTetheredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002470 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002471 }
2472
2473 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002474 * Get the set of interface names which attempted to tether but
2475 * failed. Re-attempting to tether may cause them to reset to the Tethered
2476 * state. Alternatively, causing the interface to be destroyed and recreated
2477 * may cause them to reset to the available state.
2478 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2479 * information on the cause of the errors.
2480 *
2481 * @return an array of 0 or more String indicating the interface names
2482 * which failed to tether.
2483 *
markchien75721e42020-01-21 13:11:06 +08002484 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002485 * {@hide}
2486 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002487 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002488 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002489 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002490 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002491 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002492 }
2493
2494 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002495 * Get the set of tethered dhcp ranges.
2496 *
markchien9e046242020-02-06 19:23:26 +08002497 * @deprecated This method is not supported.
2498 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002499 * {@hide}
2500 */
paulhuec0a9632019-08-12 16:25:11 +08002501 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien75721e42020-01-21 13:11:06 +08002502 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002503 public String[] getTetheredDhcpRanges() {
markchien9e046242020-02-06 19:23:26 +08002504 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002505 }
2506
2507 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002508 * Attempt to tether the named interface. This will setup a dhcp server
2509 * on the interface, forward and NAT IP packets and forward DNS requests
2510 * to the best active upstream network interface. Note that if no upstream
2511 * IP network interface is available, dhcp will still run and traffic will be
2512 * allowed between the tethered devices and this device, though upstream net
2513 * access will of course fail until an upstream network interface becomes
2514 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002515 *
2516 * <p>This method requires the caller to hold either the
2517 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2518 * or the ability to modify system settings as determined by
2519 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002520 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002521 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2522 * and WifiStateMachine which need direct access. All other clients should use
2523 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2524 * logic.</p>
2525 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002526 * @param iface the interface name to tether.
2527 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002528 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002529 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002530 * {@hide}
2531 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002532 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien10ddd022020-01-20 19:31:56 +08002533 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002534 public int tether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002535 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002536 }
2537
2538 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002539 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002540 *
2541 * <p>This method requires the caller to hold either the
2542 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2543 * or the ability to modify system settings as determined by
2544 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002545 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002546 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2547 * and WifiStateMachine which need direct access. All other clients should use
2548 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2549 * logic.</p>
2550 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002551 * @param iface the interface name to untether.
2552 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2553 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002554 * {@hide}
2555 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002556 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002557 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002558 public int untether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002559 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002560 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002561
2562 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002563 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002564 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002565 * due to device configuration.
2566 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002567 * <p>If this app does not have permission to use this API, it will always
2568 * return false rather than throw an exception.</p>
2569 *
2570 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2571 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2572 *
2573 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2574 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2575 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002576 * @return a boolean - {@code true} indicating Tethering is supported.
2577 *
markchien75721e42020-01-21 13:11:06 +08002578 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002579 * {@hide}
2580 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002581 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002582 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2583 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002584 public boolean isTetheringSupported() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002585 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002586 }
2587
2588 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002589 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien10ddd022020-01-20 19:31:56 +08002590 *
2591 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002592 * @hide
2593 */
2594 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002595 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002596 public static abstract class OnStartTetheringCallback {
2597 /**
2598 * Called when tethering has been successfully started.
2599 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002600 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002601
2602 /**
2603 * Called when starting tethering failed.
2604 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002605 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002606 }
2607
2608 /**
2609 * Convenient overload for
2610 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2611 * handler to run on the current thread's {@link Looper}.
markchien10ddd022020-01-20 19:31:56 +08002612 *
2613 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002614 * @hide
2615 */
2616 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002617 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002618 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002619 public void startTethering(int type, boolean showProvisioningUi,
2620 final OnStartTetheringCallback callback) {
2621 startTethering(type, showProvisioningUi, callback, null);
2622 }
2623
2624 /**
2625 * Runs tether provisioning for the given type if needed and then starts tethering if
2626 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2627 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2628 * schedules tether provisioning re-checks if appropriate.
2629 *
2630 * @param type The type of tethering to start. Must be one of
2631 * {@link ConnectivityManager.TETHERING_WIFI},
2632 * {@link ConnectivityManager.TETHERING_USB}, or
2633 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2634 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2635 * is one. This should be true the first time this function is called and also any time
2636 * the user can see this UI. It gives users information from their carrier about the
2637 * check failing and how they can sign up for tethering if possible.
2638 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2639 * of the result of trying to tether.
2640 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien10ddd022020-01-20 19:31:56 +08002641 *
2642 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002643 * @hide
2644 */
2645 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002646 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002647 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002648 public void startTethering(int type, boolean showProvisioningUi,
2649 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002650 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002651
markchien10ddd022020-01-20 19:31:56 +08002652 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002653 @Override
markchien10ddd022020-01-20 19:31:56 +08002654 public void execute(Runnable command) {
2655 if (handler == null) {
2656 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002657 } else {
markchien10ddd022020-01-20 19:31:56 +08002658 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002659 }
2660 }
2661 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002662
markchien10ddd022020-01-20 19:31:56 +08002663 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2664 @Override
2665 public void onTetheringStarted() {
2666 callback.onTetheringStarted();
2667 }
2668
2669 @Override
markchien68b67842020-03-19 13:37:43 +08002670 public void onTetheringFailed(final int error) {
markchien10ddd022020-01-20 19:31:56 +08002671 callback.onTetheringFailed();
2672 }
2673 };
2674
2675 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien68b67842020-03-19 13:37:43 +08002676 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien10ddd022020-01-20 19:31:56 +08002677
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002678 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002679 }
2680
2681 /**
2682 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2683 * applicable.
2684 *
2685 * @param type The type of tethering to stop. Must be one of
2686 * {@link ConnectivityManager.TETHERING_WIFI},
2687 * {@link ConnectivityManager.TETHERING_USB}, or
2688 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien75721e42020-01-21 13:11:06 +08002689 *
2690 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002691 * @hide
2692 */
2693 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002694 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002695 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002696 public void stopTethering(int type) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002697 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002698 }
2699
2700 /**
markchiena005c992019-02-27 14:56:11 +08002701 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2702 * upstream status.
2703 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002704 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien75721e42020-01-21 13:11:06 +08002705 * @hide
markchiena005c992019-02-27 14:56:11 +08002706 */
2707 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002708 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002709 public abstract static class OnTetheringEventCallback {
2710
2711 /**
2712 * Called when tethering upstream changed. This can be called multiple times and can be
2713 * called any time.
2714 *
2715 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2716 * have any upstream.
2717 */
2718 public void onUpstreamChanged(@Nullable Network network) {}
2719 }
2720
markchien75721e42020-01-21 13:11:06 +08002721 @GuardedBy("mTetheringEventCallbacks")
2722 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2723 mTetheringEventCallbacks = new ArrayMap<>();
2724
markchiena005c992019-02-27 14:56:11 +08002725 /**
2726 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002727 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002728 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2729 * with a null argument. The same callback object cannot be registered twice.
2730 *
2731 * @param executor the executor on which callback will be invoked.
2732 * @param callback the callback to be called when tethering has change events.
markchien75721e42020-01-21 13:11:06 +08002733 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002734 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002735 * @hide
2736 */
2737 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002738 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002739 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2740 public void registerTetheringEventCallback(
2741 @NonNull @CallbackExecutor Executor executor,
2742 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002743 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchiena005c992019-02-27 14:56:11 +08002744
markchien75721e42020-01-21 13:11:06 +08002745 final TetheringEventCallback tetherCallback =
2746 new TetheringEventCallback() {
2747 @Override
2748 public void onUpstreamChanged(@Nullable Network network) {
2749 callback.onUpstreamChanged(network);
2750 }
2751 };
2752
2753 synchronized (mTetheringEventCallbacks) {
2754 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002755 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002756 }
markchiena005c992019-02-27 14:56:11 +08002757 }
2758
2759 /**
2760 * Remove tethering event callback previously registered with
2761 * {@link #registerTetheringEventCallback}.
2762 *
2763 * @param callback previously registered callback.
markchien75721e42020-01-21 13:11:06 +08002764 *
2765 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002766 * @hide
2767 */
2768 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002769 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002770 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2771 public void unregisterTetheringEventCallback(
2772 @NonNull final OnTetheringEventCallback callback) {
markchien75721e42020-01-21 13:11:06 +08002773 Objects.requireNonNull(callback, "The callback must be non-null");
2774 synchronized (mTetheringEventCallbacks) {
2775 final TetheringEventCallback tetherCallback =
2776 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002777 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002778 }
markchiena005c992019-02-27 14:56:11 +08002779 }
2780
2781
2782 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002783 * Get the list of regular expressions that define any tetherable
2784 * USB network interfaces. If USB tethering is not supported by the
2785 * device, this list should be empty.
2786 *
2787 * @return an array of 0 or more regular expression Strings defining
2788 * what interfaces are considered tetherable usb interfaces.
2789 *
markchien75721e42020-01-21 13:11:06 +08002790 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002791 * {@hide}
2792 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002793 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002794 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002795 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002796 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002797 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002798 }
2799
2800 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002801 * Get the list of regular expressions that define any tetherable
2802 * Wifi network interfaces. If Wifi tethering is not supported by the
2803 * device, this list should be empty.
2804 *
2805 * @return an array of 0 or more regular expression Strings defining
2806 * what interfaces are considered tetherable wifi interfaces.
2807 *
markchien75721e42020-01-21 13:11:06 +08002808 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002809 * {@hide}
2810 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002811 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002812 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002813 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002814 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002815 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002816 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002817
Danica Chang96567052010-08-11 14:54:43 -07002818 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002819 * Get the list of regular expressions that define any tetherable
2820 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2821 * device, this list should be empty.
2822 *
2823 * @return an array of 0 or more regular expression Strings defining
2824 * what interfaces are considered tetherable bluetooth interfaces.
2825 *
markchien75721e42020-01-21 13:11:06 +08002826 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2827 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002828 * {@hide}
2829 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002830 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002831 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002832 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002833 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002834 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002835 }
2836
Mike Lockwooded4a1742011-07-19 13:04:47 -07002837 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002838 * Attempt to both alter the mode of USB and Tethering of USB. A
2839 * utility method to deal with some of the complexity of USB - will
2840 * attempt to switch to Rndis and subsequently tether the resulting
2841 * interface on {@code true} or turn off tethering and switch off
2842 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002843 *
2844 * <p>This method requires the caller to hold either the
2845 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2846 * or the ability to modify system settings as determined by
2847 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002848 *
2849 * @param enable a boolean - {@code true} to enable tethering
2850 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002851 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002852 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002853 * {@hide}
2854 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002855 @UnsupportedAppUsage
markchien10ddd022020-01-20 19:31:56 +08002856 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002857 public int setUsbTethering(boolean enable) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002858 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002859 }
2860
markchien75721e42020-01-21 13:11:06 +08002861 /**
2862 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2863 * {@hide}
2864 */
markchien5bd499c2019-01-16 17:44:13 +08002865 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002866 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002867 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien75721e42020-01-21 13:11:06 +08002868 /**
2869 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2870 * {@hide}
2871 */
2872 @Deprecated
2873 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2874 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2875 /**
2876 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2877 * {@hide}
2878 */
2879 @Deprecated
2880 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2881 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2882 /**
2883 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2884 * {@hide}
2885 */
2886 @Deprecated
2887 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2888 /**
2889 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2890 * {@hide}
2891 */
2892 @Deprecated
2893 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2894 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2895 /**
markchien68b67842020-03-19 13:37:43 +08002896 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002897 * {@hide}
2898 */
2899 @Deprecated
markchien68b67842020-03-19 13:37:43 +08002900 public static final int TETHER_ERROR_MASTER_ERROR =
2901 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien75721e42020-01-21 13:11:06 +08002902 /**
2903 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2904 * {@hide}
2905 */
2906 @Deprecated
2907 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2908 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2909 /**
2910 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2911 * {@hide}
2912 */
2913 @Deprecated
2914 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2915 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2916 /**
markchien68b67842020-03-19 13:37:43 +08002917 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002918 * {@hide}
2919 */
2920 @Deprecated
2921 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002922 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002923 /**
markchien68b67842020-03-19 13:37:43 +08002924 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002925 * {@hide}
2926 */
2927 @Deprecated
2928 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002929 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002930 /**
2931 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2932 * {@hide}
2933 */
2934 @Deprecated
2935 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2936 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2937 /**
markchien68b67842020-03-19 13:37:43 +08002938 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien75721e42020-01-21 13:11:06 +08002939 * {@hide}
2940 */
markchien5bd499c2019-01-16 17:44:13 +08002941 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002942 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002943 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien75721e42020-01-21 13:11:06 +08002944 /**
2945 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2946 * {@hide}
2947 */
2948 @Deprecated
2949 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2950 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2951 /**
2952 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2953 * {@hide}
2954 */
markchien5bd499c2019-01-16 17:44:13 +08002955 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002956 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002957 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002958
2959 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002960 * Get a more detailed error code after a Tethering or Untethering
2961 * request asynchronously failed.
2962 *
2963 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002964 * @return error The error code of the last error tethering or untethering the named
2965 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002966 *
markchien75721e42020-01-21 13:11:06 +08002967 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002968 * {@hide}
2969 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002970 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002971 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien75721e42020-01-21 13:11:06 +08002972 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002973 public int getLastTetherError(String iface) {
markchien68b67842020-03-19 13:37:43 +08002974 int error = mTetheringManager.getLastTetherError(iface);
2975 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2976 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2977 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2978 // instead.
2979 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2980 }
2981 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002982 }
2983
markchiendd41c822019-03-06 16:25:00 +08002984 /** @hide */
2985 @Retention(RetentionPolicy.SOURCE)
2986 @IntDef(value = {
2987 TETHER_ERROR_NO_ERROR,
2988 TETHER_ERROR_PROVISION_FAILED,
2989 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2990 })
2991 public @interface EntitlementResultCode {
2992 }
2993
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002994 /**
markchiendd41c822019-03-06 16:25:00 +08002995 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08002996 * entitlement succeeded.
markchien75721e42020-01-21 13:11:06 +08002997 *
2998 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08002999 * @hide
3000 */
3001 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003002 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08003003 public interface OnTetheringEntitlementResultListener {
3004 /**
3005 * Called to notify entitlement result.
3006 *
3007 * @param resultCode an int value of entitlement result. It may be one of
3008 * {@link #TETHER_ERROR_NO_ERROR},
3009 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3010 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3011 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07003012 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08003013 }
3014
3015 /**
markchien5bd499c2019-01-16 17:44:13 +08003016 * Get the last value of the entitlement check on this downstream. If the cached value is
3017 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3018 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3019 * guaranteed that the UI-based entitlement check will complete in any specific time period
3020 * and may in fact never complete. Any successful entitlement check the platform performs for
3021 * any reason will update the cached value.
3022 *
3023 * @param type the downstream type of tethering. Must be one of
3024 * {@link #TETHERING_WIFI},
3025 * {@link #TETHERING_USB}, or
3026 * {@link #TETHERING_BLUETOOTH}.
3027 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08003028 * @param executor the executor on which callback will be invoked.
3029 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3030 * notify the caller of the result of entitlement check. The listener may be called zero
3031 * or one time.
markchien75721e42020-01-21 13:11:06 +08003032 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08003033 * {@hide}
3034 */
3035 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003036 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08003037 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08003038 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3039 @NonNull @CallbackExecutor Executor executor,
3040 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003041 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchiendd41c822019-03-06 16:25:00 +08003042 ResultReceiver wrappedListener = new ResultReceiver(null) {
3043 @Override
3044 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslin9cc04192021-03-04 09:38:21 +08003045 final long token = Binder.clearCallingIdentity();
3046 try {
3047 executor.execute(() -> {
3048 listener.onTetheringEntitlementResult(resultCode);
3049 });
3050 } finally {
3051 Binder.restoreCallingIdentity(token);
3052 }
markchiendd41c822019-03-06 16:25:00 +08003053 }
3054 };
3055
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00003056 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienb0bb7862019-12-16 20:15:20 +08003057 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08003058 }
3059
3060 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003061 * Report network connectivity status. This is currently used only
3062 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003063 * <p>This method requires the caller to hold the permission
3064 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003065 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003066 * @param networkType The type of network you want to report on
3067 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09003068 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003069 * {@hide}
3070 */
3071 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003072 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003073 try {
3074 mService.reportInetCondition(networkType, percentage);
3075 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003076 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003077 }
3078 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003079
3080 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003081 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07003082 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003083 * the framework to re-evaluate network connectivity and/or switch to another
3084 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003085 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003086 * @param network The {@link Network} the application was attempting to use
3087 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04003088 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3089 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003090 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003091 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09003092 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003093 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003094 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04003095 // One of these will be ignored because it matches system's current state.
3096 // The other will trigger the necessary reevaluation.
3097 mService.reportNetworkConnectivity(network, true);
3098 mService.reportNetworkConnectivity(network, false);
3099 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003100 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003101 }
3102 }
3103
3104 /**
3105 * Report to the framework whether a network has working connectivity.
3106 * This provides a hint to the system that a particular network is providing
3107 * working connectivity or not. In response the framework may re-evaluate
3108 * the network's connectivity and might take further action thereafter.
3109 *
3110 * @param network The {@link Network} the application was attempting to use
3111 * or {@code null} to indicate the current default network.
3112 * @param hasConnectivity {@code true} if the application was able to successfully access the
3113 * Internet using {@code network} or {@code false} if not.
3114 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003115 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003116 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003117 try {
3118 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003119 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003120 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003121 }
3122 }
3123
3124 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003125 * Set a network-independent global http proxy. This is not normally what you want
3126 * for typical HTTP proxies - they are general network dependent. However if you're
3127 * doing something unusual like general internal filtering this may be useful. On
3128 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003129 *
3130 * @param p A {@link ProxyInfo} object defining the new global
3131 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003132 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003133 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003134 @SystemApi(client = MODULE_LIBRARIES)
paulhuec0a9632019-08-12 16:25:11 +08003135 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003136 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003137 try {
3138 mService.setGlobalProxy(p);
3139 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003140 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003141 }
3142 }
3143
3144 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003145 * Retrieve any network-independent global HTTP proxy.
3146 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003147 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003148 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003149 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003150 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003151 @SystemApi(client = MODULE_LIBRARIES)
3152 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04003153 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003154 try {
3155 return mService.getGlobalProxy();
3156 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003157 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003158 }
3159 }
3160
3161 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003162 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3163 * network-specific HTTP proxy. If {@code network} is null, the
3164 * network-specific proxy returned is the proxy of the default active
3165 * network.
3166 *
3167 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3168 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3169 * or when {@code network} is {@code null},
3170 * the {@code ProxyInfo} for the default active network. Returns
3171 * {@code null} when no proxy applies or the caller doesn't have
3172 * permission to use {@code network}.
3173 * @hide
3174 */
3175 public ProxyInfo getProxyForNetwork(Network network) {
3176 try {
3177 return mService.getProxyForNetwork(network);
3178 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003179 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003180 }
3181 }
3182
3183 /**
Paul Jensen12131352014-12-10 15:12:18 -05003184 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3185 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003186 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003187 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003188 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003189 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003190 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003191 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003192 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003193 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003194 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003195 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003196
3197 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003198 * Returns true if the hardware supports the given network type
3199 * else it returns false. This doesn't indicate we have coverage
3200 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003201 * hardware supports it. For example a GSM phone without a SIM
3202 * should still return {@code true} for mobile data, but a wifi only
3203 * tablet would return {@code false}.
3204 *
3205 * @param networkType The network type we'd like to check
3206 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003207 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003208 * @hide
3209 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003210 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003211 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003212 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003213 public boolean isNetworkSupported(int networkType) {
3214 try {
3215 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003216 } catch (RemoteException e) {
3217 throw e.rethrowFromSystemServer();
3218 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003219 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003220
3221 /**
3222 * Returns if the currently active data network is metered. A network is
3223 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003224 * that connection due to monetary costs, data limitations or
3225 * battery/performance issues. You should check this before doing large
3226 * data transfers, and warn the user or delay the operation until another
3227 * network is available.
3228 *
3229 * @return {@code true} if large transfers should be avoided, otherwise
3230 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003231 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003232 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003233 public boolean isActiveNetworkMetered() {
3234 try {
3235 return mService.isActiveNetworkMetered();
3236 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003237 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003238 }
3239 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003240
Robert Greenwalt26744a52013-02-15 10:56:35 -08003241 /**
Sarah Chincab74db2020-11-25 12:15:14 -08003242 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003243 *
Sarah Chincab74db2020-11-25 12:15:14 -08003244 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003245 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003246 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003247 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003248 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003249 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003250 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003251 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003252 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003253 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003254 }
3255 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003256
3257 /**
3258 * Set the value for enabling/disabling airplane mode
3259 *
3260 * @param enable whether to enable airplane mode or not
3261 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003262 * @hide
3263 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003264 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003265 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003266 android.Manifest.permission.NETWORK_SETTINGS,
3267 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3268 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003269 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003270 public void setAirplaneMode(boolean enable) {
3271 try {
3272 mService.setAirplaneMode(enable);
3273 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003274 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003275 }
3276 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003277
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003278 /**
3279 * Registers the specified {@link NetworkProvider}.
3280 * Each listener must only be registered once. The listener can be unregistered with
3281 * {@link #unregisterNetworkProvider}.
3282 *
3283 * @param provider the provider to register
3284 * @return the ID of the provider. This ID must be used by the provider when registering
3285 * {@link android.net.NetworkAgent}s.
3286 * @hide
3287 */
3288 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003289 @RequiresPermission(anyOf = {
3290 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3291 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003292 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3293 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003294 throw new IllegalStateException("NetworkProviders can only be registered once");
3295 }
3296
3297 try {
3298 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3299 provider.getName());
3300 provider.setProviderId(providerId);
3301 } catch (RemoteException e) {
3302 throw e.rethrowFromSystemServer();
3303 }
3304 return provider.getProviderId();
3305 }
3306
3307 /**
3308 * Unregisters the specified NetworkProvider.
3309 *
3310 * @param provider the provider to unregister
3311 * @hide
3312 */
3313 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003314 @RequiresPermission(anyOf = {
3315 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3316 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003317 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3318 try {
3319 mService.unregisterNetworkProvider(provider.getMessenger());
3320 } catch (RemoteException e) {
3321 throw e.rethrowFromSystemServer();
3322 }
3323 provider.setProviderId(NetworkProvider.ID_NONE);
3324 }
3325
3326
3327 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003328 @RequiresPermission(anyOf = {
3329 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3330 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003331 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3332 try {
3333 mService.declareNetworkRequestUnfulfillable(request);
3334 } catch (RemoteException e) {
3335 throw e.rethrowFromSystemServer();
3336 }
3337 }
3338
Paul Jensenc2569432015-02-13 14:18:39 -05003339 /**
3340 * @hide
3341 * Register a NetworkAgent with ConnectivityService.
Chalard Jean1aea87a2019-12-13 19:47:12 +09003342 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003343 */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003344 @RequiresPermission(anyOf = {
3345 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3346 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003347 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeandd753522020-12-21 18:36:52 +09003348 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3349 int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003350 try {
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003351 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003352 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003353 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003354 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003355 }
3356
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003357 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003358 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3359 * changes. Should be extended by applications wanting notifications.
3360 *
3361 * A {@code NetworkCallback} is registered by calling
3362 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3363 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003364 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003365 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3366 * A {@code NetworkCallback} should be registered at most once at any time.
3367 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003368 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003369 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003370 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003371 * No flags associated with this callback.
3372 * @hide
3373 */
3374 public static final int FLAG_NONE = 0;
3375 /**
3376 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3377 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3378 * <p>
3379 * These include:
3380 * <li> Some transport info instances (retrieved via
3381 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3382 * contain location sensitive information.
3383 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3384 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3385 * </p>
3386 * <p>
3387 * Note:
3388 * <li> Retrieving this location sensitive information (subject to app's location
3389 * permissions) will be noted by system. </li>
3390 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3391 * not include location sensitive info.
3392 * </p>
3393 */
3394 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3395
3396 /** @hide */
3397 @Retention(RetentionPolicy.SOURCE)
3398 @IntDef(flag = true, prefix = "FLAG_", value = {
3399 FLAG_NONE,
3400 FLAG_INCLUDE_LOCATION_INFO
3401 })
3402 public @interface Flag { }
3403
3404 /**
3405 * All the valid flags for error checking.
3406 */
3407 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3408
3409 public NetworkCallback() {
3410 this(FLAG_NONE);
3411 }
3412
3413 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003414 if ((flags & VALID_FLAGS) != flags) {
3415 throw new IllegalArgumentException("Invalid flags");
3416 }
Roshan Pius7992afd2020-12-22 15:10:42 -08003417 mFlags = flags;
3418 }
3419
3420 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003421 * Called when the framework connects to a new network to evaluate whether it satisfies this
3422 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3423 * callback. There is no guarantee that this new network will satisfy any requests, or that
3424 * the network will stay connected for longer than the time necessary to evaluate it.
3425 * <p>
3426 * Most applications <b>should not</b> act on this callback, and should instead use
3427 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3428 * the framework in properly evaluating the network &mdash; for example, an application that
3429 * can automatically log in to a captive portal without user intervention.
3430 *
3431 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003432 *
3433 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003434 */
paulhua9a6e2a2019-03-22 16:35:06 +08003435 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003436
3437 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003438 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003439 * This callback may be called more than once if the {@link Network} that is
3440 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003441 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003442 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003443 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3444 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003445 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003446 * @hide
3447 */
paulhua9a6e2a2019-03-22 16:35:06 +08003448 public void onAvailable(@NonNull Network network,
3449 @NonNull NetworkCapabilities networkCapabilities,
3450 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003451 // Internally only this method is called when a new network is available, and
3452 // it calls the callback in the same way and order that older versions used
3453 // to call so as not to change the behavior.
3454 onAvailable(network);
3455 if (!networkCapabilities.hasCapability(
3456 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3457 onNetworkSuspended(network);
3458 }
3459 onCapabilitiesChanged(network, networkCapabilities);
3460 onLinkPropertiesChanged(network, linkProperties);
junyulai5ab727b2018-08-07 19:50:45 +08003461 onBlockedStatusChanged(network, blocked);
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003462 }
3463
3464 /**
3465 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003466 *
3467 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3468 * be available at the same time, and onAvailable will be called for each of these as they
3469 * appear.
3470 *
3471 * <p>For callbacks registered with {@link #requestNetwork} and
3472 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3473 * is the new best network for this request and is now tracked by this callback ; this
3474 * callback will no longer receive method calls about other networks that may have been
3475 * passed to this method previously. The previously-best network may have disconnected, or
3476 * it may still be around and the newly-best network may simply be better.
3477 *
3478 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3479 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3480 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3481 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3482 *
3483 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3484 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3485 * this callback as this is prone to race conditions (there is no guarantee the objects
3486 * returned by these methods will be current). Instead, wait for a call to
3487 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3488 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3489 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003490 *
3491 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003492 */
paulhua9a6e2a2019-03-22 16:35:06 +08003493 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003494
3495 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003496 * Called when the network is about to be lost, typically because there are no outstanding
3497 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3498 * with the new replacement network for graceful handover. This method is not guaranteed
3499 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3500 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003501 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003502 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3503 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3504 * this callback as this is prone to race conditions ; calling these methods while in a
3505 * callback may return an outdated or even a null object.
3506 *
3507 * @param network The {@link Network} that is about to be lost.
3508 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3509 * connected for graceful handover; note that the network may still
3510 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003511 */
paulhua9a6e2a2019-03-22 16:35:06 +08003512 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003513
3514 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003515 * Called when a network disconnects or otherwise no longer satisfies this request or
3516 * callback.
3517 *
3518 * <p>If the callback was registered with requestNetwork() or
3519 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3520 * returned by onAvailable() when that network is lost and no other network satisfies
3521 * the criteria of the request.
3522 *
3523 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3524 * each network which no longer satisfies the criteria of the callback.
3525 *
3526 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3527 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3528 * this callback as this is prone to race conditions ; calling these methods while in a
3529 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003530 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003531 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003532 */
paulhua9a6e2a2019-03-22 16:35:06 +08003533 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003534
3535 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003536 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003537 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3538 * requested network request cannot be fulfilled (whether or not a timeout was
3539 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003540 * {@link NetworkRequest} will have already been removed and released, as if
3541 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003542 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003543 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003544
3545 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003546 * Called when the network corresponding to this request changes capabilities but still
3547 * satisfies the requested criteria.
3548 *
3549 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3550 * to be called immediately after {@link #onAvailable}.
3551 *
3552 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3553 * ConnectivityManager methods in this callback as this is prone to race conditions :
3554 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003555 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003556 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius7992afd2020-12-22 15:10:42 -08003557 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003558 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003559 */
paulhua9a6e2a2019-03-22 16:35:06 +08003560 public void onCapabilitiesChanged(@NonNull Network network,
3561 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003562
3563 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003564 * Called when the network corresponding to this request changes {@link LinkProperties}.
3565 *
3566 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3567 * to be called immediately after {@link #onAvailable}.
3568 *
3569 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3570 * ConnectivityManager methods in this callback as this is prone to race conditions :
3571 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003572 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003573 * @param network The {@link Network} whose link properties have changed.
3574 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003575 */
paulhua9a6e2a2019-03-22 16:35:06 +08003576 public void onLinkPropertiesChanged(@NonNull Network network,
3577 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003578
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003579 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003580 * Called when the network the framework connected to for this request suspends data
3581 * transmission temporarily.
3582 *
3583 * <p>This generally means that while the TCP connections are still live temporarily
3584 * network data fails to transfer. To give a specific example, this is used on cellular
3585 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3586 * means read operations on sockets on this network will block once the buffers are
3587 * drained, and write operations will block once the buffers are full.
3588 *
3589 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3590 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3591 * this callback as this is prone to race conditions (there is no guarantee the objects
3592 * returned by these methods will be current).
3593 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003594 * @hide
3595 */
paulhua9a6e2a2019-03-22 16:35:06 +08003596 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003597
3598 /**
3599 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003600 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3601 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003602
3603 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3604 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3605 * this callback as this is prone to race conditions : calling these methods while in a
3606 * callback may return an outdated or even a null object.
3607 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003608 * @hide
3609 */
paulhua9a6e2a2019-03-22 16:35:06 +08003610 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003611
junyulai5ab727b2018-08-07 19:50:45 +08003612 /**
3613 * Called when access to the specified network is blocked or unblocked.
3614 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003615 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3616 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3617 * this callback as this is prone to race conditions : calling these methods while in a
3618 * callback may return an outdated or even a null object.
3619 *
junyulai5ab727b2018-08-07 19:50:45 +08003620 * @param network The {@link Network} whose blocked status has changed.
3621 * @param blocked The blocked status of this {@link Network}.
3622 */
junyulai61143782019-03-04 22:45:36 +08003623 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003624
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003625 private NetworkRequest networkRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -08003626 private final int mFlags;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003627 }
3628
Hugo Benichi145e3792017-05-11 13:16:17 +09003629 /**
3630 * Constant error codes used by ConnectivityService to communicate about failures and errors
3631 * across a Binder boundary.
3632 * @hide
3633 */
3634 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003635 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003636 }
3637
3638 /** @hide */
3639 public static class TooManyRequestsException extends RuntimeException {}
3640
3641 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3642 switch (e.errorCode) {
3643 case Errors.TOO_MANY_REQUESTS:
3644 return new TooManyRequestsException();
3645 default:
3646 Log.w(TAG, "Unknown service error code " + e.errorCode);
3647 return new RuntimeException(e);
3648 }
3649 }
3650
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003651 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003652 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003653 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003654 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003655 /** @hide arg1 = TTL */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003656 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003657 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003658 public static final int CALLBACK_LOST = 4;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003659 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003660 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003661 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003662 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003663 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003664 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003665 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003666 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003667 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003668 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003669 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003670 public static final int CALLBACK_RESUMED = 10;
junyulai5ab727b2018-08-07 19:50:45 +08003671 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003672 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003673
Erik Kline66721822015-11-25 12:49:38 +09003674 /** @hide */
3675 public static String getCallbackName(int whichCallback) {
3676 switch (whichCallback) {
3677 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3678 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3679 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3680 case CALLBACK_LOST: return "CALLBACK_LOST";
3681 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3682 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3683 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003684 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3685 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3686 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003687 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003688 default:
3689 return Integer.toString(whichCallback);
3690 }
3691 }
3692
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003693 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003694 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003695 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003696
Hugo Benichife3325f2016-07-06 22:53:17 +09003697 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003698 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003699 }
3700
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003701 CallbackHandler(Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003702 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003703 }
3704
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003705 @Override
3706 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003707 if (message.what == EXPIRE_LEGACY_REQUEST) {
3708 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3709 return;
3710 }
3711
3712 final NetworkRequest request = getObject(message, NetworkRequest.class);
3713 final Network network = getObject(message, Network.class);
3714 final NetworkCallback callback;
3715 synchronized (sCallbacks) {
3716 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003717 if (callback == null) {
3718 Log.w(TAG,
3719 "callback not found for " + getCallbackName(message.what) + " message");
3720 return;
3721 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003722 if (message.what == CALLBACK_UNAVAIL) {
3723 sCallbacks.remove(request);
3724 callback.networkRequest = ALREADY_UNREGISTERED;
3725 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003726 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003727 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003728 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003729 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003730
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003731 switch (message.what) {
3732 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003733 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003734 break;
3735 }
3736 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003737 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3738 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai5ab727b2018-08-07 19:50:45 +08003739 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003740 break;
3741 }
3742 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003743 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003744 break;
3745 }
3746 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003747 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003748 break;
3749 }
3750 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003751 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003752 break;
3753 }
3754 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003755 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3756 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003757 break;
3758 }
3759 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003760 LinkProperties lp = getObject(message, LinkProperties.class);
3761 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003762 break;
3763 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003764 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003765 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003766 break;
3767 }
3768 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003769 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003770 break;
3771 }
junyulai5ab727b2018-08-07 19:50:45 +08003772 case CALLBACK_BLK_CHANGED: {
3773 boolean blocked = message.arg1 != 0;
3774 callback.onBlockedStatusChanged(network, blocked);
3775 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003776 }
3777 }
3778
Hugo Benichife3325f2016-07-06 22:53:17 +09003779 private <T> T getObject(Message msg, Class<T> c) {
3780 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003781 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003782 }
3783
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003784 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003785 synchronized (sCallbacks) {
3786 if (sCallbackHandler == null) {
3787 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003788 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003789 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003790 }
3791 }
3792
Hugo Benichiec180d52017-02-03 14:18:44 +09003793 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3794 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003795
Hugo Benichiec180d52017-02-03 14:18:44 +09003796 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaid1a78162021-01-11 16:53:38 +08003797 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003798 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003799 checkCallbackNotNull(callback);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003800 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3801 throw new IllegalArgumentException("null NetworkCapabilities");
3802 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003803 final NetworkRequest request;
Roshan Piusd26ae412020-01-16 12:17:17 -08003804 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003805 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003806 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003807 if (callback.networkRequest != null
3808 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003809 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3810 // and requests (http://b/20701525).
3811 Log.e(TAG, "NetworkCallback was already registered");
3812 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003813 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003814 Binder binder = new Binder();
Roshan Pius7992afd2020-12-22 15:10:42 -08003815 final int callbackFlags = callback.mFlags;
junyulaid1a78162021-01-11 16:53:38 +08003816 if (reqType == LISTEN) {
Roshan Piusd26ae412020-01-16 12:17:17 -08003817 request = mService.listenForNetwork(
Roshan Pius7992afd2020-12-22 15:10:42 -08003818 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08003819 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003820 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003821 request = mService.requestNetwork(
junyulaid1a78162021-01-11 16:53:38 +08003822 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
Roshan Pius7992afd2020-12-22 15:10:42 -08003823 callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003824 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003825 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003826 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003827 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003828 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003829 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003830 } catch (RemoteException e) {
3831 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003832 } catch (ServiceSpecificException e) {
3833 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003834 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003835 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003836 }
3837
3838 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003839 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003840 *
markchien0fe11402020-03-18 21:16:15 +08003841 * This API is only for use in internal system code that requests networks with legacy type and
3842 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchien769c5752020-01-14 12:54:40 +08003843 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003844 *
markchien769c5752020-01-14 12:54:40 +08003845 * @param request {@link NetworkRequest} describing this request.
markchien769c5752020-01-14 12:54:40 +08003846 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3847 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3848 * be a positive value (i.e. >0).
3849 * @param legacyType to specify the network type(#TYPE_*).
3850 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien0fe11402020-03-18 21:16:15 +08003851 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3852 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003853 *
3854 * @hide
3855 */
markchien769c5752020-01-14 12:54:40 +08003856 @SystemApi
markchien0fe11402020-03-18 21:16:15 +08003857 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003858 public void requestNetwork(@NonNull NetworkRequest request,
markchien0fe11402020-03-18 21:16:15 +08003859 int timeoutMs, int legacyType, @NonNull Handler handler,
3860 @NonNull NetworkCallback networkCallback) {
3861 if (legacyType == TYPE_NONE) {
3862 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3863 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003864 CallbackHandler cbHandler = new CallbackHandler(handler);
3865 NetworkCapabilities nc = request.networkCapabilities;
3866 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003867 }
3868
3869 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003870 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003871 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003872 * <p>This method will attempt to find the best network that matches the passed
3873 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3874 * criteria. The platform will evaluate which network is the best at its own discretion.
3875 * Throughput, latency, cost per byte, policy, user preference and other considerations
3876 * may be factored in the decision of what is considered the best network.
3877 *
3878 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3879 * matching this request, while always attempting to match the request to a better network if
3880 * possible. If a better match is found, the platform will switch this request to the now-best
3881 * network and inform the app of the newly best network by invoking
3882 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3883 * will not try to maintain any other network than the best one currently matching the request:
3884 * a network not matching any network request may be disconnected at any time.
3885 *
3886 * <p>For example, an application could use this method to obtain a connected cellular network
3887 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3888 * radio to consume additional power. Or, an application could inform the system that it wants
3889 * a network supporting sending MMSes and have the system let it know about the currently best
3890 * MMS-supporting network through the provided {@link NetworkCallback}.
3891 *
3892 * <p>The status of the request can be followed by listening to the various callbacks described
3893 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3894 * used to direct traffic to the network (although accessing some networks may be subject to
3895 * holding specific permissions). Callers will learn about the specific characteristics of the
3896 * network through
3897 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3898 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3899 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3900 * matching the request at any given time; therefore when a better network matching the request
3901 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3902 * with the new network after which no further updates are given about the previously-best
3903 * network, unless it becomes the best again at some later time. All callbacks are invoked
3904 * in order on the same thread, which by default is a thread created by the framework running
3905 * in the app.
3906 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3907 * callbacks are invoked.
3908 *
3909 * <p>This{@link NetworkRequest} will live until released via
3910 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3911 * which point the system may let go of the network at any time.
3912 *
3913 * <p>A version of this method which takes a timeout is
3914 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3915 * wait for a limited amount of time for the network to become unavailable.
3916 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003917 * <p>It is presently unsupported to request a network with mutable
3918 * {@link NetworkCapabilities} such as
3919 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3920 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3921 * as these {@code NetworkCapabilities} represent states that a particular
3922 * network may never attain, and whether a network will attain these states
3923 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09003924 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003925 *
3926 * <p>This method requires the caller to hold either the
3927 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3928 * or the ability to modify system settings as determined by
3929 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003930 *
Chalard Jean7f06b342020-05-20 16:11:50 +09003931 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3932 * number of outstanding requests to 100 per app (identified by their UID), shared with
3933 * all variants of this method, of {@link #registerNetworkCallback} as well as
3934 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3935 * Requesting a network with this method will count toward this limit. If this limit is
3936 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3937 * make sure to unregister the callbacks with
3938 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3939 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003940 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003941 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3942 * the callback must not be shared - it uniquely specifies this request.
3943 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09003944 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3945 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09003946 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003947 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003948 public void requestNetwork(@NonNull NetworkRequest request,
3949 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003950 requestNetwork(request, networkCallback, getDefaultHandler());
3951 }
3952
3953 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003954 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003955 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003956 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3957 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003958 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003959 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003960 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3961 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003962 *
3963 * @param request {@link NetworkRequest} describing this request.
3964 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3965 * the callback must not be shared - it uniquely specifies this request.
3966 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003967 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003968 public void requestNetwork(@NonNull NetworkRequest request,
3969 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003970 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08003971 NetworkCapabilities nc = request.networkCapabilities;
3972 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003973 }
3974
3975 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003976 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohen67e58a02017-03-01 12:47:28 -08003977 * by a timeout.
3978 *
3979 * This function behaves identically to the non-timed-out version
3980 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3981 * is not found within the given time (in milliseconds) the
3982 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3983 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3984 * not have to be released if timed-out (it is automatically released). Unregistering a
3985 * request that timed out is not an error.
3986 *
3987 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3988 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3989 * for that purpose. Calling this method will attempt to bring up the requested network.
3990 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003991 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003992 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3993 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08003994 *
3995 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003996 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3997 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003998 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3999 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4000 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08004001 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004002 public void requestNetwork(@NonNull NetworkRequest request,
4003 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004004 checkTimeout(timeoutMs);
markchien0fe11402020-03-18 21:16:15 +08004005 NetworkCapabilities nc = request.networkCapabilities;
4006 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4007 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004008 }
4009
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004010 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004011 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004012 * by a timeout.
4013 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004014 * This method behaves identically to
4015 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4016 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08004017 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004018 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004019 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4020 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004021 *
4022 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004023 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4024 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004025 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004026 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4027 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004028 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004029 public void requestNetwork(@NonNull NetworkRequest request,
4030 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004031 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004032 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004033 NetworkCapabilities nc = request.networkCapabilities;
4034 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004035 }
4036
4037 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004038 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004039 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004040 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08004041 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04004042 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4043 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004044 */
Erik Klinefb087f12014-11-19 12:12:24 +09004045 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004046
4047 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004048 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004049 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004050 * {@link android.content.Intent#getParcelableExtra(String)}.
4051 */
Erik Klinefb087f12014-11-19 12:12:24 +09004052 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004053
4054
4055 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004056 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004057 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08004058 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004059 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004060 * the request may outlive the calling application and get called back when a suitable
4061 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004062 * <p>
4063 * The operation is an Intent broadcast that goes to a broadcast receiver that
4064 * you registered with {@link Context#registerReceiver} or through the
4065 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4066 * <p>
4067 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09004068 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4069 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004070 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004071 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004072 * Intent to reserve the network or it will be released shortly after the Intent
4073 * is processed.
4074 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04004075 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004076 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004077 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004078 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08004079 * The request may be released normally by calling
4080 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004081 * <p>It is presently unsupported to request a network with either
4082 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4083 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4084 * as these {@code NetworkCapabilities} represent states that a particular
4085 * network may never attain, and whether a network will attain these states
4086 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09004087 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004088 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004089 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4090 * number of outstanding requests to 100 per app (identified by their UID), shared with
4091 * all variants of this method, of {@link #registerNetworkCallback} as well as
4092 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4093 * Requesting a network with this method will count toward this limit. If this limit is
4094 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4095 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4096 * or {@link #releaseNetworkRequest(PendingIntent)}.
4097 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004098 * <p>This method requires the caller to hold either the
4099 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4100 * or the ability to modify system settings as determined by
4101 * {@link android.provider.Settings.System#canWrite}.</p>
4102 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004103 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004104 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004105 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08004106 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004107 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4108 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004109 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004110 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004111 public void requestNetwork(@NonNull NetworkRequest request,
4112 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004113 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004114 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004115 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004116 mService.pendingRequestForNetwork(
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07004117 request.networkCapabilities, operation, mContext.getOpPackageName(),
4118 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004119 } catch (RemoteException e) {
4120 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004121 } catch (ServiceSpecificException e) {
4122 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004123 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004124 }
4125
4126 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004127 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4128 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004129 * This method has the same behavior as
4130 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004131 * releasing network resources and disconnecting.
4132 *
4133 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4134 * PendingIntent passed to
4135 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4136 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4137 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004138 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004139 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004140 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004141 try {
4142 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004143 } catch (RemoteException e) {
4144 throw e.rethrowFromSystemServer();
4145 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004146 }
4147
Hugo Benichiff4bf602017-05-09 15:19:01 +09004148 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004149 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004150 }
4151
4152 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004153 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004154 }
4155
4156 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004157 if (timeoutMs <= 0) {
4158 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4159 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004160 }
4161
4162 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004163 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004164 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004165 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4166 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004167 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004168 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4169 * number of outstanding requests to 100 per app (identified by their UID), shared with
4170 * all variants of this method, of {@link #requestNetwork} as well as
4171 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4172 * Requesting a network with this method will count toward this limit. If this limit is
4173 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4174 * make sure to unregister the callbacks with
4175 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4176 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004177 * @param request {@link NetworkRequest} describing this request.
4178 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4179 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004180 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004181 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004182 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004183 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004184 public void registerNetworkCallback(@NonNull NetworkRequest request,
4185 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004186 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4187 }
4188
4189 /**
4190 * Registers to receive notifications about all networks which satisfy the given
4191 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004192 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4193 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004194 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004195 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4196 * number of outstanding requests to 100 per app (identified by their UID), shared with
4197 * all variants of this method, of {@link #requestNetwork} as well as
4198 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4199 * Requesting a network with this method will count toward this limit. If this limit is
4200 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4201 * make sure to unregister the callbacks with
4202 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4203 *
4204 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004205 * @param request {@link NetworkRequest} describing this request.
4206 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4207 * networks change state.
4208 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004209 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004210 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004211 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004212 public void registerNetworkCallback(@NonNull NetworkRequest request,
4213 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004214 CallbackHandler cbHandler = new CallbackHandler(handler);
4215 NetworkCapabilities nc = request.networkCapabilities;
4216 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004217 }
4218
4219 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004220 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4221 * {@link NetworkRequest}.
4222 *
4223 * This function behaves identically to the version that takes a NetworkCallback, but instead
4224 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4225 * the request may outlive the calling application and get called back when a suitable
4226 * network is found.
4227 * <p>
4228 * The operation is an Intent broadcast that goes to a broadcast receiver that
4229 * you registered with {@link Context#registerReceiver} or through the
4230 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4231 * <p>
4232 * The operation Intent is delivered with two extras, a {@link Network} typed
4233 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4234 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4235 * the original requests parameters.
4236 * <p>
4237 * If there is already a request for this Intent registered (with the equality of
4238 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4239 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4240 * <p>
4241 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004242 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004243 *
4244 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4245 * number of outstanding requests to 100 per app (identified by their UID), shared with
4246 * all variants of this method, of {@link #requestNetwork} as well as
4247 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4248 * Requesting a network with this method will count toward this limit. If this limit is
4249 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4250 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4251 * or {@link #releaseNetworkRequest(PendingIntent)}.
4252 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004253 * @param request {@link NetworkRequest} describing this request.
4254 * @param operation Action to perform when the network is available (corresponds
4255 * to the {@link NetworkCallback#onAvailable} call. Typically
4256 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004257 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004258 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004259 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004260 public void registerNetworkCallback(@NonNull NetworkRequest request,
4261 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004262 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004263 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004264 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004265 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004266 request.networkCapabilities, operation, mContext.getOpPackageName(),
4267 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004268 } catch (RemoteException e) {
4269 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004270 } catch (ServiceSpecificException e) {
4271 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004272 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004273 }
4274
4275 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004276 * Registers to receive notifications about changes in the application's default network. This
4277 * may be a physical network or a virtual network, such as a VPN that applies to the
4278 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004279 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004280 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004281 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4282 * number of outstanding requests to 100 per app (identified by their UID), shared with
4283 * all variants of this method, of {@link #requestNetwork} as well as
4284 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4285 * Requesting a network with this method will count toward this limit. If this limit is
4286 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4287 * make sure to unregister the callbacks with
4288 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4289 *
Erik Klinee0aed632016-03-16 15:31:39 +09004290 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004291 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004292 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004293 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004294 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004295 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004296 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004297 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4298 }
4299
4300 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004301 * Registers to receive notifications about changes in the application's default network. This
4302 * may be a physical network or a virtual network, such as a VPN that applies to the
4303 * application. The callbacks will continue to be called until either the application exits or
4304 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4305 *
4306 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4307 * number of outstanding requests to 100 per app (identified by their UID), shared with
4308 * all variants of this method, of {@link #requestNetwork} as well as
4309 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4310 * Requesting a network with this method will count toward this limit. If this limit is
4311 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4312 * make sure to unregister the callbacks with
4313 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4314 *
4315 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4316 * application's default network changes.
4317 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4318 * @throws RuntimeException if the app already has too many callbacks registered.
4319 */
4320 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4321 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4322 @NonNull Handler handler) {
4323 CallbackHandler cbHandler = new CallbackHandler(handler);
4324 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4325 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4326 }
4327
4328 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004329 * Registers to receive notifications about changes in the system default network. The callbacks
4330 * will continue to be called until either the application exits or
4331 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004332 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004333 * This method should not be used to determine networking state seen by applications, because in
4334 * many cases, most or even all application traffic may not use the default network directly,
4335 * and traffic from different applications may go on different networks by default. As an
4336 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4337 * and not onto the system default network. Applications or system components desiring to do
4338 * determine network state as seen by applications should use other methods such as
4339 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4340 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004341 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4342 * number of outstanding requests to 100 per app (identified by their UID), shared with
4343 * all variants of this method, of {@link #requestNetwork} as well as
4344 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4345 * Requesting a network with this method will count toward this limit. If this limit is
4346 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4347 * make sure to unregister the callbacks with
4348 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4349 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004350 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4351 * system default network changes.
4352 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004353 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004354 *
4355 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004356 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004357 @SystemApi(client = MODULE_LIBRARIES)
4358 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4359 @RequiresPermission(anyOf = {
4360 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4361 android.Manifest.permission.NETWORK_SETTINGS})
4362 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004363 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004364 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004365 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004366 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004367 }
4368
4369 /**
junyulaibd622262021-03-15 11:48:48 +08004370 * Registers to receive notifications about the best matching network which satisfy the given
4371 * {@link NetworkRequest}. The callbacks will continue to be called until
4372 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4373 * called.
4374 *
4375 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4376 * number of outstanding requests to 100 per app (identified by their UID), shared with
4377 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4378 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4379 * Requesting a network with this method will count toward this limit. If this limit is
4380 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4381 * make sure to unregister the callbacks with
4382 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4383 *
4384 *
4385 * @param request {@link NetworkRequest} describing this request.
4386 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4387 * networks change state.
4388 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4389 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai6b0a6a22021-03-05 15:51:17 +08004390 */
junyulai6b0a6a22021-03-05 15:51:17 +08004391 @SuppressLint("ExecutorRegistration")
4392 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4393 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4394 final NetworkCapabilities nc = request.networkCapabilities;
4395 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai8cae3c72021-03-12 20:05:08 +08004396 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai6b0a6a22021-03-05 15:51:17 +08004397 }
4398
4399 /**
fenglu73169332015-04-21 17:12:05 -07004400 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4401 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4402 * network connection for updated bandwidth information. The caller will be notified via
4403 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004404 * method assumes that the caller has previously called
4405 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4406 * changes.
fenglu76564332015-03-20 11:29:56 -07004407 *
fenglu41808e82015-04-27 14:28:04 -07004408 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004409 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004410 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004411 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004412 try {
fenglu73169332015-04-21 17:12:05 -07004413 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004414 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004415 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004416 }
4417 }
4418
4419 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004420 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004421 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4422 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4423 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004424 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4425 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004426 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004427 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4428 * triggering it as soon as this call returns.
4429 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004430 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004431 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004432 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004433 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004434 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004435 final List<NetworkRequest> reqs = new ArrayList<>();
4436 // Find all requests associated to this callback and stop callback triggers immediately.
4437 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4438 synchronized (sCallbacks) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004439 if (networkCallback.networkRequest == null) {
4440 throw new IllegalArgumentException("NetworkCallback was not registered");
4441 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07004442 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4443 Log.d(TAG, "NetworkCallback was already unregistered");
4444 return;
4445 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004446 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4447 if (e.getValue() == networkCallback) {
4448 reqs.add(e.getKey());
4449 }
4450 }
4451 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4452 for (NetworkRequest r : reqs) {
4453 try {
4454 mService.releaseNetworkRequest(r);
4455 } catch (RemoteException e) {
4456 throw e.rethrowFromSystemServer();
4457 }
4458 // Only remove mapping if rpc was successful.
4459 sCallbacks.remove(r);
4460 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004461 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004462 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004463 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004464
4465 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004466 * Unregisters a callback previously registered via
4467 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4468 *
4469 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4470 * PendingIntent passed to
4471 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4472 * Cannot be null.
4473 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004474 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004475 releaseNetworkRequest(operation);
4476 }
4477
4478 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004479 * Informs the system whether it should switch to {@code network} regardless of whether it is
4480 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4481 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4482 * the system default network regardless of any other network that's currently connected. If
4483 * {@code always} is true, then the choice is remembered, so that the next time the user
4484 * connects to this network, the system will switch to it.
4485 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004486 * @param network The network to accept.
4487 * @param accept Whether to accept the network even if unvalidated.
4488 * @param always Whether to remember this choice in the future.
4489 *
4490 * @hide
4491 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004492 @SystemApi(client = MODULE_LIBRARIES)
4493 @RequiresPermission(anyOf = {
4494 android.Manifest.permission.NETWORK_SETTINGS,
4495 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4496 android.Manifest.permission.NETWORK_STACK,
4497 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4498 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004499 try {
4500 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004501 } catch (RemoteException e) {
4502 throw e.rethrowFromSystemServer();
4503 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004504 }
4505
4506 /**
lucaslin25a50472019-03-12 13:08:03 +08004507 * Informs the system whether it should consider the network as validated even if it only has
4508 * partial connectivity. If {@code accept} is true, then the network will be considered as
4509 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4510 * is remembered, so that the next time the user connects to this network, the system will
4511 * switch to it.
4512 *
4513 * @param network The network to accept.
4514 * @param accept Whether to consider the network as validated even if it has partial
4515 * connectivity.
4516 * @param always Whether to remember this choice in the future.
4517 *
4518 * @hide
4519 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004520 @SystemApi(client = MODULE_LIBRARIES)
4521 @RequiresPermission(anyOf = {
4522 android.Manifest.permission.NETWORK_SETTINGS,
4523 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4524 android.Manifest.permission.NETWORK_STACK,
4525 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4526 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4527 boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004528 try {
4529 mService.setAcceptPartialConnectivity(network, accept, always);
4530 } catch (RemoteException e) {
4531 throw e.rethrowFromSystemServer();
4532 }
4533 }
4534
4535 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004536 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4537 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4538 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4539 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4540 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004541 * @param network The network to accept.
4542 *
4543 * @hide
4544 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004545 @SystemApi(client = MODULE_LIBRARIES)
4546 @RequiresPermission(anyOf = {
4547 android.Manifest.permission.NETWORK_SETTINGS,
4548 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4549 android.Manifest.permission.NETWORK_STACK,
4550 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4551 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004552 try {
4553 mService.setAvoidUnvalidated(network);
4554 } catch (RemoteException e) {
4555 throw e.rethrowFromSystemServer();
4556 }
4557 }
4558
4559 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004560 * Requests that the system open the captive portal app on the specified network.
4561 *
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004562 * <p>This is to be used on networks where a captive portal was detected, as per
4563 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4564 *
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004565 * @param network The network to log into.
4566 *
4567 * @hide
4568 */
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004569 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4570 @RequiresPermission(anyOf = {
4571 android.Manifest.permission.NETWORK_SETTINGS,
4572 android.Manifest.permission.NETWORK_STACK,
4573 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4574 })
4575 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004576 try {
4577 mService.startCaptivePortalApp(network);
4578 } catch (RemoteException e) {
4579 throw e.rethrowFromSystemServer();
4580 }
4581 }
4582
4583 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004584 * Requests that the system open the captive portal app with the specified extras.
4585 *
4586 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4587 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004588 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004589 * @param appExtras Extras to include in the app start intent.
4590 * @hide
4591 */
4592 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004593 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004594 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004595 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004596 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004597 } catch (RemoteException e) {
4598 throw e.rethrowFromSystemServer();
4599 }
4600 }
4601
4602 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004603 * Determine whether the device is configured to avoid bad wifi.
4604 * @hide
4605 */
4606 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004607 @RequiresPermission(anyOf = {
4608 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4609 android.Manifest.permission.NETWORK_STACK})
4610 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004611 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004612 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004613 } catch (RemoteException e) {
4614 throw e.rethrowFromSystemServer();
4615 }
4616 }
4617
4618 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004619 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4620 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004621 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4622 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004623 *
4624 * An example of such an operation might be a time-sensitive foreground activity, such as a
4625 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4626 */
4627 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4628
4629 /**
4630 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4631 * a backup channel for traffic that is primarily going over another network.
4632 *
4633 * An example might be maintaining backup connections to peers or servers for the purpose of
4634 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4635 * on backup paths should be negligible compared to the traffic on the main path.
4636 */
4637 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4638
4639 /**
4640 * It is acceptable to use metered data to improve network latency and performance.
4641 */
4642 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4643
4644 /**
4645 * Return value to use for unmetered networks. On such networks we currently set all the flags
4646 * to true.
4647 * @hide
4648 */
4649 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4650 MULTIPATH_PREFERENCE_HANDOVER |
4651 MULTIPATH_PREFERENCE_RELIABILITY |
4652 MULTIPATH_PREFERENCE_PERFORMANCE;
4653
4654 /** @hide */
4655 @Retention(RetentionPolicy.SOURCE)
4656 @IntDef(flag = true, value = {
4657 MULTIPATH_PREFERENCE_HANDOVER,
4658 MULTIPATH_PREFERENCE_RELIABILITY,
4659 MULTIPATH_PREFERENCE_PERFORMANCE,
4660 })
4661 public @interface MultipathPreference {
4662 }
4663
4664 /**
4665 * Provides a hint to the calling application on whether it is desirable to use the
4666 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4667 * for multipath data transfer on this network when it is not the system default network.
4668 * Applications desiring to use multipath network protocols should call this method before
4669 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004670 *
4671 * @param network The network on which the application desires to use multipath data.
4672 * If {@code null}, this method will return the a preference that will generally
4673 * apply to metered networks.
4674 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4675 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004676 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004677 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004678 try {
4679 return mService.getMultipathPreference(network);
4680 } catch (RemoteException e) {
4681 throw e.rethrowFromSystemServer();
4682 }
4683 }
4684
4685 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004686 * Resets all connectivity manager settings back to factory defaults.
4687 * @hide
4688 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004689 @SystemApi(client = MODULE_LIBRARIES)
4690 @RequiresPermission(anyOf = {
4691 android.Manifest.permission.NETWORK_SETTINGS,
4692 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scottd3bb5082015-03-30 13:17:11 -07004693 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004694 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004695 mService.factoryReset();
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00004696 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004697 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004698 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004699 }
4700 }
4701
4702 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004703 * Binds the current process to {@code network}. All Sockets created in the future
4704 * (and not explicitly bound via a bound SocketFactory from
4705 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4706 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4707 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4708 * work and all host name resolutions will fail. This is by design so an application doesn't
4709 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4710 * To clear binding pass {@code null} for {@code network}. Using individually bound
4711 * Sockets created by Network.getSocketFactory().createSocket() and
4712 * performing network-specific host name resolutions via
4713 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004714 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004715 *
4716 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4717 * the current binding.
4718 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4719 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004720 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004721 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004722 // instantiated.
4723 return setProcessDefaultNetwork(network);
4724 }
4725
4726 /**
4727 * Binds the current process to {@code network}. All Sockets created in the future
4728 * (and not explicitly bound via a bound SocketFactory from
4729 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4730 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4731 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4732 * work and all host name resolutions will fail. This is by design so an application doesn't
4733 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4734 * To clear binding pass {@code null} for {@code network}. Using individually bound
4735 * Sockets created by Network.getSocketFactory().createSocket() and
4736 * performing network-specific host name resolutions via
4737 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4738 * {@code setProcessDefaultNetwork}.
4739 *
4740 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4741 * the current binding.
4742 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4743 * @deprecated This function can throw {@link IllegalStateException}. Use
4744 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4745 * is a direct replacement.
4746 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004747 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004748 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004749 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004750 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4751
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004752 if (netId != NETID_UNSET) {
4753 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004754 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004755
4756 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4757 return false;
4758 }
4759
4760 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004761 // Set HTTP proxy system properties to match network.
4762 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004763 try {
Remi NGUYEN VANa1860ff2021-02-03 10:18:20 +09004764 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004765 } catch (SecurityException e) {
4766 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4767 Log.e(TAG, "Can't set proxy properties", e);
4768 }
Paul Jensen99c36662014-08-27 12:38:45 -04004769 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN33e3abb2021-03-18 23:27:19 +09004770 InetAddressCompat.clearDnsCache();
Paul Jensen99c36662014-08-27 12:38:45 -04004771 // Must flush socket pool as idle sockets will be bound to previous network and may
4772 // cause subsequent fetches to be performed on old network.
4773 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004774 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004775
4776 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004777 }
4778
4779 /**
4780 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004781 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004782 *
4783 * @return {@code Network} to which this process is bound, or {@code null}.
4784 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004785 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004786 public Network getBoundNetworkForProcess() {
4787 // Forcing callers to call thru non-static function ensures ConnectivityManager
4788 // instantiated.
4789 return getProcessDefaultNetwork();
4790 }
4791
4792 /**
4793 * Returns the {@link Network} currently bound to this process via
4794 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4795 *
4796 * @return {@code Network} to which this process is bound, or {@code null}.
4797 * @deprecated Using this function can lead to other functions throwing
4798 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4799 * {@code getBoundNetworkForProcess} is a direct replacement.
4800 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004801 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004802 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004803 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004804 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004805 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004806 return new Network(netId);
4807 }
4808
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004809 private void unsupportedStartingFrom(int version) {
4810 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004811 // The getApplicationInfo() call we make below is not supported in system context. Let
4812 // the call through here, and rely on the fact that ConnectivityService will refuse to
4813 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004814 return;
4815 }
4816
4817 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4818 throw new UnsupportedOperationException(
4819 "This method is not supported in target SDK version " + version + " and above");
4820 }
4821 }
4822
4823 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4824 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004825 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004826 // remove these exemptions. Note that this check is not secure, and apps can still access these
4827 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4828 // so is unsupported and may break in the future. http://b/22728205
4829 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07004830 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004831 }
4832
Paul Jensene98c6e02014-05-29 10:12:39 -04004833 /**
4834 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04004835 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04004836 *
4837 * @param network The {@link Network} to bind host resolutions from the current process to, or
4838 * {@code null} to clear the current binding.
4839 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4840 * @hide
4841 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4842 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004843 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00004844 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04004845 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04004846 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09004847 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04004848 }
Felipe Lemed16384b2016-01-22 09:44:57 -08004849
4850 /**
4851 * Device is not restricting metered network activity while application is running on
4852 * background.
4853 */
4854 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4855
4856 /**
4857 * Device is restricting metered network activity while application is running on background,
4858 * but application is allowed to bypass it.
4859 * <p>
4860 * In this state, application should take action to mitigate metered network access.
4861 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4862 */
4863 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4864
4865 /**
4866 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08004867 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08004868 * In this state, application should not try to use the network while running on background,
4869 * because it would be denied.
4870 */
4871 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4872
Felipe Leme6a5b7692016-01-27 14:46:39 -08004873 /**
4874 * A change in the background metered network activity restriction has occurred.
4875 * <p>
4876 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4877 * applies to them.
4878 * <p>
4879 * This is only sent to registered receivers, not manifest receivers.
4880 */
4881 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4882 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4883 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4884
Felipe Leme1b42ef92016-01-25 11:48:04 -08004885 /** @hide */
4886 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08004887 @IntDef(flag = false, value = {
4888 RESTRICT_BACKGROUND_STATUS_DISABLED,
4889 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4890 RESTRICT_BACKGROUND_STATUS_ENABLED,
4891 })
Felipe Lemed16384b2016-01-22 09:44:57 -08004892 public @interface RestrictBackgroundStatus {
4893 }
4894
Felipe Lemed16384b2016-01-22 09:44:57 -08004895 /**
4896 * Determines if the calling application is subject to metered network restrictions while
4897 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07004898 *
4899 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4900 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4901 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08004902 */
4903 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4904 try {
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09004905 return mService.getRestrictBackgroundStatusByCaller();
Felipe Lemed16384b2016-01-22 09:44:57 -08004906 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004907 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08004908 }
4909 }
Ricky Waid53cf002018-01-23 04:09:45 +00004910
4911 /**
4912 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00004913 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4914 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00004915 *
4916 * @return Hash of network watchlist config file. Null if config does not exist.
4917 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004918 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00004919 public byte[] getNetworkWatchlistConfigHash() {
4920 try {
4921 return mService.getNetworkWatchlistConfigHash();
4922 } catch (RemoteException e) {
4923 Log.e(TAG, "Unable to get watchlist config hash");
4924 throw e.rethrowFromSystemServer();
4925 }
4926 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004927
4928 /**
4929 * Returns the {@code uid} of the owner of a network connection.
4930 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08004931 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4932 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004933 * @param local The local {@link InetSocketAddress} of a connection.
4934 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004935 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08004936 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4937 * android.os.Process#INVALID_UID} if the connection is not found.
4938 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4939 * user.
4940 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004941 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08004942 public int getConnectionOwnerUid(
4943 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004944 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4945 try {
4946 return mService.getConnectionOwnerUid(connectionInfo);
4947 } catch (RemoteException e) {
4948 throw e.rethrowFromSystemServer();
4949 }
4950 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004951
4952 private void printStackTrace() {
4953 if (DEBUG) {
4954 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4955 final StringBuffer sb = new StringBuffer();
4956 for (int i = 3; i < callStack.length; i++) {
4957 final String stackTrace = callStack[i].toString();
4958 if (stackTrace == null || stackTrace.contains("android.os")) {
4959 break;
4960 }
4961 sb.append(" [").append(stackTrace).append("]");
4962 }
4963 Log.d(TAG, "StackLog:" + sb.toString());
4964 }
4965 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004966
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004967 /** @hide */
4968 public TestNetworkManager startOrGetTestNetworkManager() {
4969 final IBinder tnBinder;
4970 try {
4971 tnBinder = mService.startOrGetTestNetworkService();
4972 } catch (RemoteException e) {
4973 throw e.rethrowFromSystemServer();
4974 }
4975
4976 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4977 }
4978
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004979 /** @hide */
4980 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4981 return new ConnectivityDiagnosticsManager(mContext, mService);
4982 }
4983
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004984 /**
4985 * Simulates a Data Stall for the specified Network.
4986 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004987 * <p>This method should only be used for tests.
4988 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004989 * <p>The caller must be the owner of the specified Network.
4990 *
4991 * @param detectionMethod The detection method used to identify the Data Stall.
4992 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4993 * @param network The Network for which a Data Stall is being simluated.
4994 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4995 * @throws SecurityException if the caller is not the owner of the given network.
4996 * @hide
4997 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004998 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004999 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5000 android.Manifest.permission.NETWORK_STACK})
5001 public void simulateDataStall(int detectionMethod, long timestampMillis,
5002 @NonNull Network network, @NonNull PersistableBundle extras) {
5003 try {
5004 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5005 } catch (RemoteException e) {
5006 e.rethrowFromSystemServer();
5007 }
5008 }
James Mattisdcea9fb2020-10-28 21:48:54 -07005009
Daniel Bright60f02ed2020-06-15 16:10:01 -07005010 @NonNull
5011 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5012
5013 /**
5014 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5015 * receive available QoS events related to the {@link Network} and local ip + port
5016 * specified within socketInfo.
5017 * <p/>
5018 * The same {@link QosCallback} must be unregistered before being registered a second time,
5019 * otherwise {@link QosCallbackRegistrationException} is thrown.
5020 * <p/>
5021 * This API does not, in itself, require any permission if called with a network that is not
5022 * restricted. However, the underlying implementation currently only supports the IMS network,
5023 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5024 * useful, because they'd never be called back on networks that they would have access to.
5025 *
5026 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5027 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5028 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5029 * @throws RuntimeException if the app already has too many callbacks registered.
5030 *
5031 * Exceptions after the time of registration is passed through
5032 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5033 *
5034 * @param socketInfo the socket information used to match QoS events
Daniel Bright60f02ed2020-06-15 16:10:01 -07005035 * @param executor The executor on which the callback will be invoked. The provided
5036 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Brightb953a3e2021-03-10 11:51:50 -08005037 * callbacks cannot be guaranteed.onQosCallbackRegistered
5038 * @param callback receives qos events that satisfy socketInfo
Daniel Bright60f02ed2020-06-15 16:10:01 -07005039 *
5040 * @hide
5041 */
5042 @SystemApi
5043 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Brightb953a3e2021-03-10 11:51:50 -08005044 @CallbackExecutor @NonNull final Executor executor,
5045 @NonNull final QosCallback callback) {
Daniel Bright60f02ed2020-06-15 16:10:01 -07005046 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005047 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Brightb953a3e2021-03-10 11:51:50 -08005048 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005049
5050 try {
5051 synchronized (mQosCallbackConnections) {
5052 if (getQosCallbackConnection(callback) == null) {
5053 final QosCallbackConnection connection =
5054 new QosCallbackConnection(this, callback, executor);
5055 mQosCallbackConnections.add(connection);
5056 mService.registerQosSocketCallback(socketInfo, connection);
5057 } else {
5058 Log.e(TAG, "registerQosCallback: Callback already registered");
5059 throw new QosCallbackRegistrationException();
5060 }
5061 }
5062 } catch (final RemoteException e) {
5063 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5064
5065 // The same unregister method method is called for consistency even though nothing
5066 // will be sent to the ConnectivityService since the callback was never successfully
5067 // registered.
5068 unregisterQosCallback(callback);
5069 e.rethrowFromSystemServer();
5070 } catch (final ServiceSpecificException e) {
5071 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5072 unregisterQosCallback(callback);
5073 throw convertServiceException(e);
5074 }
5075 }
5076
5077 /**
5078 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5079 * events once unregistered and can be registered a second time.
5080 * <p/>
5081 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5082 *
5083 * @param callback the callback being unregistered
5084 *
5085 * @hide
5086 */
5087 @SystemApi
5088 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5089 Objects.requireNonNull(callback, "The callback must be non-null");
5090 try {
5091 synchronized (mQosCallbackConnections) {
5092 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5093 if (connection != null) {
5094 connection.stopReceivingMessages();
5095 mService.unregisterQosCallback(connection);
5096 mQosCallbackConnections.remove(connection);
5097 } else {
5098 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5099 }
5100 }
5101 } catch (final RemoteException e) {
5102 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5103 e.rethrowFromSystemServer();
5104 }
5105 }
5106
5107 /**
5108 * Gets the connection related to the callback.
5109 *
5110 * @param callback the callback to look up
5111 * @return the related connection
5112 */
5113 @Nullable
5114 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5115 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5116 // Checking by reference here is intentional
5117 if (connection.getCallback() == callback) {
5118 return connection;
5119 }
5120 }
5121 return null;
5122 }
Junyu Lai23568a42021-01-19 11:10:56 +00005123
5124 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08005125 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Lai23568a42021-01-19 11:10:56 +00005126 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5127 * be used to request that the system provide a network without causing the network to be
5128 * in the foreground.
5129 *
5130 * <p>This method will attempt to find the best network that matches the passed
5131 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5132 * criteria. The platform will evaluate which network is the best at its own discretion.
5133 * Throughput, latency, cost per byte, policy, user preference and other considerations
5134 * may be factored in the decision of what is considered the best network.
5135 *
5136 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5137 * matching this request, while always attempting to match the request to a better network if
5138 * possible. If a better match is found, the platform will switch this request to the now-best
5139 * network and inform the app of the newly best network by invoking
5140 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5141 * will not try to maintain any other network than the best one currently matching the request:
5142 * a network not matching any network request may be disconnected at any time.
5143 *
5144 * <p>For example, an application could use this method to obtain a connected cellular network
5145 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5146 * radio to consume additional power. Or, an application could inform the system that it wants
5147 * a network supporting sending MMSes and have the system let it know about the currently best
5148 * MMS-supporting network through the provided {@link NetworkCallback}.
5149 *
5150 * <p>The status of the request can be followed by listening to the various callbacks described
5151 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5152 * used to direct traffic to the network (although accessing some networks may be subject to
5153 * holding specific permissions). Callers will learn about the specific characteristics of the
5154 * network through
5155 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5156 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5157 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5158 * matching the request at any given time; therefore when a better network matching the request
5159 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5160 * with the new network after which no further updates are given about the previously-best
5161 * network, unless it becomes the best again at some later time. All callbacks are invoked
5162 * in order on the same thread, which by default is a thread created by the framework running
5163 * in the app.
5164 *
5165 * <p>This{@link NetworkRequest} will live until released via
5166 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5167 * which point the system may let go of the network at any time.
5168 *
5169 * <p>It is presently unsupported to request a network with mutable
5170 * {@link NetworkCapabilities} such as
5171 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5172 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5173 * as these {@code NetworkCapabilities} represent states that a particular
5174 * network may never attain, and whether a network will attain these states
5175 * is unknown prior to bringing up the network so the framework does not
5176 * know how to go about satisfying a request with these capabilities.
5177 *
5178 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5179 * number of outstanding requests to 100 per app (identified by their UID), shared with
5180 * all variants of this method, of {@link #registerNetworkCallback} as well as
5181 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5182 * Requesting a network with this method will count toward this limit. If this limit is
5183 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5184 * make sure to unregister the callbacks with
5185 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5186 *
5187 * @param request {@link NetworkRequest} describing this request.
5188 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5189 * If null, the callback is invoked on the default internal Handler.
5190 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5191 * the callback must not be shared - it uniquely specifies this request.
5192 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5193 * @throws SecurityException if missing the appropriate permissions.
5194 * @throws RuntimeException if the app already has too many callbacks registered.
5195 *
5196 * @hide
5197 */
5198 @SystemApi(client = MODULE_LIBRARIES)
5199 @SuppressLint("ExecutorRegistration")
5200 @RequiresPermission(anyOf = {
5201 android.Manifest.permission.NETWORK_SETTINGS,
5202 android.Manifest.permission.NETWORK_STACK,
5203 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5204 })
5205 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaif4bc12f2021-03-09 20:49:48 +08005206 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Lai23568a42021-01-19 11:10:56 +00005207 final NetworkCapabilities nc = request.networkCapabilities;
5208 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaif4bc12f2021-03-09 20:49:48 +08005209 TYPE_NONE, new CallbackHandler(handler));
Junyu Lai23568a42021-01-19 11:10:56 +00005210 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005211
5212 /**
James Mattis6e6fabf2021-01-10 14:24:24 -08005213 * Used by automotive devices to set the network preferences used to direct traffic at an
5214 * application level as per the given OemNetworkPreferences. An example use-case would be an
5215 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5216 * vehicle via a particular network.
5217 *
5218 * Calling this will overwrite the existing preference.
5219 *
5220 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5221 * @param executor the executor on which listener will be invoked.
5222 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5223 * communicate completion of setOemNetworkPreference(). This will only be
5224 * called once upon successful completion of setOemNetworkPreference().
5225 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5226 * @throws SecurityException if missing the appropriate permissions.
5227 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005228 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005229 */
James Mattis7a253542021-01-26 16:23:52 -08005230 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005231 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005232 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005233 @Nullable @CallbackExecutor final Executor executor,
Chalard Jeancc9ad152021-03-03 16:37:13 +09005234 @Nullable final Runnable listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08005235 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5236 if (null != listener) {
5237 Objects.requireNonNull(executor, "Executor must be non-null");
5238 }
Chalard Jeancc9ad152021-03-03 16:37:13 +09005239 final IOnCompleteListener listenerInternal = listener == null ? null :
5240 new IOnCompleteListener.Stub() {
James Mattis6e6fabf2021-01-10 14:24:24 -08005241 @Override
5242 public void onComplete() {
Chalard Jeancc9ad152021-03-03 16:37:13 +09005243 executor.execute(listener::run);
James Mattis6e6fabf2021-01-10 14:24:24 -08005244 }
5245 };
5246
5247 try {
5248 mService.setOemNetworkPreference(preference, listenerInternal);
5249 } catch (RemoteException e) {
5250 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5251 throw e.rethrowFromSystemServer();
5252 }
5253 }
lucaslin1a6095c2021-03-12 00:46:33 +08005254
Chalard Jean03433052021-02-25 17:23:40 +09005255 /**
5256 * Request that a user profile is put by default on a network matching a given preference.
5257 *
5258 * See the documentation for the individual preferences for a description of the supported
5259 * behaviors.
5260 *
5261 * @param profile the profile concerned.
5262 * @param preference the preference for this profile.
5263 * @param executor an executor to execute the listener on. Optional if listener is null.
5264 * @param listener an optional listener to listen for completion of the operation.
5265 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5266 * @throws SecurityException if missing the appropriate permissions.
5267 * @hide
5268 */
Chalard Jeancc9ad152021-03-03 16:37:13 +09005269 // This function is for establishing per-profile default networking and can only be called by
5270 // the device policy manager, running as the system server. It would make no sense to call it
5271 // on a context for a user because it does not establish a setting on behalf of a user, rather
5272 // it establishes a setting for a user on behalf of the DPM.
5273 @SuppressLint({"UserHandle"})
5274 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09005275 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5276 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5277 @ProfileNetworkPreference final int preference,
5278 @Nullable @CallbackExecutor final Executor executor,
5279 @Nullable final Runnable listener) {
5280 if (null != listener) {
5281 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5282 }
5283 final IOnCompleteListener proxy;
5284 if (null == listener) {
5285 proxy = null;
5286 } else {
5287 proxy = new IOnCompleteListener.Stub() {
5288 @Override
5289 public void onComplete() {
5290 executor.execute(listener::run);
5291 }
5292 };
5293 }
5294 try {
5295 mService.setProfileNetworkPreference(profile, preference, proxy);
5296 } catch (RemoteException e) {
5297 throw e.rethrowFromSystemServer();
5298 }
5299 }
5300
lucaslin1a6095c2021-03-12 00:46:33 +08005301 // The first network ID of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005302 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin1a6095c2021-03-12 00:46:33 +08005303 // The network ID range of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005304 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin1a6095c2021-03-12 00:46:33 +08005305
5306 /**
5307 * Get the network ID range reserved for IPSec tunnel interfaces.
5308 *
5309 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5310 * @hide
5311 */
5312 @SystemApi(client = MODULE_LIBRARIES)
5313 @NonNull
5314 public static Range<Integer> getIpSecNetIdRange() {
5315 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5316 }
lucaslin50205af2021-03-12 16:11:27 +08005317
5318 /**
5319 * Get private DNS mode from settings.
5320 *
lucaslin73c98602021-03-17 14:53:35 +08005321 * @param context The Context to query the private DNS mode from settings.
lucaslin50205af2021-03-12 16:11:27 +08005322 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5323 *
5324 * @hide
5325 */
5326 @SystemApi(client = MODULE_LIBRARIES)
5327 @NonNull
5328 @PrivateDnsMode
lucaslinacd3ded2021-03-16 17:11:14 +08005329 public static String getPrivateDnsMode(@NonNull Context context) {
5330 final ContentResolver cr = context.getContentResolver();
lucaslin50205af2021-03-12 16:11:27 +08005331 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5332 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5333 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5334 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5335 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5336 return mode;
5337 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005338}