blob: 417246318a79e04777bfdd1098d6989a91f87bc6 [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;
Junyu Lai23568a42021-01-19 11:10:56 +000019import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaid1a78162021-01-11 16:53:38 +080020import static android.net.NetworkRequest.Type.LISTEN;
21import static android.net.NetworkRequest.Type.REQUEST;
junyulai6b0a6a22021-03-05 15:51:17 +080022import static android.net.NetworkRequest.Type.TRACK_BEST;
junyulaid1a78162021-01-11 16:53:38 +080023import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +090024import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Bright60f02ed2020-06-15 16:10:01 -070025import static android.net.QosCallback.QosCallbackRegistrationException;
lucaslin8f026612021-03-12 17:56:09 +080026import static android.provider.Settings.Global.PRIVATE_DNS_DEFAULT_MODE;
27import static android.provider.Settings.Global.PRIVATE_DNS_MODE;
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;
lucaslin8f026612021-03-12 17:56:09 +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 Satayev0e45d782019-12-10 17:47:52 +000041import android.compat.annotation.UnsupportedAppUsage;
lucaslin8f026612021-03-12 17:56:09 +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;
markchiencc1bc1b2020-01-20 19:31:56 +080047import android.net.TetheringManager.StartTetheringCallback;
markchieneeea0be2020-01-21 13:11:06 +080048import android.net.TetheringManager.TetheringEventCallback;
markchiencc1bc1b2020-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;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080065import android.os.ServiceManager;
Hugo Benichi145e3792017-05-11 13:16:17 +090066import android.os.ServiceSpecificException;
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;
lucaslin8f026612021-03-12 17:56:09 +080070import android.text.TextUtils;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080071import android.util.ArrayMap;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070072import android.util.Log;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090073import android.util.Range;
Erik Kline50068e52017-01-26 18:08:28 +090074import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080075
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +090076import com.android.connectivity.aidl.INetworkAgent;
markchieneeea0be2020-01-21 13:11:06 +080077import com.android.internal.annotations.GuardedBy;
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +000078import com.android.internal.util.Preconditions;
Hugo Benichi45a49542017-03-06 09:17:06 +090079import com.android.internal.util.Protocol;
Robert Greenwalt3d6c9582014-05-21 20:04:36 -070080
Paul Jensen99c36662014-08-27 12:38:45 -040081import libcore.net.event.NetworkEventDispatcher;
82
junyulai61143782019-03-04 22:45:36 +080083import java.io.IOException;
84import java.io.UncheckedIOException;
Felipe Lemed16384b2016-01-22 09:44:57 -080085import java.lang.annotation.Retention;
86import java.lang.annotation.RetentionPolicy;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090087import java.net.DatagramSocket;
Jeremy Klein04863332015-12-28 15:11:58 -080088import java.net.InetAddress;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -070089import java.net.InetSocketAddress;
junyulaic7ea1242019-01-08 20:04:33 +080090import java.net.Socket;
Hugo Benichi45a49542017-03-06 09:17:06 +090091import java.util.ArrayList;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090092import java.util.Collection;
Jeremy Klein04863332015-12-28 15:11:58 -080093import java.util.HashMap;
Hugo Benichi45a49542017-03-06 09:17:06 +090094import java.util.List;
95import java.util.Map;
markchieneeea0be2020-01-21 13:11:06 +080096import java.util.Objects;
junyulaia86defc2018-12-27 17:25:29 +080097import java.util.concurrent.Executor;
junyulai9f872232019-01-16 20:23:34 +080098import java.util.concurrent.ExecutorService;
99import java.util.concurrent.Executors;
100import java.util.concurrent.RejectedExecutionException;
Jeremy Klein04863332015-12-28 15:11:58 -0800101
The Android Open Source Project28527d22009-03-03 19:31:44 -0800102/**
103 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600104 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800105 * <p>
106 * The primary responsibilities of this class are to:
107 * <ol>
108 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
109 * <li>Send broadcast intents when network connectivity changes</li>
110 * <li>Attempt to "fail over" to another network when connectivity to a network
111 * is lost</li>
112 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
113 * state of the available networks</li>
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700114 * <li>Provide an API that allows applications to request and select networks for their data
115 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800116 * </ol>
117 */
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600118@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700119public class ConnectivityManager {
120 private static final String TAG = "ConnectivityManager";
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +0900121 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700122
The Android Open Source Project28527d22009-03-03 19:31:44 -0800123 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700124 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800125 * been established or lost. The NetworkInfo for the affected network is
126 * sent as an extra; it should be consulted to see what kind of
127 * connectivity event occurred.
128 * <p/>
Mark Lue1682a02016-12-05 10:57:55 -0800129 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
130 * broadcast if they declare the broadcast receiver in their manifest. Apps
131 * will still receive broadcasts if they register their
132 * {@link android.content.BroadcastReceiver} with
133 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
134 * and that context is still valid.
135 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800136 * If this is a connection that was the result of failing over from a
137 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
138 * set to true.
139 * <p/>
140 * For a loss of connectivity, if the connectivity manager is attempting
141 * to connect (or has already connected) to another network, the
142 * NetworkInfo for the new network is also passed as an extra. This lets
143 * any receivers of the broadcast know that they should not necessarily
144 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt26744a52013-02-15 10:56:35 -0800145 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800146 * the failover attempt succeeded (and so there is still overall data
147 * connectivity), or that the failover attempt failed, meaning that all
148 * connectivity has been lost.
149 * <p/>
150 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
151 * is set to {@code true} if there are no connected networks at all.
Chalard Jeanae2424a2018-02-10 05:33:50 +0900152 *
153 * @deprecated apps should use the more versatile {@link #requestNetwork},
154 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
155 * functions instead for faster and more detailed updates about the network
156 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800158 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jeanae2424a2018-02-10 05:33:50 +0900159 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800160 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700161
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162 /**
Paul Jensened4d55c2015-02-27 22:55:47 -0500163 * The device has connected to a network that has presented a captive
164 * portal, which is blocking Internet connectivity. The user was presented
165 * with a notification that network sign in is required,
166 * and the user invoked the notification's action indicating they
Paul Jensen4173cce2015-05-22 10:50:39 -0400167 * desire to sign in to the network. Apps handling this activity should
Paul Jensened4d55c2015-02-27 22:55:47 -0500168 * facilitate signing in to the network. This action includes a
169 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
170 * the network presenting the captive portal; all communication with the
171 * captive portal must be done using this {@code Network} object.
172 * <p/>
Paul Jensen4173cce2015-05-22 10:50:39 -0400173 * This activity includes a {@link CaptivePortal} extra named
174 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
175 * outcomes of the captive portal sign in to the system:
176 * <ul>
177 * <li> When the app handling this action believes the user has signed in to
178 * the network and the captive portal has been dismissed, the app should
179 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
180 * reevaluate the network. If reevaluation finds the network no longer
181 * subject to a captive portal, the network may become the default active
Chalard Jean73d9db72018-06-04 16:52:49 +0900182 * data network.</li>
Paul Jensen4173cce2015-05-22 10:50:39 -0400183 * <li> When the app handling this action believes the user explicitly wants
Paul Jensened4d55c2015-02-27 22:55:47 -0500184 * to ignore the captive portal and the network, the app should call
Paul Jensen4173cce2015-05-22 10:50:39 -0400185 * {@link CaptivePortal#ignoreNetwork}. </li>
186 * </ul>
Paul Jensened4d55c2015-02-27 22:55:47 -0500187 */
188 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
189 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
190
191 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800192 * The lookup key for a {@link NetworkInfo} object. Retrieve with
193 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700194 *
Chalard Jeancc47b522019-01-11 16:47:53 +0900195 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
196 * can't accurately represent modern network characteristics.
197 * Please obtain information about networks from the {@link NetworkCapabilities}
198 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800199 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700200 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800201 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700202
The Android Open Source Project28527d22009-03-03 19:31:44 -0800203 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700204 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700205 *
206 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeancc47b522019-01-11 16:47:53 +0900207 * @deprecated The network type is not rich enough to represent the characteristics
208 * of modern networks. Please use {@link NetworkCapabilities} instead,
209 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700210 */
Chalard Jeancc47b522019-01-11 16:47:53 +0900211 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700212 public static final String EXTRA_NETWORK_TYPE = "networkType";
213
214 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800215 * The lookup key for a boolean that indicates whether a connect event
216 * is for a network to which the connectivity manager was failing over
217 * following a disconnect on another network.
218 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai5c2f6262018-12-13 12:47:51 +0800219 *
220 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800221 */
junyulai5c2f6262018-12-13 12:47:51 +0800222 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800223 public static final String EXTRA_IS_FAILOVER = "isFailover";
224 /**
225 * The lookup key for a {@link NetworkInfo} object. This is supplied when
226 * there is another network that it may be possible to connect to. Retrieve with
227 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800228 *
229 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230 */
junyulai5c2f6262018-12-13 12:47:51 +0800231 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
233 /**
234 * The lookup key for a boolean that indicates whether there is a
235 * complete lack of connectivity, i.e., no network is available.
236 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
237 */
238 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
239 /**
240 * The lookup key for a string that indicates why an attempt to connect
241 * to a network failed. The string has no particular structure. It is
242 * intended to be used in notifications presented to users. Retrieve
243 * it with {@link android.content.Intent#getStringExtra(String)}.
244 */
245 public static final String EXTRA_REASON = "reason";
246 /**
247 * The lookup key for a string that provides optionally supplied
248 * extra information about the network state. The information
249 * may be passed up from the lower networking layers, and its
250 * meaning may be specific to a particular network type. Retrieve
251 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800252 *
253 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800254 */
junyulai5c2f6262018-12-13 12:47:51 +0800255 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800256 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700257 /**
258 * The lookup key for an int that provides information about
259 * our connection to the internet at large. 0 indicates no connection,
260 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700261 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700262 * {@hide}
263 */
264 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800265 /**
Paul Jensen4173cce2015-05-22 10:50:39 -0400266 * The lookup key for a {@link CaptivePortal} object included with the
267 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
268 * object can be used to either indicate to the system that the captive
269 * portal has been dismissed or that the user does not want to pursue
270 * signing in to captive portal. Retrieve it with
271 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensened4d55c2015-02-27 22:55:47 -0500272 */
Paul Jensen4173cce2015-05-22 10:50:39 -0400273 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist0f3b4442015-09-22 15:54:32 -0700274
275 /**
276 * Key for passing a URL to the captive portal login activity.
277 */
278 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
279
Paul Jensened4d55c2015-02-27 22:55:47 -0500280 /**
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900281 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
282 * portal login activity.
283 * {@hide}
284 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900285 @SystemApi
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900286 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
287 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
288
289 /**
Hugo Benichidce21c52016-12-14 08:23:40 +0900290 * Key for passing a user agent string to the captive portal login activity.
291 * {@hide}
292 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900293 @SystemApi
Hugo Benichidce21c52016-12-14 08:23:40 +0900294 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
295 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
296
297 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700298 * Broadcast action to indicate the change of data activity status
299 * (idle or active) on a network in a recent period.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800300 * The network becomes active when data transmission is started, or
301 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700302 * {@hide}
303 */
304 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean73d9db72018-06-04 16:52:49 +0900305 public static final String ACTION_DATA_ACTIVITY_CHANGE =
306 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700307 /**
308 * The lookup key for an enum that indicates the network device type on which this data activity
309 * change happens.
310 * {@hide}
311 */
312 public static final String EXTRA_DEVICE_TYPE = "deviceType";
313 /**
314 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
315 * it is actively sending or receiving data and {@code false} means it is idle.
316 * {@hide}
317 */
318 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma601fba92014-03-12 18:42:23 -0700319 /**
320 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
321 * {@hide}
322 */
323 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700324
325 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800326 * Broadcast Action: The setting for background data usage has changed
327 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
328 * <p>
329 * If an application uses the network in the background, it should listen
330 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700331 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800332 * <p>
333 *
334 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
335 * of background data depends on several combined factors, and
336 * this broadcast is no longer sent. Instead, when background
337 * data is unavailable, {@link #getActiveNetworkInfo()} will now
338 * appear disconnected. During first boot after a platform
339 * upgrade, this broadcast will be sent once if
340 * {@link #getBackgroundDataSetting()} was {@code false} before
341 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800342 */
343 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800344 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800345 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
346 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
347
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700348 /**
349 * Broadcast Action: The network connection may not be good
350 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
351 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
352 * the network and it's condition.
353 * @hide
354 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800355 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100356 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700357 public static final String INET_CONDITION_ACTION =
358 "android.net.conn.INET_CONDITION_ACTION";
359
Robert Greenwalt2034b912009-08-12 16:08:25 -0700360 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800361 * Broadcast Action: A tetherable connection has come or gone.
362 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline449ccfe2017-04-17 16:47:23 +0900363 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
364 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt26744a52013-02-15 10:56:35 -0800365 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
366 * the current state of tethering. Each include a list of
367 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800368 * @hide
369 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800370 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood5a09a712020-11-04 09:29:36 +0000371 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800372 public static final String ACTION_TETHER_STATE_CHANGED =
markchien1f523702019-12-25 19:40:32 +0800373 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800374
375 /**
376 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800377 * gives a String[] listing all the interfaces configured for
378 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800379 */
Mathew Inwood5a09a712020-11-04 09:29:36 +0000380 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800381 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800382
383 /**
384 * @hide
Erik Kline449ccfe2017-04-17 16:47:23 +0900385 * gives a String[] listing all the interfaces currently in local-only
386 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800387 */
markchien1f523702019-12-25 19:40:32 +0800388 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline449ccfe2017-04-17 16:47:23 +0900389
390 /**
391 * @hide
392 * gives a String[] listing all the interfaces currently tethered
393 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
394 */
Mathew Inwood5a09a712020-11-04 09:29:36 +0000395 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800396 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800397
398 /**
399 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800400 * gives a String[] listing all the interfaces we tried to tether and
401 * failed. Use {@link #getLastTetherError} to find the error code
402 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800403 */
Mathew Inwood5a09a712020-11-04 09:29:36 +0000404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800405 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800406
407 /**
Russell Brenner4774b022013-02-12 10:03:14 -0800408 * Broadcast Action: The captive portal tracker has finished its test.
409 * Sent only while running Setup Wizard, in lieu of showing a user
410 * notification.
411 * @hide
412 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800413 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner4774b022013-02-12 10:03:14 -0800414 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
415 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
416 /**
417 * The lookup key for a boolean that indicates whether a captive portal was detected.
418 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
419 * @hide
420 */
421 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
422
423 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900424 * Action used to display a dialog that asks the user whether to connect to a network that is
425 * not validated. This intent is used to start the dialog in settings via startActivity.
426 *
427 * @hide
428 */
429 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
430
431 /**
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900432 * Action used to display a dialog that asks the user whether to avoid a network that is no
433 * longer validated. This intent is used to start the dialog in settings via startActivity.
434 *
435 * @hide
436 */
437 public static final String ACTION_PROMPT_LOST_VALIDATION =
438 "android.net.conn.PROMPT_LOST_VALIDATION";
439
440 /**
lucaslin25a50472019-03-12 13:08:03 +0800441 * Action used to display a dialog that asks the user whether to stay connected to a network
442 * that has not validated. This intent is used to start the dialog in settings via
443 * startActivity.
444 *
445 * @hide
446 */
447 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
448 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
449
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 */
markchieneeea0be2020-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 */
markchieneeea0be2020-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 */
markchieneeea0be2020-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 */
markchieneeea0be2020-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 */
markchieneeea0be2020-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 Jeane5b9e822020-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 */
lucaslin8f026612021-03-12 17:56:09 +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 */
lucaslin8f026612021-03-12 17:56:09 +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 */
lucaslin8f026612021-03-12 17:56:09 +0800820 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900821 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin8f026612021-03-12 17:56:09 +0800822
823 /** @hide */
824 @Retention(RetentionPolicy.SOURCE)
825 @StringDef(value = {
826 PRIVATE_DNS_MODE_OFF,
827 PRIVATE_DNS_MODE_OPPORTUNISTIC,
828 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
829 })
830 public @interface PrivateDnsMode {}
Erik Kline1ecdd962017-10-30 15:29:44 +0900831
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900832 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700833 private final IConnectivityManager mService;
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +0900834
Paul Jensen12131352014-12-10 15:12:18 -0500835 /**
836 * A kludge to facilitate static access where a Context pointer isn't available, like in the
837 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
838 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
839 * methods that take a Context argument.
840 */
841 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800842
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +0900843 private final Context mContext;
844
Felipe Lemed16384b2016-01-22 09:44:57 -0800845 private INetworkPolicyManager mNPManager;
Amos Bianchiddadca42020-03-04 11:07:38 -0800846 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800847
Robert Greenwalt26744a52013-02-15 10:56:35 -0800848 /**
849 * Tests if a given integer represents a valid network type.
850 * @param networkType the type to be tested
851 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen1c9f2e42015-05-06 10:42:25 -0400852 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
853 * validate a network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800854 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700855 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700856 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900857 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800858 }
859
Robert Greenwalt26744a52013-02-15 10:56:35 -0800860 /**
861 * Returns a non-localized string representing a given network type.
862 * ONLY used for debugging output.
863 * @param type the type needing naming
864 * @return a String for the given type, or a string version of the type ("87")
865 * if no name is known.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900866 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800867 * {@hide}
868 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900869 @Deprecated
Mathew Inwood5a09a712020-11-04 09:29:36 +0000870 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700871 public static String getNetworkTypeName(int type) {
872 switch (type) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900873 case TYPE_NONE:
874 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700875 case TYPE_MOBILE:
876 return "MOBILE";
877 case TYPE_WIFI:
878 return "WIFI";
879 case TYPE_MOBILE_MMS:
880 return "MOBILE_MMS";
881 case TYPE_MOBILE_SUPL:
882 return "MOBILE_SUPL";
883 case TYPE_MOBILE_DUN:
884 return "MOBILE_DUN";
885 case TYPE_MOBILE_HIPRI:
886 return "MOBILE_HIPRI";
887 case TYPE_WIMAX:
888 return "WIMAX";
889 case TYPE_BLUETOOTH:
890 return "BLUETOOTH";
891 case TYPE_DUMMY:
892 return "DUMMY";
893 case TYPE_ETHERNET:
894 return "ETHERNET";
895 case TYPE_MOBILE_FOTA:
896 return "MOBILE_FOTA";
897 case TYPE_MOBILE_IMS:
898 return "MOBILE_IMS";
899 case TYPE_MOBILE_CBS:
900 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700901 case TYPE_WIFI_P2P:
902 return "WIFI_P2P";
Wink Saville70dbdcc2013-07-29 15:00:57 -0700903 case TYPE_MOBILE_IA:
904 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -0700905 case TYPE_MOBILE_EMERGENCY:
906 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -0500907 case TYPE_PROXY:
908 return "PROXY";
Erik Klineb1ff7002014-11-19 17:23:41 +0900909 case TYPE_VPN:
910 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700911 default:
912 return Integer.toString(type);
913 }
914 }
915
Robert Greenwalt26744a52013-02-15 10:56:35 -0800916 /**
Aaron Huang925d09b2020-06-27 07:18:23 +0800917 * @hide
918 * TODO: Expose for SystemServer when becomes a module.
919 */
920 public void systemReady() {
921 try {
922 mService.systemReady();
923 } catch (RemoteException e) {
924 throw e.rethrowFromSystemServer();
925 }
926 }
927
928 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800929 * Checks if a given type uses the cellular data connection.
930 * This should be replaced in the future by a network property.
931 * @param networkType the type to check
932 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +0900933 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800934 * {@hide}
935 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900936 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900937 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700938 public static boolean isNetworkTypeMobile(int networkType) {
939 switch (networkType) {
940 case TYPE_MOBILE:
941 case TYPE_MOBILE_MMS:
942 case TYPE_MOBILE_SUPL:
943 case TYPE_MOBILE_DUN:
944 case TYPE_MOBILE_HIPRI:
945 case TYPE_MOBILE_FOTA:
946 case TYPE_MOBILE_IMS:
947 case TYPE_MOBILE_CBS:
Wink Saville70dbdcc2013-07-29 15:00:57 -0700948 case TYPE_MOBILE_IA:
Ram201d45f2014-06-26 11:03:44 -0700949 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700950 return true;
951 default:
952 return false;
953 }
954 }
955
Robert Greenwalt26744a52013-02-15 10:56:35 -0800956 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700957 * Checks if the given network type is backed by a Wi-Fi radio.
958 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900959 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700960 * @hide
961 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900962 @Deprecated
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700963 public static boolean isNetworkTypeWifi(int networkType) {
964 switch (networkType) {
965 case TYPE_WIFI:
966 case TYPE_WIFI_P2P:
967 return true;
968 default:
969 return false;
970 }
971 }
972
973 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800974 * Specifies the preferred network type. When the device has more
975 * than one type available the preferred network type will be used.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800976 *
977 * @param preference the network type to prefer over all others. It is
978 * unspecified what happens to the old preferred network in the
979 * overall ordering.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700980 * @deprecated Functionality has been removed as it no longer makes sense,
981 * with many more than two networks - we'd need an array to express
982 * preference. Instead we use dynamic network properties of
983 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800984 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700985 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800986 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800987 }
988
Robert Greenwalt26744a52013-02-15 10:56:35 -0800989 /**
990 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800991 *
992 * @return an integer representing the preferred network type
993 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700994 * @deprecated Functionality has been removed as it no longer makes sense,
995 * with many more than two networks - we'd need an array to express
996 * preference. Instead we use dynamic network properties of
997 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800998 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700999 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001000 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001001 public int getNetworkPreference() {
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001002 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001003 }
1004
Scott Mainf58b7d82011-10-06 19:02:28 -07001005 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001006 * Returns details about the currently active default data network. When
1007 * connected, this network is the default route for outgoing connections.
1008 * You should always check {@link NetworkInfo#isConnected()} before initiating
1009 * network traffic. This may return {@code null} when there is no default
1010 * network.
Chalard Jean7c85ba42018-03-29 17:45:24 +09001011 * Note that if the default network is a VPN, this method will return the
1012 * NetworkInfo for one of its underlying networks instead, or null if the
1013 * VPN agent did not specify any. Apps interested in learning about VPNs
1014 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001015 *
1016 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001017 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001018 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001019 */
junyulai5c2f6262018-12-13 12:47:51 +08001020 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001021 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001022 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001023 public NetworkInfo getActiveNetworkInfo() {
1024 try {
1025 return mService.getActiveNetworkInfo();
1026 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001027 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001028 }
1029 }
1030
Robert Greenwalt26744a52013-02-15 10:56:35 -08001031 /**
Paul Jensenc2569432015-02-13 14:18:39 -05001032 * Returns a {@link Network} object corresponding to the currently active
1033 * default data network. In the event that the current active default data
1034 * network disconnects, the returned {@code Network} object will no longer
1035 * be usable. This will return {@code null} when there is no default
1036 * network.
1037 *
1038 * @return a {@link Network} object for the current default network or
1039 * {@code null} if no default network is currently active
Paul Jensenc2569432015-02-13 14:18:39 -05001040 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001041 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001042 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001043 public Network getActiveNetwork() {
1044 try {
1045 return mService.getActiveNetwork();
1046 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001047 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001048 }
1049 }
1050
1051 /**
Robin Leeda4d2e22016-03-24 12:07:00 +00001052 * Returns a {@link Network} object corresponding to the currently active
1053 * default data network for a specific UID. In the event that the default data
1054 * network disconnects, the returned {@code Network} object will no longer
1055 * be usable. This will return {@code null} when there is no default
1056 * network for the UID.
Robin Leeda4d2e22016-03-24 12:07:00 +00001057 *
1058 * @return a {@link Network} object for the current default network for the
1059 * given UID or {@code null} if no default network is currently active
1060 *
1061 * @hide
1062 */
paulhud70b7dd2019-08-12 16:25:11 +08001063 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001064 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001065 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001066 return getActiveNetworkForUid(uid, false);
1067 }
1068
1069 /** {@hide} */
1070 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001071 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001072 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001073 } catch (RemoteException e) {
1074 throw e.rethrowFromSystemServer();
1075 }
1076 }
1077
1078 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001079 * Adds or removes a requirement for given UID ranges to use the VPN.
1080 *
1081 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1082 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1083 * otherwise have permission to bypass the VPN (e.g., because they have the
1084 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1085 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1086 * set to {@code false}, a previously-added restriction is removed.
1087 * <p>
1088 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1089 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1090 * remove a previously-added range, the exact range must be removed as is.
1091 * <p>
1092 * The changes are applied asynchronously and may not have been applied by the time the method
1093 * returns. Apps will be notified about any changes that apply to them via
1094 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1095 * effect.
1096 * <p>
1097 * This method should be called only by the VPN code.
1098 *
1099 * @param ranges the UID ranges to restrict
1100 * @param requireVpn whether the specified UID ranges must use a VPN
1101 *
1102 * TODO: expose as @SystemApi.
1103 * @hide
1104 */
1105 @RequiresPermission(anyOf = {
1106 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1107 android.Manifest.permission.NETWORK_STACK})
1108 public void setRequireVpnForUids(boolean requireVpn,
1109 @NonNull Collection<Range<Integer>> ranges) {
1110 Objects.requireNonNull(ranges);
1111 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1112 // This method is not necessarily expected to be used outside the system server, so
1113 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1114 // stack process, or by tests.
1115 UidRange[] rangesArray = new UidRange[ranges.size()];
1116 int index = 0;
1117 for (Range<Integer> range : ranges) {
1118 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1119 }
1120 try {
1121 mService.setRequireVpnForUids(requireVpn, rangesArray);
1122 } catch (RemoteException e) {
1123 throw e.rethrowFromSystemServer();
1124 }
1125 }
1126
1127 /**
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001128 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1129 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1130 * but is still supported for backwards compatibility.
1131 * <p>
1132 * This type of VPN is assumed always to use the system default network, and must always declare
1133 * exactly one underlying network, which is the network that was the default when the VPN
1134 * connected.
1135 * <p>
1136 * Calling this method with {@code true} enables legacy behaviour, specifically:
1137 * <ul>
1138 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1139 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1140 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1141 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1142 * underlying the VPN.</li>
1143 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1144 * similarly replaced by the VPN network state.</li>
1145 * <li>Information on current network interfaces passed to NetworkStatsService will not
1146 * include any VPN interfaces.</li>
1147 * </ul>
1148 *
1149 * @param enabled whether legacy lockdown VPN is enabled or disabled
1150 *
1151 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1152 *
1153 * @hide
1154 */
1155 @RequiresPermission(anyOf = {
1156 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1157 android.Manifest.permission.NETWORK_SETTINGS})
1158 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1159 try {
1160 mService.setLegacyLockdownVpnEnabled(enabled);
1161 } catch (RemoteException e) {
1162 throw e.rethrowFromSystemServer();
1163 }
1164 }
1165
1166 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001167 * Returns details about the currently active default data network
1168 * for a given uid. This is for internal use only to avoid spying
1169 * other apps.
1170 *
1171 * @return a {@link NetworkInfo} object for the current default network
1172 * for the given uid or {@code null} if no default network is
1173 * available for the specified uid.
1174 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001175 * {@hide}
1176 */
paulhud70b7dd2019-08-12 16:25:11 +08001177 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwood5a09a712020-11-04 09:29:36 +00001178 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001179 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001180 return getActiveNetworkInfoForUid(uid, false);
1181 }
1182
1183 /** {@hide} */
1184 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001185 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001186 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001187 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001188 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001189 }
1190 }
1191
Robert Greenwalt26744a52013-02-15 10:56:35 -08001192 /**
1193 * Returns connection status information about a particular
1194 * network type.
1195 *
1196 * @param networkType integer specifying which networkType in
1197 * which you're interested.
1198 * @return a {@link NetworkInfo} object for the requested
1199 * network type or {@code null} if the type is not
Chalard Jean7c85ba42018-03-29 17:45:24 +09001200 * supported by the device. If {@code networkType} is
1201 * TYPE_VPN and a VPN is active for the calling app,
1202 * then this method will try to return one of the
1203 * underlying networks for the VPN or null if the
1204 * VPN agent didn't specify any.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001205 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001206 * @deprecated This method does not support multiple connected networks
1207 * of the same type. Use {@link #getAllNetworks} and
1208 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001209 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001210 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001211 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001212 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001213 public NetworkInfo getNetworkInfo(int networkType) {
1214 try {
1215 return mService.getNetworkInfo(networkType);
1216 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001217 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001218 }
1219 }
1220
Robert Greenwalt26744a52013-02-15 10:56:35 -08001221 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001222 * Returns connection status information about a particular
1223 * Network.
1224 *
1225 * @param network {@link Network} specifying which network
1226 * in which you're interested.
1227 * @return a {@link NetworkInfo} object for the requested
1228 * network or {@code null} if the {@code Network}
1229 * is not valid.
junyulai5c2f6262018-12-13 12:47:51 +08001230 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001231 */
junyulai5c2f6262018-12-13 12:47:51 +08001232 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001233 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001234 @Nullable
1235 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001236 return getNetworkInfoForUid(network, Process.myUid(), false);
1237 }
1238
1239 /** {@hide} */
1240 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001241 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001242 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001243 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001244 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001245 }
1246 }
1247
1248 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001249 * Returns connection status information about all network
1250 * types supported by the device.
1251 *
1252 * @return an array of {@link NetworkInfo} objects. Check each
1253 * {@link NetworkInfo#getType} for which type each applies.
1254 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001255 * @deprecated This method does not support multiple connected networks
1256 * of the same type. Use {@link #getAllNetworks} and
1257 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001258 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001259 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001260 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001261 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001262 public NetworkInfo[] getAllNetworkInfo() {
1263 try {
1264 return mService.getAllNetworkInfo();
1265 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001266 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001267 }
1268 }
1269
Robert Greenwalt26744a52013-02-15 10:56:35 -08001270 /**
junyulai57840802021-03-03 12:09:05 +08001271 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1272 * connected.
1273 * @hide
1274 */
1275 @SystemApi(client = MODULE_LIBRARIES)
1276 @RequiresPermission(anyOf = {
1277 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1278 android.Manifest.permission.NETWORK_STACK,
1279 android.Manifest.permission.NETWORK_SETTINGS})
1280 @NonNull
1281 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1282 try {
1283 return mService.getAllNetworkStateSnapshot();
1284 } catch (RemoteException e) {
1285 throw e.rethrowFromSystemServer();
1286 }
1287 }
1288
1289 /**
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001290 * Returns the {@link Network} object currently serving a given type, or
1291 * null if the given type is not connected.
1292 *
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001293 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04001294 * @deprecated This method does not support multiple connected networks
1295 * of the same type. Use {@link #getAllNetworks} and
1296 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001297 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001298 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001299 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001300 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001301 public Network getNetworkForType(int networkType) {
1302 try {
1303 return mService.getNetworkForType(networkType);
1304 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001305 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001306 }
1307 }
1308
1309 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001310 * Returns an array of all {@link Network} currently tracked by the
1311 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001312 *
1313 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001314 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001315 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001316 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001317 public Network[] getAllNetworks() {
1318 try {
1319 return mService.getAllNetworks();
1320 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001321 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001322 }
1323 }
1324
1325 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001326 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001327 * the Networks that applications run by the given user will use by default.
1328 * @hide
1329 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001330 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001331 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1332 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001333 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001334 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001335 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001336 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001337 }
1338 }
1339
1340 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001341 * Returns the IP information for the current default network.
1342 *
1343 * @return a {@link LinkProperties} object describing the IP info
1344 * for the current default network, or {@code null} if there
1345 * is no current default network.
1346 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001347 * {@hide}
Chalard Jeancc47b522019-01-11 16:47:53 +09001348 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1349 * value of {@link #getActiveNetwork()} instead. In particular,
1350 * this method will return non-null LinkProperties even if the
1351 * app is blocked by policy from using this network.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001352 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001353 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-01-11 16:47:53 +09001354 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001355 public LinkProperties getActiveLinkProperties() {
1356 try {
1357 return mService.getActiveLinkProperties();
1358 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001359 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001360 }
1361 }
1362
Robert Greenwalt26744a52013-02-15 10:56:35 -08001363 /**
1364 * Returns the IP information for a given network type.
1365 *
1366 * @param networkType the network type of interest.
1367 * @return a {@link LinkProperties} object describing the IP info
1368 * for the given networkType, or {@code null} if there is
1369 * no current default network.
1370 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001371 * {@hide}
Paul Jensena8e6dc62015-03-18 12:23:02 -04001372 * @deprecated This method does not support multiple connected networks
1373 * of the same type. Use {@link #getAllNetworks},
1374 * {@link #getNetworkInfo(android.net.Network)}, and
1375 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001376 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001377 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001378 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001379 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001380 public LinkProperties getLinkProperties(int networkType) {
1381 try {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001382 return mService.getLinkPropertiesForType(networkType);
1383 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001384 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001385 }
1386 }
1387
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001388 /**
1389 * Get the {@link LinkProperties} for the given {@link Network}. This
1390 * will return {@code null} if the network is unknown.
1391 *
1392 * @param network The {@link Network} object identifying the network in question.
1393 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001394 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001395 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001396 @Nullable
1397 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001398 try {
1399 return mService.getLinkProperties(network);
1400 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001401 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001402 }
1403 }
1404
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001405 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001406 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001407 * will return {@code null} if the network is unknown.
1408 *
Roshan Pius7992afd2020-12-22 15:10:42 -08001409 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1410 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1411 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1412 * this location sensitive information (subject to app's location permissions) will be
1413 * noted by system. To include any location sensitive data in {@link TransportInfo},
1414 * use a {@link NetworkCallback} with
1415 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1416 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001417 * @param network The {@link Network} object identifying the network in question.
Roshan Pius7992afd2020-12-22 15:10:42 -08001418 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001419 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001420 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001421 @Nullable
1422 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001423 try {
Roshan Piusc97d8062020-12-17 14:53:09 -08001424 return mService.getNetworkCapabilities(
1425 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001426 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001427 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001428 }
1429 }
1430
Robert Greenwalt26744a52013-02-15 10:56:35 -08001431 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001432 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001433 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1434 * portal is present.
1435 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1436 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1437 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001438 * The system network validation may be using different strategies to detect captive portals,
1439 * so this method does not necessarily return a URL used by the system. It only returns a URL
1440 * that may be relevant for other components trying to detect captive portals.
paulhud70b7dd2019-08-12 16:25:11 +08001441 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001442 * @hide
paulhud70b7dd2019-08-12 16:25:11 +08001443 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1444 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001445 */
paulhud70b7dd2019-08-12 16:25:11 +08001446 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001447 @SystemApi
paulhud70b7dd2019-08-12 16:25:11 +08001448 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001449 public String getCaptivePortalServerUrl() {
1450 try {
1451 return mService.getCaptivePortalServerUrl();
1452 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001453 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001454 }
1455 }
1456
1457 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001458 * Tells the underlying networking system that the caller wants to
1459 * begin using the named feature. The interpretation of {@code feature}
1460 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001461 *
1462 * <p>This method requires the caller to hold either the
1463 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1464 * or the ability to modify system settings as determined by
1465 * {@link android.provider.Settings.System#canWrite}.</p>
1466 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001467 * @param networkType specifies which network the request pertains to
1468 * @param feature the name of the feature to be used
1469 * @return an integer value representing the outcome of the request.
1470 * The interpretation of this value is specific to each networking
1471 * implementation+feature combination, except that the value {@code -1}
1472 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001473 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001474 * @deprecated Deprecated in favor of the cleaner
1475 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001476 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001477 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001478 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001479 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001480 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001481 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001482 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001483 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1484 if (netCap == null) {
1485 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1486 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001487 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001488 }
1489
1490 NetworkRequest request = null;
1491 synchronized (sLegacyRequests) {
1492 LegacyRequest l = sLegacyRequests.get(netCap);
1493 if (l != null) {
1494 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1495 renewRequestLocked(l);
1496 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001497 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001498 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001499 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001500 }
1501 }
1502
1503 request = requestNetworkForFeatureLocked(netCap);
1504 }
1505 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001506 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001507 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001508 } else {
1509 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001510 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001511 }
1512 }
1513
1514 /**
1515 * Tells the underlying networking system that the caller is finished
1516 * using the named feature. The interpretation of {@code feature}
1517 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001518 *
1519 * <p>This method requires the caller to hold either the
1520 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1521 * or the ability to modify system settings as determined by
1522 * {@link android.provider.Settings.System#canWrite}.</p>
1523 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001524 * @param networkType specifies which network the request pertains to
1525 * @param feature the name of the feature that is no longer needed
1526 * @return an integer value representing the outcome of the request.
1527 * The interpretation of this value is specific to each networking
1528 * implementation+feature combination, except that the value {@code -1}
1529 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001530 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001531 * @deprecated Deprecated in favor of the cleaner
1532 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001533 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001534 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001535 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001536 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001537 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001538 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001539 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001540 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1541 if (netCap == null) {
1542 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1543 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001544 return -1;
1545 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001546
Paul Jensen034dea32014-12-17 10:39:34 -05001547 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001548 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001549 }
1550 return 1;
1551 }
1552
Mathew Inwood5a09a712020-11-04 09:29:36 +00001553 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001554 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1555 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001556 switch (feature) {
1557 case "enableCBS":
1558 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1559 case "enableDUN":
1560 case "enableDUNAlways":
1561 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1562 case "enableFOTA":
1563 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1564 case "enableHIPRI":
1565 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1566 case "enableIMS":
1567 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1568 case "enableMMS":
1569 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1570 case "enableSUPL":
1571 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1572 default:
1573 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001574 }
Erik Kline50068e52017-01-26 18:08:28 +09001575 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1576 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001577 }
1578 return null;
1579 }
1580
Robert Greenwalt5a367872014-06-02 15:32:02 -07001581 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001582 if (netCap == null) return TYPE_NONE;
1583 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1584 return TYPE_MOBILE_CBS;
1585 }
1586 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1587 return TYPE_MOBILE_IMS;
1588 }
1589 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1590 return TYPE_MOBILE_FOTA;
1591 }
1592 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1593 return TYPE_MOBILE_DUN;
1594 }
1595 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1596 return TYPE_MOBILE_SUPL;
1597 }
1598 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1599 return TYPE_MOBILE_MMS;
1600 }
1601 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1602 return TYPE_MOBILE_HIPRI;
1603 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001604 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1605 return TYPE_WIFI_P2P;
1606 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001607 return TYPE_NONE;
1608 }
1609
1610 private static class LegacyRequest {
1611 NetworkCapabilities networkCapabilities;
1612 NetworkRequest networkRequest;
1613 int expireSequenceNumber;
1614 Network currentNetwork;
1615 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001616
1617 private void clearDnsBinding() {
1618 if (currentNetwork != null) {
1619 currentNetwork = null;
1620 setProcessDefaultNetworkForHostResolution(null);
1621 }
1622 }
1623
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001624 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001625 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001626 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001627 currentNetwork = network;
1628 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001629 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001630 }
1631 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001632 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001633 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001634 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1635 }
1636 };
1637 }
1638
Mathew Inwood5a09a712020-11-04 09:29:36 +00001639 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001640 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1641 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001642
1643 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1644 synchronized (sLegacyRequests) {
1645 LegacyRequest l = sLegacyRequests.get(netCap);
1646 if (l != null) return l.networkRequest;
1647 }
1648 return null;
1649 }
1650
1651 private void renewRequestLocked(LegacyRequest l) {
1652 l.expireSequenceNumber++;
1653 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1654 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1655 }
1656
1657 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1658 int ourSeqNum = -1;
1659 synchronized (sLegacyRequests) {
1660 LegacyRequest l = sLegacyRequests.get(netCap);
1661 if (l == null) return;
1662 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001663 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001664 }
1665 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1666 }
1667
Mathew Inwood5a09a712020-11-04 09:29:36 +00001668 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001669 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1670 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001671 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001672 try {
1673 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001674 } catch (RemoteException e) {
1675 throw e.rethrowFromSystemServer();
1676 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001677 LegacyRequest l = new LegacyRequest();
1678 l.networkCapabilities = netCap;
1679 l.delay = delay;
1680 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001681 l.networkRequest = sendRequestForNetwork(
1682 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001683 if (l.networkRequest == null) return null;
1684 sLegacyRequests.put(netCap, l);
1685 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1686 return l.networkRequest;
1687 }
1688
1689 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1690 if (delay >= 0) {
1691 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001692 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001693 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1694 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001695 }
1696 }
1697
Mathew Inwood5a09a712020-11-04 09:29:36 +00001698 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001699 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1700 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001701 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001702 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001703 }
Paul Jensen034dea32014-12-17 10:39:34 -05001704 if (l == null) return false;
1705 unregisterNetworkCallback(l.networkCallback);
1706 l.clearDnsBinding();
1707 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001708 }
1709
Erik Kline50068e52017-01-26 18:08:28 +09001710 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1711 static {
1712 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1713 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1714 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1715 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1716 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1717 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1718 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1719 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1720 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1721 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1722 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1723 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1724 }
1725
1726 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1727 static {
1728 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1729 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1730 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1731 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1732 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1733 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1734 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1735 }
1736
1737 /**
1738 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1739 * instance suitable for registering a request or callback. Throws an
1740 * IllegalArgumentException if no mapping from the legacy type to
1741 * NetworkCapabilities is known.
1742 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001743 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1744 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001745 * @hide
1746 */
1747 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1748 final NetworkCapabilities nc = new NetworkCapabilities();
1749
1750 // Map from type to transports.
1751 final int NOT_FOUND = -1;
1752 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00001753 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline50068e52017-01-26 18:08:28 +09001754 nc.addTransportType(transport);
1755
1756 // Map from type to capabilities.
1757 nc.addCapability(sLegacyTypeToCapability.get(
1758 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1759 nc.maybeMarkCapabilitiesRestricted();
1760 return nc;
1761 }
1762
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001763 /** @hide */
1764 public static class PacketKeepaliveCallback {
Mathew Inwood5a09a712020-11-04 09:29:36 +00001765 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev198d6502019-11-04 17:50:59 +00001766 public PacketKeepaliveCallback() {
1767 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001768 /** The requested keepalive was successfully started. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001769 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001770 public void onStarted() {}
1771 /** The keepalive was successfully stopped. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001772 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001773 public void onStopped() {}
1774 /** An error occurred. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001775 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001776 public void onError(int error) {}
1777 }
1778
1779 /**
1780 * Allows applications to request that the system periodically send specific packets on their
1781 * behalf, using hardware offload to save battery power.
1782 *
1783 * To request that the system send keepalives, call one of the methods that return a
1784 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1785 * passing in a non-null callback. If the callback is successfully started, the callback's
1786 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1787 * specifying one of the {@code ERROR_*} constants in this class.
1788 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001789 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1790 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1791 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001792 *
junyulaia86defc2018-12-27 17:25:29 +08001793 * @deprecated Use {@link SocketKeepalive} instead.
1794 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001795 * @hide
1796 */
1797 public class PacketKeepalive {
1798
1799 private static final String TAG = "PacketKeepalive";
1800
1801 /** @hide */
1802 public static final int SUCCESS = 0;
1803
1804 /** @hide */
1805 public static final int NO_KEEPALIVE = -1;
1806
1807 /** @hide */
1808 public static final int BINDER_DIED = -10;
1809
1810 /** The specified {@code Network} is not connected. */
1811 public static final int ERROR_INVALID_NETWORK = -20;
1812 /** The specified IP addresses are invalid. For example, the specified source IP address is
1813 * not configured on the specified {@code Network}. */
1814 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1815 /** The requested port is invalid. */
1816 public static final int ERROR_INVALID_PORT = -22;
1817 /** The packet length is invalid (e.g., too long). */
1818 public static final int ERROR_INVALID_LENGTH = -23;
1819 /** The packet transmission interval is invalid (e.g., too short). */
1820 public static final int ERROR_INVALID_INTERVAL = -24;
1821
1822 /** The hardware does not support this request. */
1823 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001824 /** The hardware returned an error. */
1825 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001826
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001827 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001828 public static final int NATT_PORT = 4500;
1829
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001830 /** The minimum interval in seconds between keepalive packet transmissions */
1831 public static final int MIN_INTERVAL = 10;
1832
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001833 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001834 private final ISocketKeepaliveCallback mCallback;
1835 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001836
1837 private volatile Integer mSlot;
1838
Mathew Inwood5a09a712020-11-04 09:29:36 +00001839 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001840 public void stop() {
1841 try {
junyulai9f872232019-01-16 20:23:34 +08001842 mExecutor.execute(() -> {
1843 try {
1844 if (mSlot != null) {
1845 mService.stopKeepalive(mNetwork, mSlot);
1846 }
1847 } catch (RemoteException e) {
1848 Log.e(TAG, "Error stopping packet keepalive: ", e);
1849 throw e.rethrowFromSystemServer();
1850 }
1851 });
1852 } catch (RejectedExecutionException e) {
1853 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001854 }
1855 }
1856
1857 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00001858 Preconditions.checkNotNull(network, "network cannot be null");
1859 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001860 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08001861 mExecutor = Executors.newSingleThreadExecutor();
1862 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001863 @Override
junyulai9f872232019-01-16 20:23:34 +08001864 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08001865 final long token = Binder.clearCallingIdentity();
1866 try {
1867 mExecutor.execute(() -> {
1868 mSlot = slot;
1869 callback.onStarted();
1870 });
1871 } finally {
1872 Binder.restoreCallingIdentity(token);
1873 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001874 }
junyulai9f872232019-01-16 20:23:34 +08001875
1876 @Override
1877 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08001878 final long token = Binder.clearCallingIdentity();
1879 try {
1880 mExecutor.execute(() -> {
1881 mSlot = null;
1882 callback.onStopped();
1883 });
1884 } finally {
1885 Binder.restoreCallingIdentity(token);
1886 }
junyulai9f872232019-01-16 20:23:34 +08001887 mExecutor.shutdown();
1888 }
1889
1890 @Override
1891 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08001892 final long token = Binder.clearCallingIdentity();
1893 try {
1894 mExecutor.execute(() -> {
1895 mSlot = null;
1896 callback.onError(error);
1897 });
1898 } finally {
1899 Binder.restoreCallingIdentity(token);
1900 }
junyulai9f872232019-01-16 20:23:34 +08001901 mExecutor.shutdown();
1902 }
1903
1904 @Override
1905 public void onDataReceived() {
1906 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1907 // this callback when data is received.
1908 }
1909 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001910 }
1911 }
1912
1913 /**
1914 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1915 *
junyulaia86defc2018-12-27 17:25:29 +08001916 * @deprecated Use {@link #createSocketKeepalive} instead.
1917 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001918 * @hide
1919 */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001920 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001921 public PacketKeepalive startNattKeepalive(
1922 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1923 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1924 final PacketKeepalive k = new PacketKeepalive(network, callback);
1925 try {
junyulai9f872232019-01-16 20:23:34 +08001926 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001927 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1928 } catch (RemoteException e) {
1929 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08001930 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001931 }
1932 return k;
1933 }
1934
Chiachang Wangc5f86f42021-01-15 11:06:21 +08001935 // Construct an invalid fd.
1936 private ParcelFileDescriptor createInvalidFd() {
1937 final int invalidFd = -1;
1938 return ParcelFileDescriptor.adoptFd(invalidFd);
1939 }
1940
The Android Open Source Project28527d22009-03-03 19:31:44 -08001941 /**
junyulaia86defc2018-12-27 17:25:29 +08001942 * Request that keepalives be started on a IPsec NAT-T socket.
1943 *
1944 * @param network The {@link Network} the socket is on.
1945 * @param socket The socket that needs to be kept alive.
1946 * @param source The source address of the {@link UdpEncapsulationSocket}.
1947 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1948 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1949 * must run callback sequentially, otherwise the order of callbacks cannot be
1950 * guaranteed.
1951 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1952 * changes. Must be extended by applications that use this API.
1953 *
junyulaic7ea1242019-01-08 20:04:33 +08001954 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1955 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08001956 **/
junyulai61143782019-03-04 22:45:36 +08001957 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08001958 @NonNull UdpEncapsulationSocket socket,
1959 @NonNull InetAddress source,
1960 @NonNull InetAddress destination,
1961 @NonNull @CallbackExecutor Executor executor,
1962 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08001963 ParcelFileDescriptor dup;
1964 try {
junyulaic4fb2482019-03-27 11:00:37 +08001965 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1966 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08001967 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1968 } catch (IOException ignored) {
1969 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1970 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08001971 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08001972 }
1973 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1974 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08001975 }
1976
1977 /**
1978 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1979 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1980 *
1981 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08001982 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1983 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1984 * from that port.
junyulai48a59382019-01-15 11:32:44 +08001985 * @param source The source address of the {@link UdpEncapsulationSocket}.
1986 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1987 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1988 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1989 * must run callback sequentially, otherwise the order of callbacks cannot be
1990 * guaranteed.
1991 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1992 * changes. Must be extended by applications that use this API.
1993 *
junyulaic7ea1242019-01-08 20:04:33 +08001994 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1995 * given socket.
junyulai48a59382019-01-15 11:32:44 +08001996 * @hide
1997 */
1998 @SystemApi
1999 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002000 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2001 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08002002 @NonNull InetAddress source,
2003 @NonNull InetAddress destination,
2004 @NonNull @CallbackExecutor Executor executor,
2005 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002006 ParcelFileDescriptor dup;
2007 try {
junyulaic4fb2482019-03-27 11:00:37 +08002008 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08002009 dup = pfd.dup();
2010 } catch (IOException ignored) {
2011 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2012 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002013 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002014 }
2015 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VAN642d6ab2021-03-11 10:56:49 +00002016 -1 /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08002017 }
2018
2019 /**
junyulaic7ea1242019-01-08 20:04:33 +08002020 * Request that keepalives be started on a TCP socket.
2021 * The socket must be established.
2022 *
2023 * @param network The {@link Network} the socket is on.
2024 * @param socket The socket that needs to be kept alive.
2025 * @param executor The executor on which callback will be invoked. This implementation assumes
2026 * the provided {@link Executor} runs the callbacks in sequence with no
2027 * concurrency. Failing this, no guarantee of correctness can be made. It is
2028 * the responsibility of the caller to ensure the executor provides this
2029 * guarantee. A simple way of creating such an executor is with the standard
2030 * tool {@code Executors.newSingleThreadExecutor}.
2031 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2032 * changes. Must be extended by applications that use this API.
2033 *
2034 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2035 * given socket.
2036 * @hide
2037 */
2038 @SystemApi
2039 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002040 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002041 @NonNull Socket socket,
2042 @NonNull Executor executor,
2043 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002044 ParcelFileDescriptor dup;
2045 try {
2046 dup = ParcelFileDescriptor.fromSocket(socket);
2047 } catch (UncheckedIOException ignored) {
2048 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2049 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002050 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002051 }
2052 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002053 }
2054
2055 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002056 * Ensure that a network route exists to deliver traffic to the specified
2057 * host via the specified network interface. An attempt to add a route that
2058 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002059 *
2060 * <p>This method requires the caller to hold either the
2061 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2062 * or the ability to modify system settings as determined by
2063 * {@link android.provider.Settings.System#canWrite}.</p>
2064 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002065 * @param networkType the type of the network over which traffic to the specified
2066 * host is to be routed
2067 * @param hostAddress the IP address of the host to which the route is desired
2068 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002069 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002070 * @deprecated Deprecated in favor of the
2071 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2072 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002073 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002074 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002075 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002076 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002077 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002078 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002079 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002080 }
2081
2082 /**
2083 * Ensure that a network route exists to deliver traffic to the specified
2084 * host via the specified network interface. An attempt to add a route that
2085 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002086 *
2087 * <p>This method requires the caller to hold either the
2088 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2089 * or the ability to modify system settings as determined by
2090 * {@link android.provider.Settings.System#canWrite}.</p>
2091 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002092 * @param networkType the type of the network over which traffic to the specified
2093 * host is to be routed
2094 * @param hostAddress the IP address of the host to which the route is desired
2095 * @return {@code true} on success, {@code false} on failure
2096 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002097 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002098 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002099 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002100 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002101 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002102 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002103 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002104 try {
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002105 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2106 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002107 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002108 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002109 }
2110 }
2111
2112 /**
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002113 * @return the context's attribution tag
2114 */
2115 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2116 private @Nullable String getAttributionTag() {
Roshan Piusc97d8062020-12-17 14:53:09 -08002117 return mContext.getAttributionTag();
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002118 }
2119
2120 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002121 * Returns the value of the setting for background data usage. If false,
2122 * applications should not use the network if the application is not in the
2123 * foreground. Developers should respect this setting, and check the value
2124 * of this before performing any background data operations.
2125 * <p>
2126 * All applications that have background services that use the network
2127 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002128 * <p>
Scott Main50589142011-10-06 18:32:43 -07002129 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002130 * background data depends on several combined factors, and this method will
2131 * always return {@code true}. Instead, when background data is unavailable,
2132 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002133 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134 * @return Whether background data usage is allowed.
2135 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002136 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002138 // assume that background data is allowed; final authority is
2139 // NetworkInfo which may be blocked.
2140 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002141 }
2142
2143 /**
2144 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002145 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002146 * @param allowBackgroundData Whether an application should use data while
2147 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002148 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002149 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2150 * @see #getBackgroundDataSetting()
2151 * @hide
2152 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002153 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002154 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002155 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002156 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002157 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002158
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002159 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002160 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002161 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002162 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002163 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002164 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002165 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002166 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2167 if (tm != null) {
2168 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2169 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2170 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2171 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2172 + " retVal=" + retVal);
2173 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002174 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002175 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002176 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002177 }
2178
The Android Open Source Project28527d22009-03-03 19:31:44 -08002179 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002180 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002181 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002182 */
2183 public interface OnNetworkActiveListener {
2184 /**
2185 * Called on the main thread of the process to report that the current data network
2186 * has become active, and it is now a good time to perform any pending network
2187 * operations. Note that this listener only tells you when the network becomes
2188 * active; if at any other time you want to know whether it is active (and thus okay
2189 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002190 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002191 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002192 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002193 }
2194
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002195 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002196 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002197
2198 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002199 * Start listening to reports when the system's default data network is active, meaning it is
2200 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2201 * to determine the current state of the system's default network after registering the
2202 * listener.
2203 * <p>
2204 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002205 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002206 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002207 *
2208 * @param l The listener to be told when the network is active.
2209 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002210 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002211 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2212 @Override
2213 public void onNetworkActive() throws RemoteException {
2214 l.onNetworkActive();
2215 }
2216 };
2217
2218 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002219 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002220 mNetworkActivityListeners.put(l, rl);
2221 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002222 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002223 }
2224 }
2225
2226 /**
2227 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002228 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002229 *
2230 * @param l Previously registered listener.
2231 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002232 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002233 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00002234 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002235 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002236 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002237 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002238 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002239 }
2240 }
2241
2242 /**
2243 * Return whether the data network is currently active. An active network means that
2244 * it is currently in a high power state for performing data transmission. On some
2245 * types of networks, it may be expensive to move and stay in such a state, so it is
2246 * more power efficient to batch network traffic together when the radio is already in
2247 * this state. This method tells you whether right now is currently a good time to
2248 * initiate network traffic, as the network is already active.
2249 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002250 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002251 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002252 return mService.isDefaultNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002253 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002254 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002255 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002256 }
2257
2258 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002259 * {@hide}
2260 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002261 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00002262 mContext = Preconditions.checkNotNull(context, "missing context");
2263 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchiddadca42020-03-04 11:07:38 -08002264 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002265 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002266 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002267
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002268 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002269 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002270 public static ConnectivityManager from(Context context) {
2271 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2272 }
2273
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002274 /** @hide */
2275 public NetworkRequest getDefaultRequest() {
2276 try {
2277 // This is not racy as the default request is final in ConnectivityService.
2278 return mService.getDefaultRequest();
2279 } catch (RemoteException e) {
2280 throw e.rethrowFromSystemServer();
2281 }
2282 }
2283
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002284 /**
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002285 * Check if the package is a allowed to write settings. This also accounts that such an access
2286 * happened.
2287 *
2288 * @return {@code true} iff the package is allowed to write settings.
2289 */
2290 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2291 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2292 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2293 boolean throwException) {
2294 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2295 throwException);
2296 }
2297
2298 /**
Paul Jensen12131352014-12-10 15:12:18 -05002299 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2300 * situations where a Context pointer is unavailable.
2301 * @hide
2302 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002303 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002304 static ConnectivityManager getInstanceOrNull() {
2305 return sInstance;
2306 }
2307
2308 /**
2309 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2310 * situations where a Context pointer is unavailable.
2311 * @hide
2312 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002313 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002314 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002315 private static ConnectivityManager getInstance() {
2316 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002317 throw new IllegalStateException("No ConnectivityManager yet constructed");
2318 }
Paul Jensen895c3942015-03-10 10:54:12 -04002319 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002320 }
2321
2322 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002323 * Get the set of tetherable, available interfaces. This list is limited by
2324 * device configuration and current interface existence.
2325 *
2326 * @return an array of 0 or more Strings of tetherable interface names.
2327 *
markchieneeea0be2020-01-21 13:11:06 +08002328 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002329 * {@hide}
2330 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002331 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002332 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002333 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002334 public String[] getTetherableIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002335 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002336 }
2337
2338 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002339 * Get the set of tethered interfaces.
2340 *
2341 * @return an array of 0 or more String of currently tethered interface names.
2342 *
markchieneeea0be2020-01-21 13:11:06 +08002343 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002344 * {@hide}
2345 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002346 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002347 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002348 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002349 public String[] getTetheredIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002350 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002351 }
2352
2353 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002354 * Get the set of interface names which attempted to tether but
2355 * failed. Re-attempting to tether may cause them to reset to the Tethered
2356 * state. Alternatively, causing the interface to be destroyed and recreated
2357 * may cause them to reset to the available state.
2358 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2359 * information on the cause of the errors.
2360 *
2361 * @return an array of 0 or more String indicating the interface names
2362 * which failed to tether.
2363 *
markchieneeea0be2020-01-21 13:11:06 +08002364 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002365 * {@hide}
2366 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002367 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002368 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002369 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002370 public String[] getTetheringErroredIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002371 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002372 }
2373
2374 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002375 * Get the set of tethered dhcp ranges.
2376 *
markchien218230f2020-02-14 11:55:48 +08002377 * @deprecated This method is not supported.
2378 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002379 * {@hide}
2380 */
paulhud70b7dd2019-08-12 16:25:11 +08002381 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchieneeea0be2020-01-21 13:11:06 +08002382 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002383 public String[] getTetheredDhcpRanges() {
markchien218230f2020-02-14 11:55:48 +08002384 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002385 }
2386
2387 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002388 * Attempt to tether the named interface. This will setup a dhcp server
2389 * on the interface, forward and NAT IP packets and forward DNS requests
2390 * to the best active upstream network interface. Note that if no upstream
2391 * IP network interface is available, dhcp will still run and traffic will be
2392 * allowed between the tethered devices and this device, though upstream net
2393 * access will of course fail until an upstream network interface becomes
2394 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002395 *
2396 * <p>This method requires the caller to hold either the
2397 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2398 * or the ability to modify system settings as determined by
2399 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002400 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002401 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2402 * and WifiStateMachine which need direct access. All other clients should use
2403 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2404 * logic.</p>
2405 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002406 * @param iface the interface name to tether.
2407 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiencc1bc1b2020-01-20 19:31:56 +08002408 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002409 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002410 * {@hide}
2411 */
Mathew Inwood5a09a712020-11-04 09:29:36 +00002412 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiencc1bc1b2020-01-20 19:31:56 +08002413 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002414 public int tether(String iface) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002415 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002416 }
2417
2418 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002419 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002420 *
2421 * <p>This method requires the caller to hold either the
2422 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2423 * or the ability to modify system settings as determined by
2424 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002425 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002426 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2427 * and WifiStateMachine which need direct access. All other clients should use
2428 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2429 * logic.</p>
2430 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002431 * @param iface the interface name to untether.
2432 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2433 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002434 * {@hide}
2435 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002436 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002437 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002438 public int untether(String iface) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002439 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002440 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002441
2442 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002443 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002444 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002445 * due to device configuration.
2446 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002447 * <p>If this app does not have permission to use this API, it will always
2448 * return false rather than throw an exception.</p>
2449 *
2450 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2451 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2452 *
2453 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2454 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2455 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002456 * @return a boolean - {@code true} indicating Tethering is supported.
2457 *
markchieneeea0be2020-01-21 13:11:06 +08002458 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002459 * {@hide}
2460 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002461 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002462 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2463 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002464 public boolean isTetheringSupported() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002465 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002466 }
2467
2468 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002469 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchiencc1bc1b2020-01-20 19:31:56 +08002470 *
2471 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002472 * @hide
2473 */
2474 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002475 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002476 public static abstract class OnStartTetheringCallback {
2477 /**
2478 * Called when tethering has been successfully started.
2479 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002480 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002481
2482 /**
2483 * Called when starting tethering failed.
2484 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002485 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002486 }
2487
2488 /**
2489 * Convenient overload for
2490 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2491 * handler to run on the current thread's {@link Looper}.
markchiencc1bc1b2020-01-20 19:31:56 +08002492 *
2493 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002494 * @hide
2495 */
2496 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002497 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002498 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002499 public void startTethering(int type, boolean showProvisioningUi,
2500 final OnStartTetheringCallback callback) {
2501 startTethering(type, showProvisioningUi, callback, null);
2502 }
2503
2504 /**
2505 * Runs tether provisioning for the given type if needed and then starts tethering if
2506 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2507 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2508 * schedules tether provisioning re-checks if appropriate.
2509 *
2510 * @param type The type of tethering to start. Must be one of
2511 * {@link ConnectivityManager.TETHERING_WIFI},
2512 * {@link ConnectivityManager.TETHERING_USB}, or
2513 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2514 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2515 * is one. This should be true the first time this function is called and also any time
2516 * the user can see this UI. It gives users information from their carrier about the
2517 * check failing and how they can sign up for tethering if possible.
2518 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2519 * of the result of trying to tether.
2520 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchiencc1bc1b2020-01-20 19:31:56 +08002521 *
2522 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002523 * @hide
2524 */
2525 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002526 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002527 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002528 public void startTethering(int type, boolean showProvisioningUi,
2529 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00002530 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002531
markchiencc1bc1b2020-01-20 19:31:56 +08002532 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002533 @Override
markchiencc1bc1b2020-01-20 19:31:56 +08002534 public void execute(Runnable command) {
2535 if (handler == null) {
2536 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002537 } else {
markchiencc1bc1b2020-01-20 19:31:56 +08002538 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002539 }
2540 }
2541 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002542
markchiencc1bc1b2020-01-20 19:31:56 +08002543 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2544 @Override
2545 public void onTetheringStarted() {
2546 callback.onTetheringStarted();
2547 }
2548
2549 @Override
markchien19336c22020-03-19 13:37:43 +08002550 public void onTetheringFailed(final int error) {
markchiencc1bc1b2020-01-20 19:31:56 +08002551 callback.onTetheringFailed();
2552 }
2553 };
2554
2555 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien19336c22020-03-19 13:37:43 +08002556 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchiencc1bc1b2020-01-20 19:31:56 +08002557
Amos Bianchiddadca42020-03-04 11:07:38 -08002558 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002559 }
2560
2561 /**
2562 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2563 * applicable.
2564 *
2565 * @param type The type of tethering to stop. Must be one of
2566 * {@link ConnectivityManager.TETHERING_WIFI},
2567 * {@link ConnectivityManager.TETHERING_USB}, or
2568 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchieneeea0be2020-01-21 13:11:06 +08002569 *
2570 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002571 * @hide
2572 */
2573 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002574 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002575 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002576 public void stopTethering(int type) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002577 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002578 }
2579
2580 /**
markchiena005c992019-02-27 14:56:11 +08002581 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2582 * upstream status.
2583 *
Nathan Haroldbbb48c62020-01-23 18:03:46 -08002584 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchieneeea0be2020-01-21 13:11:06 +08002585 * @hide
markchiena005c992019-02-27 14:56:11 +08002586 */
2587 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002588 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002589 public abstract static class OnTetheringEventCallback {
2590
2591 /**
2592 * Called when tethering upstream changed. This can be called multiple times and can be
2593 * called any time.
2594 *
2595 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2596 * have any upstream.
2597 */
2598 public void onUpstreamChanged(@Nullable Network network) {}
2599 }
2600
markchieneeea0be2020-01-21 13:11:06 +08002601 @GuardedBy("mTetheringEventCallbacks")
2602 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2603 mTetheringEventCallbacks = new ArrayMap<>();
2604
markchiena005c992019-02-27 14:56:11 +08002605 /**
2606 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002607 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002608 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2609 * with a null argument. The same callback object cannot be registered twice.
2610 *
2611 * @param executor the executor on which callback will be invoked.
2612 * @param callback the callback to be called when tethering has change events.
markchieneeea0be2020-01-21 13:11:06 +08002613 *
Nathan Haroldbbb48c62020-01-23 18:03:46 -08002614 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002615 * @hide
2616 */
2617 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002618 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002619 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2620 public void registerTetheringEventCallback(
2621 @NonNull @CallbackExecutor Executor executor,
2622 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00002623 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
markchiena005c992019-02-27 14:56:11 +08002624
markchieneeea0be2020-01-21 13:11:06 +08002625 final TetheringEventCallback tetherCallback =
2626 new TetheringEventCallback() {
2627 @Override
2628 public void onUpstreamChanged(@Nullable Network network) {
2629 callback.onUpstreamChanged(network);
2630 }
2631 };
2632
2633 synchronized (mTetheringEventCallbacks) {
2634 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchiddadca42020-03-04 11:07:38 -08002635 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchieneeea0be2020-01-21 13:11:06 +08002636 }
markchiena005c992019-02-27 14:56:11 +08002637 }
2638
2639 /**
2640 * Remove tethering event callback previously registered with
2641 * {@link #registerTetheringEventCallback}.
2642 *
2643 * @param callback previously registered callback.
markchieneeea0be2020-01-21 13:11:06 +08002644 *
2645 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002646 * @hide
2647 */
2648 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002649 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002650 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2651 public void unregisterTetheringEventCallback(
2652 @NonNull final OnTetheringEventCallback callback) {
markchieneeea0be2020-01-21 13:11:06 +08002653 Objects.requireNonNull(callback, "The callback must be non-null");
2654 synchronized (mTetheringEventCallbacks) {
2655 final TetheringEventCallback tetherCallback =
2656 mTetheringEventCallbacks.remove(callback);
Amos Bianchiddadca42020-03-04 11:07:38 -08002657 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchieneeea0be2020-01-21 13:11:06 +08002658 }
markchiena005c992019-02-27 14:56:11 +08002659 }
2660
2661
2662 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002663 * Get the list of regular expressions that define any tetherable
2664 * USB network interfaces. If USB tethering is not supported by the
2665 * device, this list should be empty.
2666 *
2667 * @return an array of 0 or more regular expression Strings defining
2668 * what interfaces are considered tetherable usb interfaces.
2669 *
markchieneeea0be2020-01-21 13:11:06 +08002670 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002671 * {@hide}
2672 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002673 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002674 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002675 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002676 public String[] getTetherableUsbRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002677 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002678 }
2679
2680 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002681 * Get the list of regular expressions that define any tetherable
2682 * Wifi network interfaces. If Wifi tethering is not supported by the
2683 * device, this list should be empty.
2684 *
2685 * @return an array of 0 or more regular expression Strings defining
2686 * what interfaces are considered tetherable wifi interfaces.
2687 *
markchieneeea0be2020-01-21 13:11:06 +08002688 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002689 * {@hide}
2690 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002691 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002692 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002693 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002694 public String[] getTetherableWifiRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002695 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002696 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002697
Danica Chang96567052010-08-11 14:54:43 -07002698 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002699 * Get the list of regular expressions that define any tetherable
2700 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2701 * device, this list should be empty.
2702 *
2703 * @return an array of 0 or more regular expression Strings defining
2704 * what interfaces are considered tetherable bluetooth interfaces.
2705 *
markchieneeea0be2020-01-21 13:11:06 +08002706 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2707 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002708 * {@hide}
2709 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002710 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002711 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002712 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002713 public String[] getTetherableBluetoothRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002714 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002715 }
2716
Mike Lockwooded4a1742011-07-19 13:04:47 -07002717 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002718 * Attempt to both alter the mode of USB and Tethering of USB. A
2719 * utility method to deal with some of the complexity of USB - will
2720 * attempt to switch to Rndis and subsequently tether the resulting
2721 * interface on {@code true} or turn off tethering and switch off
2722 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002723 *
2724 * <p>This method requires the caller to hold either the
2725 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2726 * or the ability to modify system settings as determined by
2727 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002728 *
2729 * @param enable a boolean - {@code true} to enable tethering
2730 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiencc1bc1b2020-01-20 19:31:56 +08002731 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002732 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002733 * {@hide}
2734 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002735 @UnsupportedAppUsage
markchiencc1bc1b2020-01-20 19:31:56 +08002736 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002737 public int setUsbTethering(boolean enable) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002738 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002739 }
2740
markchieneeea0be2020-01-21 13:11:06 +08002741 /**
2742 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2743 * {@hide}
2744 */
markchien5bd499c2019-01-16 17:44:13 +08002745 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002746 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002747 public static final int TETHER_ERROR_NO_ERROR = 0;
markchieneeea0be2020-01-21 13:11:06 +08002748 /**
2749 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2750 * {@hide}
2751 */
2752 @Deprecated
2753 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2754 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2755 /**
2756 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2757 * {@hide}
2758 */
2759 @Deprecated
2760 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2761 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2762 /**
2763 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2764 * {@hide}
2765 */
2766 @Deprecated
2767 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2768 /**
2769 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2770 * {@hide}
2771 */
2772 @Deprecated
2773 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2774 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2775 /**
markchien19336c22020-03-19 13:37:43 +08002776 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002777 * {@hide}
2778 */
2779 @Deprecated
markchien19336c22020-03-19 13:37:43 +08002780 public static final int TETHER_ERROR_MASTER_ERROR =
2781 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002782 /**
2783 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2784 * {@hide}
2785 */
2786 @Deprecated
2787 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2788 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2789 /**
2790 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2791 * {@hide}
2792 */
2793 @Deprecated
2794 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2795 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2796 /**
markchien19336c22020-03-19 13:37:43 +08002797 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002798 * {@hide}
2799 */
2800 @Deprecated
2801 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien19336c22020-03-19 13:37:43 +08002802 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002803 /**
markchien19336c22020-03-19 13:37:43 +08002804 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002805 * {@hide}
2806 */
2807 @Deprecated
2808 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien19336c22020-03-19 13:37:43 +08002809 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002810 /**
2811 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2812 * {@hide}
2813 */
2814 @Deprecated
2815 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2816 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2817 /**
markchien19336c22020-03-19 13:37:43 +08002818 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchieneeea0be2020-01-21 13:11:06 +08002819 * {@hide}
2820 */
markchien5bd499c2019-01-16 17:44:13 +08002821 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002822 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002823 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchieneeea0be2020-01-21 13:11:06 +08002824 /**
2825 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2826 * {@hide}
2827 */
2828 @Deprecated
2829 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2830 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2831 /**
2832 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2833 * {@hide}
2834 */
markchien5bd499c2019-01-16 17:44:13 +08002835 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002836 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002837 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002838
2839 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002840 * Get a more detailed error code after a Tethering or Untethering
2841 * request asynchronously failed.
2842 *
2843 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002844 * @return error The error code of the last error tethering or untethering the named
2845 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002846 *
markchieneeea0be2020-01-21 13:11:06 +08002847 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002848 * {@hide}
2849 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002850 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood5a09a712020-11-04 09:29:36 +00002851 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchieneeea0be2020-01-21 13:11:06 +08002852 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002853 public int getLastTetherError(String iface) {
markchien19336c22020-03-19 13:37:43 +08002854 int error = mTetheringManager.getLastTetherError(iface);
2855 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2856 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2857 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2858 // instead.
2859 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2860 }
2861 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002862 }
2863
markchiendd41c822019-03-06 16:25:00 +08002864 /** @hide */
2865 @Retention(RetentionPolicy.SOURCE)
2866 @IntDef(value = {
2867 TETHER_ERROR_NO_ERROR,
2868 TETHER_ERROR_PROVISION_FAILED,
2869 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2870 })
2871 public @interface EntitlementResultCode {
2872 }
2873
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002874 /**
markchiendd41c822019-03-06 16:25:00 +08002875 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08002876 * entitlement succeeded.
markchieneeea0be2020-01-21 13:11:06 +08002877 *
2878 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08002879 * @hide
2880 */
2881 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002882 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08002883 public interface OnTetheringEntitlementResultListener {
2884 /**
2885 * Called to notify entitlement result.
2886 *
2887 * @param resultCode an int value of entitlement result. It may be one of
2888 * {@link #TETHER_ERROR_NO_ERROR},
2889 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2890 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2891 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07002892 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08002893 }
2894
2895 /**
markchien5bd499c2019-01-16 17:44:13 +08002896 * Get the last value of the entitlement check on this downstream. If the cached value is
2897 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2898 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2899 * guaranteed that the UI-based entitlement check will complete in any specific time period
2900 * and may in fact never complete. Any successful entitlement check the platform performs for
2901 * any reason will update the cached value.
2902 *
2903 * @param type the downstream type of tethering. Must be one of
2904 * {@link #TETHERING_WIFI},
2905 * {@link #TETHERING_USB}, or
2906 * {@link #TETHERING_BLUETOOTH}.
2907 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08002908 * @param executor the executor on which callback will be invoked.
2909 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2910 * notify the caller of the result of entitlement check. The listener may be called zero
2911 * or one time.
markchieneeea0be2020-01-21 13:11:06 +08002912 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08002913 * {@hide}
2914 */
2915 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002916 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08002917 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08002918 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2919 @NonNull @CallbackExecutor Executor executor,
2920 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00002921 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchiendd41c822019-03-06 16:25:00 +08002922 ResultReceiver wrappedListener = new ResultReceiver(null) {
2923 @Override
2924 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslin9cc04192021-03-04 09:38:21 +08002925 final long token = Binder.clearCallingIdentity();
2926 try {
2927 executor.execute(() -> {
2928 listener.onTetheringEntitlementResult(resultCode);
2929 });
2930 } finally {
2931 Binder.restoreCallingIdentity(token);
2932 }
markchiendd41c822019-03-06 16:25:00 +08002933 }
2934 };
2935
Amos Bianchiddadca42020-03-04 11:07:38 -08002936 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien4f949812019-12-16 20:15:20 +08002937 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08002938 }
2939
2940 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002941 * Report network connectivity status. This is currently used only
2942 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04002943 * <p>This method requires the caller to hold the permission
2944 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08002945 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002946 * @param networkType The type of network you want to report on
2947 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09002948 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002949 * {@hide}
2950 */
2951 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09002952 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002953 try {
2954 mService.reportInetCondition(networkType, percentage);
2955 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002956 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002957 }
2958 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002959
2960 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002961 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07002962 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002963 * the framework to re-evaluate network connectivity and/or switch to another
2964 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002965 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002966 * @param network The {@link Network} the application was attempting to use
2967 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04002968 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2969 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002970 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002971 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09002972 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09002973 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002974 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04002975 // One of these will be ignored because it matches system's current state.
2976 // The other will trigger the necessary reevaluation.
2977 mService.reportNetworkConnectivity(network, true);
2978 mService.reportNetworkConnectivity(network, false);
2979 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002980 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04002981 }
2982 }
2983
2984 /**
2985 * Report to the framework whether a network has working connectivity.
2986 * This provides a hint to the system that a particular network is providing
2987 * working connectivity or not. In response the framework may re-evaluate
2988 * the network's connectivity and might take further action thereafter.
2989 *
2990 * @param network The {@link Network} the application was attempting to use
2991 * or {@code null} to indicate the current default network.
2992 * @param hasConnectivity {@code true} if the application was able to successfully access the
2993 * Internet using {@code network} or {@code false} if not.
2994 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002995 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09002996 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04002997 try {
2998 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002999 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003000 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003001 }
3002 }
3003
3004 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003005 * Set a network-independent global http proxy. This is not normally what you want
3006 * for typical HTTP proxies - they are general network dependent. However if you're
3007 * doing something unusual like general internal filtering this may be useful. On
3008 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003009 *
3010 * @param p A {@link ProxyInfo} object defining the new global
3011 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003012 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003013 */
paulhud70b7dd2019-08-12 16:25:11 +08003014 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk1e3df5d2014-04-25 15:00:09 -04003015 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003016 try {
3017 mService.setGlobalProxy(p);
3018 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003019 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003020 }
3021 }
3022
3023 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003024 * Retrieve any network-independent global HTTP proxy.
3025 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003026 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003027 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003028 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003029 */
Jason Monk1e3df5d2014-04-25 15:00:09 -04003030 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003031 try {
3032 return mService.getGlobalProxy();
3033 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003034 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003035 }
3036 }
3037
3038 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003039 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3040 * network-specific HTTP proxy. If {@code network} is null, the
3041 * network-specific proxy returned is the proxy of the default active
3042 * network.
3043 *
3044 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3045 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3046 * or when {@code network} is {@code null},
3047 * the {@code ProxyInfo} for the default active network. Returns
3048 * {@code null} when no proxy applies or the caller doesn't have
3049 * permission to use {@code network}.
3050 * @hide
3051 */
3052 public ProxyInfo getProxyForNetwork(Network network) {
3053 try {
3054 return mService.getProxyForNetwork(network);
3055 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003056 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003057 }
3058 }
3059
3060 /**
Paul Jensen12131352014-12-10 15:12:18 -05003061 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3062 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003063 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003064 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003065 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003066 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003067 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003068 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003069 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003070 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003071 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003072 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003073
3074 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003075 * Returns true if the hardware supports the given network type
3076 * else it returns false. This doesn't indicate we have coverage
3077 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003078 * hardware supports it. For example a GSM phone without a SIM
3079 * should still return {@code true} for mobile data, but a wifi only
3080 * tablet would return {@code false}.
3081 *
3082 * @param networkType The network type we'd like to check
3083 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003084 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003085 * @hide
3086 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003087 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003088 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003089 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003090 public boolean isNetworkSupported(int networkType) {
3091 try {
3092 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003093 } catch (RemoteException e) {
3094 throw e.rethrowFromSystemServer();
3095 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003096 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003097
3098 /**
3099 * Returns if the currently active data network is metered. A network is
3100 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003101 * that connection due to monetary costs, data limitations or
3102 * battery/performance issues. You should check this before doing large
3103 * data transfers, and warn the user or delay the operation until another
3104 * network is available.
3105 *
3106 * @return {@code true} if large transfers should be avoided, otherwise
3107 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003108 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003109 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003110 public boolean isActiveNetworkMetered() {
3111 try {
3112 return mService.isActiveNetworkMetered();
3113 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003114 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003115 }
3116 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003117
Robert Greenwalt26744a52013-02-15 10:56:35 -08003118 /**
Sarah Chincf44f2f2020-11-25 12:15:14 -08003119 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003120 *
Sarah Chincf44f2f2020-11-25 12:15:14 -08003121 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003122 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003123 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003124 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003125 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003126 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003127 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003128 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003129 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003130 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003131 }
3132 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003133
3134 /**
3135 * Set the value for enabling/disabling airplane mode
3136 *
3137 * @param enable whether to enable airplane mode or not
3138 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003139 * @hide
3140 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003141 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003142 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003143 android.Manifest.permission.NETWORK_SETTINGS,
3144 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3145 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003146 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003147 public void setAirplaneMode(boolean enable) {
3148 try {
3149 mService.setAirplaneMode(enable);
3150 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003151 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003152 }
3153 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003154
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003155 /**
3156 * Registers the specified {@link NetworkProvider}.
3157 * Each listener must only be registered once. The listener can be unregistered with
3158 * {@link #unregisterNetworkProvider}.
3159 *
3160 * @param provider the provider to register
3161 * @return the ID of the provider. This ID must be used by the provider when registering
3162 * {@link android.net.NetworkAgent}s.
3163 * @hide
3164 */
3165 @SystemApi
paulhu44939832020-03-04 09:43:41 +08003166 @RequiresPermission(anyOf = {
3167 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3168 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003169 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3170 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003171 throw new IllegalStateException("NetworkProviders can only be registered once");
3172 }
3173
3174 try {
3175 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3176 provider.getName());
3177 provider.setProviderId(providerId);
3178 } catch (RemoteException e) {
3179 throw e.rethrowFromSystemServer();
3180 }
3181 return provider.getProviderId();
3182 }
3183
3184 /**
3185 * Unregisters the specified NetworkProvider.
3186 *
3187 * @param provider the provider to unregister
3188 * @hide
3189 */
3190 @SystemApi
paulhu44939832020-03-04 09:43:41 +08003191 @RequiresPermission(anyOf = {
3192 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3193 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003194 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3195 try {
3196 mService.unregisterNetworkProvider(provider.getMessenger());
3197 } catch (RemoteException e) {
3198 throw e.rethrowFromSystemServer();
3199 }
3200 provider.setProviderId(NetworkProvider.ID_NONE);
3201 }
3202
3203
3204 /** @hide exposed via the NetworkProvider class. */
paulhu44939832020-03-04 09:43:41 +08003205 @RequiresPermission(anyOf = {
3206 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3207 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003208 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3209 try {
3210 mService.declareNetworkRequestUnfulfillable(request);
3211 } catch (RemoteException e) {
3212 throw e.rethrowFromSystemServer();
3213 }
3214 }
3215
Paul Jensenc2569432015-02-13 14:18:39 -05003216 /**
3217 * @hide
3218 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana973c7a2019-12-13 19:47:12 +09003219 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003220 */
paulhu44939832020-03-04 09:43:41 +08003221 @RequiresPermission(anyOf = {
3222 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3223 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003224 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeandd753522020-12-21 18:36:52 +09003225 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3226 int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003227 try {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003228 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003229 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003230 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003231 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003232 }
3233
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003234 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003235 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3236 * changes. Should be extended by applications wanting notifications.
3237 *
3238 * A {@code NetworkCallback} is registered by calling
3239 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3240 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003241 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003242 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3243 * A {@code NetworkCallback} should be registered at most once at any time.
3244 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003245 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003246 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003247 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003248 * No flags associated with this callback.
3249 * @hide
3250 */
3251 public static final int FLAG_NONE = 0;
3252 /**
3253 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3254 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3255 * <p>
3256 * These include:
3257 * <li> Some transport info instances (retrieved via
3258 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3259 * contain location sensitive information.
3260 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3261 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3262 * </p>
3263 * <p>
3264 * Note:
3265 * <li> Retrieving this location sensitive information (subject to app's location
3266 * permissions) will be noted by system. </li>
3267 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3268 * not include location sensitive info.
3269 * </p>
3270 */
3271 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3272
3273 /** @hide */
3274 @Retention(RetentionPolicy.SOURCE)
3275 @IntDef(flag = true, prefix = "FLAG_", value = {
3276 FLAG_NONE,
3277 FLAG_INCLUDE_LOCATION_INFO
3278 })
3279 public @interface Flag { }
3280
3281 /**
3282 * All the valid flags for error checking.
3283 */
3284 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3285
3286 public NetworkCallback() {
3287 this(FLAG_NONE);
3288 }
3289
3290 public NetworkCallback(@Flag int flags) {
3291 Preconditions.checkArgument((flags & VALID_FLAGS) == flags);
3292 mFlags = flags;
3293 }
3294
3295 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003296 * Called when the framework connects to a new network to evaluate whether it satisfies this
3297 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3298 * callback. There is no guarantee that this new network will satisfy any requests, or that
3299 * the network will stay connected for longer than the time necessary to evaluate it.
3300 * <p>
3301 * Most applications <b>should not</b> act on this callback, and should instead use
3302 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3303 * the framework in properly evaluating the network &mdash; for example, an application that
3304 * can automatically log in to a captive portal without user intervention.
3305 *
3306 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003307 *
3308 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003309 */
paulhua9a6e2a2019-03-22 16:35:06 +08003310 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003311
3312 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003313 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003314 * This callback may be called more than once if the {@link Network} that is
3315 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003316 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003317 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003318 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3319 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003320 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003321 * @hide
3322 */
paulhua9a6e2a2019-03-22 16:35:06 +08003323 public void onAvailable(@NonNull Network network,
3324 @NonNull NetworkCapabilities networkCapabilities,
3325 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003326 // Internally only this method is called when a new network is available, and
3327 // it calls the callback in the same way and order that older versions used
3328 // to call so as not to change the behavior.
3329 onAvailable(network);
3330 if (!networkCapabilities.hasCapability(
3331 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3332 onNetworkSuspended(network);
3333 }
3334 onCapabilitiesChanged(network, networkCapabilities);
3335 onLinkPropertiesChanged(network, linkProperties);
junyulai5ab727b2018-08-07 19:50:45 +08003336 onBlockedStatusChanged(network, blocked);
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003337 }
3338
3339 /**
3340 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003341 *
3342 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3343 * be available at the same time, and onAvailable will be called for each of these as they
3344 * appear.
3345 *
3346 * <p>For callbacks registered with {@link #requestNetwork} and
3347 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3348 * is the new best network for this request and is now tracked by this callback ; this
3349 * callback will no longer receive method calls about other networks that may have been
3350 * passed to this method previously. The previously-best network may have disconnected, or
3351 * it may still be around and the newly-best network may simply be better.
3352 *
3353 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3354 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3355 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3356 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3357 *
3358 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3359 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3360 * this callback as this is prone to race conditions (there is no guarantee the objects
3361 * returned by these methods will be current). Instead, wait for a call to
3362 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3363 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3364 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003365 *
3366 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003367 */
paulhua9a6e2a2019-03-22 16:35:06 +08003368 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003369
3370 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003371 * Called when the network is about to be lost, typically because there are no outstanding
3372 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3373 * with the new replacement network for graceful handover. This method is not guaranteed
3374 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3375 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003376 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003377 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3378 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3379 * this callback as this is prone to race conditions ; calling these methods while in a
3380 * callback may return an outdated or even a null object.
3381 *
3382 * @param network The {@link Network} that is about to be lost.
3383 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3384 * connected for graceful handover; note that the network may still
3385 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003386 */
paulhua9a6e2a2019-03-22 16:35:06 +08003387 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003388
3389 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003390 * Called when a network disconnects or otherwise no longer satisfies this request or
3391 * callback.
3392 *
3393 * <p>If the callback was registered with requestNetwork() or
3394 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3395 * returned by onAvailable() when that network is lost and no other network satisfies
3396 * the criteria of the request.
3397 *
3398 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3399 * each network which no longer satisfies the criteria of the callback.
3400 *
3401 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3402 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3403 * this callback as this is prone to race conditions ; calling these methods while in a
3404 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003405 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003406 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003407 */
paulhua9a6e2a2019-03-22 16:35:06 +08003408 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003409
3410 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003411 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003412 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3413 * requested network request cannot be fulfilled (whether or not a timeout was
3414 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003415 * {@link NetworkRequest} will have already been removed and released, as if
3416 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003417 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003418 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003419
3420 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003421 * Called when the network corresponding to this request changes capabilities but still
3422 * satisfies the requested criteria.
3423 *
3424 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3425 * to be called immediately after {@link #onAvailable}.
3426 *
3427 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3428 * ConnectivityManager methods in this callback as this is prone to race conditions :
3429 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003430 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003431 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius7992afd2020-12-22 15:10:42 -08003432 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003433 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003434 */
paulhua9a6e2a2019-03-22 16:35:06 +08003435 public void onCapabilitiesChanged(@NonNull Network network,
3436 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003437
3438 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003439 * Called when the network corresponding to this request changes {@link LinkProperties}.
3440 *
3441 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3442 * to be called immediately after {@link #onAvailable}.
3443 *
3444 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3445 * ConnectivityManager methods in this callback as this is prone to race conditions :
3446 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003447 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003448 * @param network The {@link Network} whose link properties have changed.
3449 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003450 */
paulhua9a6e2a2019-03-22 16:35:06 +08003451 public void onLinkPropertiesChanged(@NonNull Network network,
3452 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003453
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003454 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003455 * Called when the network the framework connected to for this request suspends data
3456 * transmission temporarily.
3457 *
3458 * <p>This generally means that while the TCP connections are still live temporarily
3459 * network data fails to transfer. To give a specific example, this is used on cellular
3460 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3461 * means read operations on sockets on this network will block once the buffers are
3462 * drained, and write operations will block once the buffers are full.
3463 *
3464 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3465 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3466 * this callback as this is prone to race conditions (there is no guarantee the objects
3467 * returned by these methods will be current).
3468 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003469 * @hide
3470 */
paulhua9a6e2a2019-03-22 16:35:06 +08003471 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003472
3473 /**
3474 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003475 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3476 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003477
3478 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3479 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3480 * this callback as this is prone to race conditions : calling these methods while in a
3481 * callback may return an outdated or even a null object.
3482 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003483 * @hide
3484 */
paulhua9a6e2a2019-03-22 16:35:06 +08003485 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003486
junyulai5ab727b2018-08-07 19:50:45 +08003487 /**
3488 * Called when access to the specified network is blocked or unblocked.
3489 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003490 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3491 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3492 * this callback as this is prone to race conditions : calling these methods while in a
3493 * callback may return an outdated or even a null object.
3494 *
junyulai5ab727b2018-08-07 19:50:45 +08003495 * @param network The {@link Network} whose blocked status has changed.
3496 * @param blocked The blocked status of this {@link Network}.
3497 */
junyulai61143782019-03-04 22:45:36 +08003498 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003499
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003500 private NetworkRequest networkRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -08003501 private final int mFlags;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003502 }
3503
Hugo Benichi145e3792017-05-11 13:16:17 +09003504 /**
3505 * Constant error codes used by ConnectivityService to communicate about failures and errors
3506 * across a Binder boundary.
3507 * @hide
3508 */
3509 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003510 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003511 }
3512
3513 /** @hide */
3514 public static class TooManyRequestsException extends RuntimeException {}
3515
3516 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3517 switch (e.errorCode) {
3518 case Errors.TOO_MANY_REQUESTS:
3519 return new TooManyRequestsException();
3520 default:
3521 Log.w(TAG, "Unknown service error code " + e.errorCode);
3522 return new RuntimeException(e);
3523 }
3524 }
3525
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003526 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003527 /** @hide */
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003528 public static final int CALLBACK_PRECHECK = BASE + 1;
3529 /** @hide */
3530 public static final int CALLBACK_AVAILABLE = BASE + 2;
3531 /** @hide arg1 = TTL */
3532 public static final int CALLBACK_LOSING = BASE + 3;
3533 /** @hide */
3534 public static final int CALLBACK_LOST = BASE + 4;
3535 /** @hide */
3536 public static final int CALLBACK_UNAVAIL = BASE + 5;
3537 /** @hide */
3538 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3539 /** @hide */
3540 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003541 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichi4802c802017-03-23 22:40:44 +09003542 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003543 /** @hide */
Hugo Benichi4802c802017-03-23 22:40:44 +09003544 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003545 /** @hide */
Hugo Benichi4802c802017-03-23 22:40:44 +09003546 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai5ab727b2018-08-07 19:50:45 +08003547 /** @hide */
3548 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003549
Erik Kline66721822015-11-25 12:49:38 +09003550 /** @hide */
3551 public static String getCallbackName(int whichCallback) {
3552 switch (whichCallback) {
3553 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3554 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3555 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3556 case CALLBACK_LOST: return "CALLBACK_LOST";
3557 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3558 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3559 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003560 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3561 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3562 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003563 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003564 default:
3565 return Integer.toString(whichCallback);
3566 }
3567 }
3568
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003569 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003570 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003571 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003572
Hugo Benichife3325f2016-07-06 22:53:17 +09003573 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003574 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003575 }
3576
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003577 CallbackHandler(Handler handler) {
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00003578 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003579 }
3580
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003581 @Override
3582 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003583 if (message.what == EXPIRE_LEGACY_REQUEST) {
3584 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3585 return;
3586 }
3587
3588 final NetworkRequest request = getObject(message, NetworkRequest.class);
3589 final Network network = getObject(message, Network.class);
3590 final NetworkCallback callback;
3591 synchronized (sCallbacks) {
3592 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003593 if (callback == null) {
3594 Log.w(TAG,
3595 "callback not found for " + getCallbackName(message.what) + " message");
3596 return;
3597 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003598 if (message.what == CALLBACK_UNAVAIL) {
3599 sCallbacks.remove(request);
3600 callback.networkRequest = ALREADY_UNREGISTERED;
3601 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003602 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003603 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003604 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003605 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003606
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003607 switch (message.what) {
3608 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003609 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003610 break;
3611 }
3612 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003613 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3614 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai5ab727b2018-08-07 19:50:45 +08003615 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003616 break;
3617 }
3618 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003619 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003620 break;
3621 }
3622 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003623 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003624 break;
3625 }
3626 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003627 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003628 break;
3629 }
3630 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003631 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3632 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003633 break;
3634 }
3635 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003636 LinkProperties lp = getObject(message, LinkProperties.class);
3637 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003638 break;
3639 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003640 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003641 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003642 break;
3643 }
3644 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003645 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003646 break;
3647 }
junyulai5ab727b2018-08-07 19:50:45 +08003648 case CALLBACK_BLK_CHANGED: {
3649 boolean blocked = message.arg1 != 0;
3650 callback.onBlockedStatusChanged(network, blocked);
3651 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003652 }
3653 }
3654
Hugo Benichife3325f2016-07-06 22:53:17 +09003655 private <T> T getObject(Message msg, Class<T> c) {
3656 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003657 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003658 }
3659
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003660 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003661 synchronized (sCallbacks) {
3662 if (sCallbackHandler == null) {
3663 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003664 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003665 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003666 }
3667 }
3668
Hugo Benichiec180d52017-02-03 14:18:44 +09003669 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3670 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003671
Hugo Benichiec180d52017-02-03 14:18:44 +09003672 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaid1a78162021-01-11 16:53:38 +08003673 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003674 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003675 checkCallbackNotNull(callback);
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00003676 Preconditions.checkArgument(
3677 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3678 "null NetworkCapabilities");
Hugo Benichife3325f2016-07-06 22:53:17 +09003679 final NetworkRequest request;
Roshan Pius34dc4be2020-01-16 12:17:17 -08003680 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003681 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003682 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003683 if (callback.networkRequest != null
3684 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003685 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3686 // and requests (http://b/20701525).
3687 Log.e(TAG, "NetworkCallback was already registered");
3688 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003689 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003690 Binder binder = new Binder();
Roshan Pius7992afd2020-12-22 15:10:42 -08003691 final int callbackFlags = callback.mFlags;
junyulaid1a78162021-01-11 16:53:38 +08003692 if (reqType == LISTEN) {
Roshan Pius34dc4be2020-01-16 12:17:17 -08003693 request = mService.listenForNetwork(
Roshan Pius7992afd2020-12-22 15:10:42 -08003694 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08003695 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003696 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003697 request = mService.requestNetwork(
junyulaid1a78162021-01-11 16:53:38 +08003698 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
Roshan Pius7992afd2020-12-22 15:10:42 -08003699 callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003700 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003701 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003702 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003703 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003704 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003705 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003706 } catch (RemoteException e) {
3707 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003708 } catch (ServiceSpecificException e) {
3709 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003710 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003711 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003712 }
3713
3714 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003715 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003716 *
markchieneddbe2b2020-03-18 21:16:15 +08003717 * This API is only for use in internal system code that requests networks with legacy type and
3718 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchienddd59372020-01-14 00:55:21 +08003719 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003720 *
markchienddd59372020-01-14 00:55:21 +08003721 * @param request {@link NetworkRequest} describing this request.
markchienddd59372020-01-14 00:55:21 +08003722 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3723 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3724 * be a positive value (i.e. >0).
3725 * @param legacyType to specify the network type(#TYPE_*).
3726 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchieneddbe2b2020-03-18 21:16:15 +08003727 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3728 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003729 *
3730 * @hide
3731 */
markchienddd59372020-01-14 00:55:21 +08003732 @SystemApi
markchieneddbe2b2020-03-18 21:16:15 +08003733 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003734 public void requestNetwork(@NonNull NetworkRequest request,
markchieneddbe2b2020-03-18 21:16:15 +08003735 int timeoutMs, int legacyType, @NonNull Handler handler,
3736 @NonNull NetworkCallback networkCallback) {
3737 if (legacyType == TYPE_NONE) {
3738 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3739 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003740 CallbackHandler cbHandler = new CallbackHandler(handler);
3741 NetworkCapabilities nc = request.networkCapabilities;
3742 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003743 }
3744
3745 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003746 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003747 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003748 * <p>This method will attempt to find the best network that matches the passed
3749 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3750 * criteria. The platform will evaluate which network is the best at its own discretion.
3751 * Throughput, latency, cost per byte, policy, user preference and other considerations
3752 * may be factored in the decision of what is considered the best network.
3753 *
3754 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3755 * matching this request, while always attempting to match the request to a better network if
3756 * possible. If a better match is found, the platform will switch this request to the now-best
3757 * network and inform the app of the newly best network by invoking
3758 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3759 * will not try to maintain any other network than the best one currently matching the request:
3760 * a network not matching any network request may be disconnected at any time.
3761 *
3762 * <p>For example, an application could use this method to obtain a connected cellular network
3763 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3764 * radio to consume additional power. Or, an application could inform the system that it wants
3765 * a network supporting sending MMSes and have the system let it know about the currently best
3766 * MMS-supporting network through the provided {@link NetworkCallback}.
3767 *
3768 * <p>The status of the request can be followed by listening to the various callbacks described
3769 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3770 * used to direct traffic to the network (although accessing some networks may be subject to
3771 * holding specific permissions). Callers will learn about the specific characteristics of the
3772 * network through
3773 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3774 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3775 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3776 * matching the request at any given time; therefore when a better network matching the request
3777 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3778 * with the new network after which no further updates are given about the previously-best
3779 * network, unless it becomes the best again at some later time. All callbacks are invoked
3780 * in order on the same thread, which by default is a thread created by the framework running
3781 * in the app.
3782 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3783 * callbacks are invoked.
3784 *
3785 * <p>This{@link NetworkRequest} will live until released via
3786 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3787 * which point the system may let go of the network at any time.
3788 *
3789 * <p>A version of this method which takes a timeout is
3790 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3791 * wait for a limited amount of time for the network to become unavailable.
3792 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003793 * <p>It is presently unsupported to request a network with mutable
3794 * {@link NetworkCapabilities} such as
3795 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3796 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3797 * as these {@code NetworkCapabilities} represent states that a particular
3798 * network may never attain, and whether a network will attain these states
3799 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09003800 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003801 *
3802 * <p>This method requires the caller to hold either the
3803 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3804 * or the ability to modify system settings as determined by
3805 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003806 *
Chalard Jean7f06b342020-05-20 16:11:50 +09003807 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3808 * number of outstanding requests to 100 per app (identified by their UID), shared with
3809 * all variants of this method, of {@link #registerNetworkCallback} as well as
3810 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3811 * Requesting a network with this method will count toward this limit. If this limit is
3812 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3813 * make sure to unregister the callbacks with
3814 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3815 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003816 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003817 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3818 * the callback must not be shared - it uniquely specifies this request.
3819 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09003820 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3821 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09003822 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003823 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003824 public void requestNetwork(@NonNull NetworkRequest request,
3825 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003826 requestNetwork(request, networkCallback, getDefaultHandler());
3827 }
3828
3829 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003830 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003831 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003832 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3833 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003834 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003835 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003836 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3837 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003838 *
3839 * @param request {@link NetworkRequest} describing this request.
3840 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3841 * the callback must not be shared - it uniquely specifies this request.
3842 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003843 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003844 public void requestNetwork(@NonNull NetworkRequest request,
3845 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003846 CallbackHandler cbHandler = new CallbackHandler(handler);
markchieneddbe2b2020-03-18 21:16:15 +08003847 NetworkCapabilities nc = request.networkCapabilities;
3848 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003849 }
3850
3851 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003852 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohen67e58a02017-03-01 12:47:28 -08003853 * by a timeout.
3854 *
3855 * This function behaves identically to the non-timed-out version
3856 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3857 * is not found within the given time (in milliseconds) the
3858 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3859 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3860 * not have to be released if timed-out (it is automatically released). Unregistering a
3861 * request that timed out is not an error.
3862 *
3863 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3864 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3865 * for that purpose. Calling this method will attempt to bring up the requested network.
3866 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003867 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003868 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3869 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08003870 *
3871 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003872 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3873 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003874 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3875 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3876 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08003877 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003878 public void requestNetwork(@NonNull NetworkRequest request,
3879 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003880 checkTimeout(timeoutMs);
markchieneddbe2b2020-03-18 21:16:15 +08003881 NetworkCapabilities nc = request.networkCapabilities;
3882 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3883 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003884 }
3885
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003886 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003887 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003888 * by a timeout.
3889 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003890 * This method behaves identically to
3891 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3892 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08003893 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003894 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003895 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3896 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003897 *
3898 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003899 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3900 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003901 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003902 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3903 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003904 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003905 public void requestNetwork(@NonNull NetworkRequest request,
3906 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003907 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003908 CallbackHandler cbHandler = new CallbackHandler(handler);
markchieneddbe2b2020-03-18 21:16:15 +08003909 NetworkCapabilities nc = request.networkCapabilities;
3910 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003911 }
3912
3913 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003914 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003915 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003916 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08003917 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04003918 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3919 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003920 */
Erik Klinefb087f12014-11-19 12:12:24 +09003921 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003922
3923 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003924 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003925 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003926 * {@link android.content.Intent#getParcelableExtra(String)}.
3927 */
Erik Klinefb087f12014-11-19 12:12:24 +09003928 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003929
3930
3931 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003932 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003933 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08003934 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003935 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003936 * the request may outlive the calling application and get called back when a suitable
3937 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003938 * <p>
3939 * The operation is an Intent broadcast that goes to a broadcast receiver that
3940 * you registered with {@link Context#registerReceiver} or through the
3941 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3942 * <p>
3943 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09003944 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3945 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003946 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003947 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003948 * Intent to reserve the network or it will be released shortly after the Intent
3949 * is processed.
3950 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04003951 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003952 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003953 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003954 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08003955 * The request may be released normally by calling
3956 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003957 * <p>It is presently unsupported to request a network with either
3958 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3959 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3960 * as these {@code NetworkCapabilities} represent states that a particular
3961 * network may never attain, and whether a network will attain these states
3962 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09003963 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003964 *
Chalard Jean7f06b342020-05-20 16:11:50 +09003965 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3966 * number of outstanding requests to 100 per app (identified by their UID), shared with
3967 * all variants of this method, of {@link #registerNetworkCallback} as well as
3968 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3969 * Requesting a network with this method will count toward this limit. If this limit is
3970 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3971 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3972 * or {@link #releaseNetworkRequest(PendingIntent)}.
3973 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003974 * <p>This method requires the caller to hold either the
3975 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3976 * or the ability to modify system settings as determined by
3977 * {@link android.provider.Settings.System#canWrite}.</p>
3978 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003979 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003980 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003981 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08003982 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09003983 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3984 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09003985 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003986 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003987 public void requestNetwork(@NonNull NetworkRequest request,
3988 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003989 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003990 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003991 try {
Roshan Pius34dc4be2020-01-16 12:17:17 -08003992 mService.pendingRequestForNetwork(
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07003993 request.networkCapabilities, operation, mContext.getOpPackageName(),
3994 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003995 } catch (RemoteException e) {
3996 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003997 } catch (ServiceSpecificException e) {
3998 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003999 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004000 }
4001
4002 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004003 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4004 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004005 * This method has the same behavior as
4006 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004007 * releasing network resources and disconnecting.
4008 *
4009 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4010 * PendingIntent passed to
4011 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4012 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4013 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004014 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004015 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004016 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004017 try {
4018 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004019 } catch (RemoteException e) {
4020 throw e.rethrowFromSystemServer();
4021 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004022 }
4023
Hugo Benichiff4bf602017-05-09 15:19:01 +09004024 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00004025 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004026 }
4027
4028 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00004029 Preconditions.checkNotNull(callback, "null NetworkCallback");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004030 }
4031
4032 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00004033 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin94c30992014-11-05 10:32:09 -08004034 }
4035
4036 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004037 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004038 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004039 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4040 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004041 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004042 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4043 * number of outstanding requests to 100 per app (identified by their UID), shared with
4044 * all variants of this method, of {@link #requestNetwork} as well as
4045 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4046 * Requesting a network with this method will count toward this limit. If this limit is
4047 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4048 * make sure to unregister the callbacks with
4049 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4050 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004051 * @param request {@link NetworkRequest} describing this request.
4052 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4053 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004054 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004055 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004056 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004057 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004058 public void registerNetworkCallback(@NonNull NetworkRequest request,
4059 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004060 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4061 }
4062
4063 /**
4064 * Registers to receive notifications about all networks which satisfy the given
4065 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004066 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4067 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004068 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004069 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4070 * number of outstanding requests to 100 per app (identified by their UID), shared with
4071 * all variants of this method, of {@link #requestNetwork} as well as
4072 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4073 * Requesting a network with this method will count toward this limit. If this limit is
4074 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4075 * make sure to unregister the callbacks with
4076 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4077 *
4078 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004079 * @param request {@link NetworkRequest} describing this request.
4080 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4081 * networks change state.
4082 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004083 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004084 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004085 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004086 public void registerNetworkCallback(@NonNull NetworkRequest request,
4087 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004088 CallbackHandler cbHandler = new CallbackHandler(handler);
4089 NetworkCapabilities nc = request.networkCapabilities;
4090 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004091 }
4092
4093 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004094 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4095 * {@link NetworkRequest}.
4096 *
4097 * This function behaves identically to the version that takes a NetworkCallback, but instead
4098 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4099 * the request may outlive the calling application and get called back when a suitable
4100 * network is found.
4101 * <p>
4102 * The operation is an Intent broadcast that goes to a broadcast receiver that
4103 * you registered with {@link Context#registerReceiver} or through the
4104 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4105 * <p>
4106 * The operation Intent is delivered with two extras, a {@link Network} typed
4107 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4108 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4109 * the original requests parameters.
4110 * <p>
4111 * If there is already a request for this Intent registered (with the equality of
4112 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4113 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4114 * <p>
4115 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004116 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004117 *
4118 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4119 * number of outstanding requests to 100 per app (identified by their UID), shared with
4120 * all variants of this method, of {@link #requestNetwork} as well as
4121 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4122 * Requesting a network with this method will count toward this limit. If this limit is
4123 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4124 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4125 * or {@link #releaseNetworkRequest(PendingIntent)}.
4126 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004127 * @param request {@link NetworkRequest} describing this request.
4128 * @param operation Action to perform when the network is available (corresponds
4129 * to the {@link NetworkCallback#onAvailable} call. Typically
4130 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004131 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004132 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004133 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004134 public void registerNetworkCallback(@NonNull NetworkRequest request,
4135 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004136 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004137 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004138 try {
Roshan Pius34dc4be2020-01-16 12:17:17 -08004139 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004140 request.networkCapabilities, operation, mContext.getOpPackageName(),
4141 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004142 } catch (RemoteException e) {
4143 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004144 } catch (ServiceSpecificException e) {
4145 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004146 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004147 }
4148
4149 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004150 * Registers to receive notifications about changes in the application's default network. This
4151 * may be a physical network or a virtual network, such as a VPN that applies to the
4152 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004153 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004154 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004155 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4156 * number of outstanding requests to 100 per app (identified by their UID), shared with
4157 * all variants of this method, of {@link #requestNetwork} as well as
4158 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4159 * Requesting a network with this method will count toward this limit. If this limit is
4160 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4161 * make sure to unregister the callbacks with
4162 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4163 *
Erik Klinee0aed632016-03-16 15:31:39 +09004164 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004165 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004166 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004167 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004168 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004169 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004170 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004171 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4172 }
4173
4174 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004175 * Registers to receive notifications about changes in the application's default network. This
4176 * may be a physical network or a virtual network, such as a VPN that applies to the
4177 * application. The callbacks will continue to be called until either the application exits or
4178 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4179 *
4180 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4181 * number of outstanding requests to 100 per app (identified by their UID), shared with
4182 * all variants of this method, of {@link #requestNetwork} as well as
4183 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4184 * Requesting a network with this method will count toward this limit. If this limit is
4185 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4186 * make sure to unregister the callbacks with
4187 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4188 *
4189 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4190 * application's default network changes.
4191 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4192 * @throws RuntimeException if the app already has too many callbacks registered.
4193 */
4194 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4195 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4196 @NonNull Handler handler) {
4197 CallbackHandler cbHandler = new CallbackHandler(handler);
4198 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4199 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4200 }
4201
4202 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004203 * Registers to receive notifications about changes in the system default network. The callbacks
4204 * will continue to be called until either the application exits or
4205 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004206 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004207 * This method should not be used to determine networking state seen by applications, because in
4208 * many cases, most or even all application traffic may not use the default network directly,
4209 * and traffic from different applications may go on different networks by default. As an
4210 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4211 * and not onto the system default network. Applications or system components desiring to do
4212 * determine network state as seen by applications should use other methods such as
4213 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4214 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004215 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4216 * number of outstanding requests to 100 per app (identified by their UID), shared with
4217 * all variants of this method, of {@link #requestNetwork} as well as
4218 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4219 * Requesting a network with this method will count toward this limit. If this limit is
4220 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4221 * make sure to unregister the callbacks with
4222 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4223 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004224 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4225 * system default network changes.
4226 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004227 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004228 *
4229 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004230 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004231 @SystemApi(client = MODULE_LIBRARIES)
4232 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4233 @RequiresPermission(anyOf = {
4234 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4235 android.Manifest.permission.NETWORK_SETTINGS})
4236 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004237 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004238 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004239 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004240 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004241 }
4242
4243 /**
junyulai6b0a6a22021-03-05 15:51:17 +08004244 * @hide
4245 */
4246 // TODO: Make it public api.
4247 @SuppressLint("ExecutorRegistration")
4248 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4249 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4250 final NetworkCapabilities nc = request.networkCapabilities;
4251 final CallbackHandler cbHandler = new CallbackHandler(handler);
4252 sendRequestForNetwork(nc, networkCallback, 0, TRACK_BEST, TYPE_NONE, cbHandler);
4253 }
4254
4255 /**
fenglu73169332015-04-21 17:12:05 -07004256 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4257 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4258 * network connection for updated bandwidth information. The caller will be notified via
4259 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004260 * method assumes that the caller has previously called
4261 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4262 * changes.
fenglu76564332015-03-20 11:29:56 -07004263 *
fenglu41808e82015-04-27 14:28:04 -07004264 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004265 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004266 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004267 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004268 try {
fenglu73169332015-04-21 17:12:05 -07004269 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004270 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004271 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004272 }
4273 }
4274
4275 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004276 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004277 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4278 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4279 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004280 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4281 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004282 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004283 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4284 * triggering it as soon as this call returns.
4285 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004286 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004287 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004288 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004289 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004290 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004291 final List<NetworkRequest> reqs = new ArrayList<>();
4292 // Find all requests associated to this callback and stop callback triggers immediately.
4293 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4294 synchronized (sCallbacks) {
Remi NGUYEN VAN00c531f2021-03-15 07:27:44 +00004295 Preconditions.checkArgument(networkCallback.networkRequest != null,
4296 "NetworkCallback was not registered");
Etan Cohene0e2ca92019-04-16 15:07:55 -07004297 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4298 Log.d(TAG, "NetworkCallback was already unregistered");
4299 return;
4300 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004301 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4302 if (e.getValue() == networkCallback) {
4303 reqs.add(e.getKey());
4304 }
4305 }
4306 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4307 for (NetworkRequest r : reqs) {
4308 try {
4309 mService.releaseNetworkRequest(r);
4310 } catch (RemoteException e) {
4311 throw e.rethrowFromSystemServer();
4312 }
4313 // Only remove mapping if rpc was successful.
4314 sCallbacks.remove(r);
4315 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004316 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004317 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004318 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004319
4320 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004321 * Unregisters a callback previously registered via
4322 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4323 *
4324 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4325 * PendingIntent passed to
4326 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4327 * Cannot be null.
4328 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004329 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004330 releaseNetworkRequest(operation);
4331 }
4332
4333 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004334 * Informs the system whether it should switch to {@code network} regardless of whether it is
4335 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4336 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4337 * the system default network regardless of any other network that's currently connected. If
4338 * {@code always} is true, then the choice is remembered, so that the next time the user
4339 * connects to this network, the system will switch to it.
4340 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004341 * @param network The network to accept.
4342 * @param accept Whether to accept the network even if unvalidated.
4343 * @param always Whether to remember this choice in the future.
4344 *
4345 * @hide
4346 */
lucaslin25a50472019-03-12 13:08:03 +08004347 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004348 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4349 try {
4350 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004351 } catch (RemoteException e) {
4352 throw e.rethrowFromSystemServer();
4353 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004354 }
4355
4356 /**
lucaslin25a50472019-03-12 13:08:03 +08004357 * Informs the system whether it should consider the network as validated even if it only has
4358 * partial connectivity. If {@code accept} is true, then the network will be considered as
4359 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4360 * is remembered, so that the next time the user connects to this network, the system will
4361 * switch to it.
4362 *
4363 * @param network The network to accept.
4364 * @param accept Whether to consider the network as validated even if it has partial
4365 * connectivity.
4366 * @param always Whether to remember this choice in the future.
4367 *
4368 * @hide
4369 */
4370 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4371 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4372 try {
4373 mService.setAcceptPartialConnectivity(network, accept, always);
4374 } catch (RemoteException e) {
4375 throw e.rethrowFromSystemServer();
4376 }
4377 }
4378
4379 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004380 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4381 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4382 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4383 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4384 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004385 * @param network The network to accept.
4386 *
4387 * @hide
4388 */
lucaslin25a50472019-03-12 13:08:03 +08004389 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004390 public void setAvoidUnvalidated(Network network) {
4391 try {
4392 mService.setAvoidUnvalidated(network);
4393 } catch (RemoteException e) {
4394 throw e.rethrowFromSystemServer();
4395 }
4396 }
4397
4398 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004399 * Requests that the system open the captive portal app on the specified network.
4400 *
4401 * @param network The network to log into.
4402 *
4403 * @hide
4404 */
paulhud70b7dd2019-08-12 16:25:11 +08004405 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004406 public void startCaptivePortalApp(Network network) {
4407 try {
4408 mService.startCaptivePortalApp(network);
4409 } catch (RemoteException e) {
4410 throw e.rethrowFromSystemServer();
4411 }
4412 }
4413
4414 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004415 * Requests that the system open the captive portal app with the specified extras.
4416 *
4417 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4418 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004419 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004420 * @param appExtras Extras to include in the app start intent.
4421 * @hide
4422 */
4423 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004424 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004425 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004426 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004427 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004428 } catch (RemoteException e) {
4429 throw e.rethrowFromSystemServer();
4430 }
4431 }
4432
4433 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004434 * Determine whether the device is configured to avoid bad wifi.
4435 * @hide
4436 */
4437 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004438 @RequiresPermission(anyOf = {
4439 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4440 android.Manifest.permission.NETWORK_STACK})
4441 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004442 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004443 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004444 } catch (RemoteException e) {
4445 throw e.rethrowFromSystemServer();
4446 }
4447 }
4448
4449 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004450 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4451 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004452 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4453 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004454 *
4455 * An example of such an operation might be a time-sensitive foreground activity, such as a
4456 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4457 */
4458 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4459
4460 /**
4461 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4462 * a backup channel for traffic that is primarily going over another network.
4463 *
4464 * An example might be maintaining backup connections to peers or servers for the purpose of
4465 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4466 * on backup paths should be negligible compared to the traffic on the main path.
4467 */
4468 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4469
4470 /**
4471 * It is acceptable to use metered data to improve network latency and performance.
4472 */
4473 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4474
4475 /**
4476 * Return value to use for unmetered networks. On such networks we currently set all the flags
4477 * to true.
4478 * @hide
4479 */
4480 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4481 MULTIPATH_PREFERENCE_HANDOVER |
4482 MULTIPATH_PREFERENCE_RELIABILITY |
4483 MULTIPATH_PREFERENCE_PERFORMANCE;
4484
4485 /** @hide */
4486 @Retention(RetentionPolicy.SOURCE)
4487 @IntDef(flag = true, value = {
4488 MULTIPATH_PREFERENCE_HANDOVER,
4489 MULTIPATH_PREFERENCE_RELIABILITY,
4490 MULTIPATH_PREFERENCE_PERFORMANCE,
4491 })
4492 public @interface MultipathPreference {
4493 }
4494
4495 /**
4496 * Provides a hint to the calling application on whether it is desirable to use the
4497 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4498 * for multipath data transfer on this network when it is not the system default network.
4499 * Applications desiring to use multipath network protocols should call this method before
4500 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004501 *
4502 * @param network The network on which the application desires to use multipath data.
4503 * If {@code null}, this method will return the a preference that will generally
4504 * apply to metered networks.
4505 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4506 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004507 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004508 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004509 try {
4510 return mService.getMultipathPreference(network);
4511 } catch (RemoteException e) {
4512 throw e.rethrowFromSystemServer();
4513 }
4514 }
4515
4516 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004517 * Resets all connectivity manager settings back to factory defaults.
4518 * @hide
4519 */
paulhud70b7dd2019-08-12 16:25:11 +08004520 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scottd3bb5082015-03-30 13:17:11 -07004521 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004522 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004523 mService.factoryReset();
Amos Bianchiddadca42020-03-04 11:07:38 -08004524 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004525 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004526 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004527 }
4528 }
4529
4530 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004531 * Binds the current process to {@code network}. All Sockets created in the future
4532 * (and not explicitly bound via a bound SocketFactory from
4533 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4534 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4535 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4536 * work and all host name resolutions will fail. This is by design so an application doesn't
4537 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4538 * To clear binding pass {@code null} for {@code network}. Using individually bound
4539 * Sockets created by Network.getSocketFactory().createSocket() and
4540 * performing network-specific host name resolutions via
4541 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004542 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004543 *
4544 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4545 * the current binding.
4546 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4547 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004548 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004549 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004550 // instantiated.
4551 return setProcessDefaultNetwork(network);
4552 }
4553
4554 /**
4555 * Binds the current process to {@code network}. All Sockets created in the future
4556 * (and not explicitly bound via a bound SocketFactory from
4557 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4558 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4559 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4560 * work and all host name resolutions will fail. This is by design so an application doesn't
4561 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4562 * To clear binding pass {@code null} for {@code network}. Using individually bound
4563 * Sockets created by Network.getSocketFactory().createSocket() and
4564 * performing network-specific host name resolutions via
4565 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4566 * {@code setProcessDefaultNetwork}.
4567 *
4568 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4569 * the current binding.
4570 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4571 * @deprecated This function can throw {@link IllegalStateException}. Use
4572 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4573 * is a direct replacement.
4574 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004575 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004576 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004577 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004578 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4579
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004580 if (netId != NETID_UNSET) {
4581 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004582 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004583
4584 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4585 return false;
4586 }
4587
4588 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004589 // Set HTTP proxy system properties to match network.
4590 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004591 try {
Remi NGUYEN VAN9ff113b2021-02-03 10:18:20 +09004592 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004593 } catch (SecurityException e) {
4594 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4595 Log.e(TAG, "Can't set proxy properties", e);
4596 }
Paul Jensen99c36662014-08-27 12:38:45 -04004597 // Must flush DNS cache as new network may have different DNS resolutions.
4598 InetAddress.clearDnsCache();
4599 // Must flush socket pool as idle sockets will be bound to previous network and may
4600 // cause subsequent fetches to be performed on old network.
4601 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004602 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004603
4604 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004605 }
4606
4607 /**
4608 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004609 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004610 *
4611 * @return {@code Network} to which this process is bound, or {@code null}.
4612 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004613 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004614 public Network getBoundNetworkForProcess() {
4615 // Forcing callers to call thru non-static function ensures ConnectivityManager
4616 // instantiated.
4617 return getProcessDefaultNetwork();
4618 }
4619
4620 /**
4621 * Returns the {@link Network} currently bound to this process via
4622 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4623 *
4624 * @return {@code Network} to which this process is bound, or {@code null}.
4625 * @deprecated Using this function can lead to other functions throwing
4626 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4627 * {@code getBoundNetworkForProcess} is a direct replacement.
4628 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004629 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004630 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004631 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004632 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004633 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004634 return new Network(netId);
4635 }
4636
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004637 private void unsupportedStartingFrom(int version) {
4638 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004639 // The getApplicationInfo() call we make below is not supported in system context. Let
4640 // the call through here, and rely on the fact that ConnectivityService will refuse to
4641 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004642 return;
4643 }
4644
4645 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4646 throw new UnsupportedOperationException(
4647 "This method is not supported in target SDK version " + version + " and above");
4648 }
4649 }
4650
4651 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4652 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004653 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004654 // remove these exemptions. Note that this check is not secure, and apps can still access these
4655 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4656 // so is unsupported and may break in the future. http://b/22728205
4657 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07004658 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004659 }
4660
Paul Jensene98c6e02014-05-29 10:12:39 -04004661 /**
4662 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04004663 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04004664 *
4665 * @param network The {@link Network} to bind host resolutions from the current process to, or
4666 * {@code null} to clear the current binding.
4667 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4668 * @hide
4669 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4670 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004671 @Deprecated
Mathew Inwood5a09a712020-11-04 09:29:36 +00004672 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04004673 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04004674 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09004675 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04004676 }
Felipe Lemed16384b2016-01-22 09:44:57 -08004677
4678 /**
4679 * Device is not restricting metered network activity while application is running on
4680 * background.
4681 */
4682 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4683
4684 /**
4685 * Device is restricting metered network activity while application is running on background,
4686 * but application is allowed to bypass it.
4687 * <p>
4688 * In this state, application should take action to mitigate metered network access.
4689 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4690 */
4691 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4692
4693 /**
4694 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08004695 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08004696 * In this state, application should not try to use the network while running on background,
4697 * because it would be denied.
4698 */
4699 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4700
Felipe Leme6a5b7692016-01-27 14:46:39 -08004701 /**
4702 * A change in the background metered network activity restriction has occurred.
4703 * <p>
4704 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4705 * applies to them.
4706 * <p>
4707 * This is only sent to registered receivers, not manifest receivers.
4708 */
4709 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4710 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4711 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4712
Felipe Leme1b42ef92016-01-25 11:48:04 -08004713 /** @hide */
4714 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08004715 @IntDef(flag = false, value = {
4716 RESTRICT_BACKGROUND_STATUS_DISABLED,
4717 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4718 RESTRICT_BACKGROUND_STATUS_ENABLED,
4719 })
Felipe Lemed16384b2016-01-22 09:44:57 -08004720 public @interface RestrictBackgroundStatus {
4721 }
4722
4723 private INetworkPolicyManager getNetworkPolicyManager() {
4724 synchronized (this) {
4725 if (mNPManager != null) {
4726 return mNPManager;
4727 }
4728 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4729 .getService(Context.NETWORK_POLICY_SERVICE));
4730 return mNPManager;
4731 }
4732 }
4733
4734 /**
4735 * Determines if the calling application is subject to metered network restrictions while
4736 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07004737 *
4738 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4739 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4740 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08004741 */
4742 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4743 try {
4744 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4745 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004746 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08004747 }
4748 }
Ricky Waid53cf002018-01-23 04:09:45 +00004749
4750 /**
4751 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00004752 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4753 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00004754 *
4755 * @return Hash of network watchlist config file. Null if config does not exist.
4756 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004757 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00004758 public byte[] getNetworkWatchlistConfigHash() {
4759 try {
4760 return mService.getNetworkWatchlistConfigHash();
4761 } catch (RemoteException e) {
4762 Log.e(TAG, "Unable to get watchlist config hash");
4763 throw e.rethrowFromSystemServer();
4764 }
4765 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004766
4767 /**
4768 * Returns the {@code uid} of the owner of a network connection.
4769 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08004770 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4771 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004772 * @param local The local {@link InetSocketAddress} of a connection.
4773 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004774 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08004775 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4776 * android.os.Process#INVALID_UID} if the connection is not found.
4777 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4778 * user.
4779 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004780 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08004781 public int getConnectionOwnerUid(
4782 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004783 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4784 try {
4785 return mService.getConnectionOwnerUid(connectionInfo);
4786 } catch (RemoteException e) {
4787 throw e.rethrowFromSystemServer();
4788 }
4789 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004790
4791 private void printStackTrace() {
4792 if (DEBUG) {
4793 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4794 final StringBuffer sb = new StringBuffer();
4795 for (int i = 3; i < callStack.length; i++) {
4796 final String stackTrace = callStack[i].toString();
4797 if (stackTrace == null || stackTrace.contains("android.os")) {
4798 break;
4799 }
4800 sb.append(" [").append(stackTrace).append("]");
4801 }
4802 Log.d(TAG, "StackLog:" + sb.toString());
4803 }
4804 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004805
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004806 /** @hide */
4807 public TestNetworkManager startOrGetTestNetworkManager() {
4808 final IBinder tnBinder;
4809 try {
4810 tnBinder = mService.startOrGetTestNetworkService();
4811 } catch (RemoteException e) {
4812 throw e.rethrowFromSystemServer();
4813 }
4814
4815 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4816 }
4817
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004818 /** @hide */
4819 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4820 return new ConnectivityDiagnosticsManager(mContext, mService);
4821 }
4822
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004823 /**
4824 * Simulates a Data Stall for the specified Network.
4825 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004826 * <p>This method should only be used for tests.
4827 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004828 * <p>The caller must be the owner of the specified Network.
4829 *
4830 * @param detectionMethod The detection method used to identify the Data Stall.
4831 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4832 * @param network The Network for which a Data Stall is being simluated.
4833 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4834 * @throws SecurityException if the caller is not the owner of the given network.
4835 * @hide
4836 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004837 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004838 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4839 android.Manifest.permission.NETWORK_STACK})
4840 public void simulateDataStall(int detectionMethod, long timestampMillis,
4841 @NonNull Network network, @NonNull PersistableBundle extras) {
4842 try {
4843 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4844 } catch (RemoteException e) {
4845 e.rethrowFromSystemServer();
4846 }
4847 }
James Mattisdcea9fb2020-10-28 21:48:54 -07004848
Daniel Bright60f02ed2020-06-15 16:10:01 -07004849 @NonNull
4850 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4851
4852 /**
4853 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4854 * receive available QoS events related to the {@link Network} and local ip + port
4855 * specified within socketInfo.
4856 * <p/>
4857 * The same {@link QosCallback} must be unregistered before being registered a second time,
4858 * otherwise {@link QosCallbackRegistrationException} is thrown.
4859 * <p/>
4860 * This API does not, in itself, require any permission if called with a network that is not
4861 * restricted. However, the underlying implementation currently only supports the IMS network,
4862 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4863 * useful, because they'd never be called back on networks that they would have access to.
4864 *
4865 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4866 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4867 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4868 * @throws RuntimeException if the app already has too many callbacks registered.
4869 *
4870 * Exceptions after the time of registration is passed through
4871 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4872 *
4873 * @param socketInfo the socket information used to match QoS events
4874 * @param callback receives qos events that satisfy socketInfo
4875 * @param executor The executor on which the callback will be invoked. The provided
4876 * {@link Executor} must run callback sequentially, otherwise the order of
4877 * callbacks cannot be guaranteed.
4878 *
4879 * @hide
4880 */
4881 @SystemApi
4882 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4883 @NonNull final QosCallback callback,
4884 @CallbackExecutor @NonNull final Executor executor) {
4885 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4886 Objects.requireNonNull(callback, "callback must be non-null");
4887 Objects.requireNonNull(executor, "executor must be non-null");
4888
4889 try {
4890 synchronized (mQosCallbackConnections) {
4891 if (getQosCallbackConnection(callback) == null) {
4892 final QosCallbackConnection connection =
4893 new QosCallbackConnection(this, callback, executor);
4894 mQosCallbackConnections.add(connection);
4895 mService.registerQosSocketCallback(socketInfo, connection);
4896 } else {
4897 Log.e(TAG, "registerQosCallback: Callback already registered");
4898 throw new QosCallbackRegistrationException();
4899 }
4900 }
4901 } catch (final RemoteException e) {
4902 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4903
4904 // The same unregister method method is called for consistency even though nothing
4905 // will be sent to the ConnectivityService since the callback was never successfully
4906 // registered.
4907 unregisterQosCallback(callback);
4908 e.rethrowFromSystemServer();
4909 } catch (final ServiceSpecificException e) {
4910 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4911 unregisterQosCallback(callback);
4912 throw convertServiceException(e);
4913 }
4914 }
4915
4916 /**
4917 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4918 * events once unregistered and can be registered a second time.
4919 * <p/>
4920 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4921 *
4922 * @param callback the callback being unregistered
4923 *
4924 * @hide
4925 */
4926 @SystemApi
4927 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4928 Objects.requireNonNull(callback, "The callback must be non-null");
4929 try {
4930 synchronized (mQosCallbackConnections) {
4931 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4932 if (connection != null) {
4933 connection.stopReceivingMessages();
4934 mService.unregisterQosCallback(connection);
4935 mQosCallbackConnections.remove(connection);
4936 } else {
4937 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4938 }
4939 }
4940 } catch (final RemoteException e) {
4941 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4942 e.rethrowFromSystemServer();
4943 }
4944 }
4945
4946 /**
4947 * Gets the connection related to the callback.
4948 *
4949 * @param callback the callback to look up
4950 * @return the related connection
4951 */
4952 @Nullable
4953 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4954 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4955 // Checking by reference here is intentional
4956 if (connection.getCallback() == callback) {
4957 return connection;
4958 }
4959 }
4960 return null;
4961 }
Junyu Lai23568a42021-01-19 11:10:56 +00004962
4963 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004964 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Lai23568a42021-01-19 11:10:56 +00004965 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4966 * be used to request that the system provide a network without causing the network to be
4967 * in the foreground.
4968 *
4969 * <p>This method will attempt to find the best network that matches the passed
4970 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4971 * criteria. The platform will evaluate which network is the best at its own discretion.
4972 * Throughput, latency, cost per byte, policy, user preference and other considerations
4973 * may be factored in the decision of what is considered the best network.
4974 *
4975 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4976 * matching this request, while always attempting to match the request to a better network if
4977 * possible. If a better match is found, the platform will switch this request to the now-best
4978 * network and inform the app of the newly best network by invoking
4979 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4980 * will not try to maintain any other network than the best one currently matching the request:
4981 * a network not matching any network request may be disconnected at any time.
4982 *
4983 * <p>For example, an application could use this method to obtain a connected cellular network
4984 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4985 * radio to consume additional power. Or, an application could inform the system that it wants
4986 * a network supporting sending MMSes and have the system let it know about the currently best
4987 * MMS-supporting network through the provided {@link NetworkCallback}.
4988 *
4989 * <p>The status of the request can be followed by listening to the various callbacks described
4990 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4991 * used to direct traffic to the network (although accessing some networks may be subject to
4992 * holding specific permissions). Callers will learn about the specific characteristics of the
4993 * network through
4994 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4995 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4996 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4997 * matching the request at any given time; therefore when a better network matching the request
4998 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4999 * with the new network after which no further updates are given about the previously-best
5000 * network, unless it becomes the best again at some later time. All callbacks are invoked
5001 * in order on the same thread, which by default is a thread created by the framework running
5002 * in the app.
5003 *
5004 * <p>This{@link NetworkRequest} will live until released via
5005 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5006 * which point the system may let go of the network at any time.
5007 *
5008 * <p>It is presently unsupported to request a network with mutable
5009 * {@link NetworkCapabilities} such as
5010 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5011 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5012 * as these {@code NetworkCapabilities} represent states that a particular
5013 * network may never attain, and whether a network will attain these states
5014 * is unknown prior to bringing up the network so the framework does not
5015 * know how to go about satisfying a request with these capabilities.
5016 *
5017 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5018 * number of outstanding requests to 100 per app (identified by their UID), shared with
5019 * all variants of this method, of {@link #registerNetworkCallback} as well as
5020 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5021 * Requesting a network with this method will count toward this limit. If this limit is
5022 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5023 * make sure to unregister the callbacks with
5024 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5025 *
5026 * @param request {@link NetworkRequest} describing this request.
5027 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5028 * If null, the callback is invoked on the default internal Handler.
5029 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5030 * the callback must not be shared - it uniquely specifies this request.
5031 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5032 * @throws SecurityException if missing the appropriate permissions.
5033 * @throws RuntimeException if the app already has too many callbacks registered.
5034 *
5035 * @hide
5036 */
5037 @SystemApi(client = MODULE_LIBRARIES)
5038 @SuppressLint("ExecutorRegistration")
5039 @RequiresPermission(anyOf = {
5040 android.Manifest.permission.NETWORK_SETTINGS,
5041 android.Manifest.permission.NETWORK_STACK,
5042 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5043 })
5044 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaif4bc12f2021-03-09 20:49:48 +08005045 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Lai23568a42021-01-19 11:10:56 +00005046 final NetworkCapabilities nc = request.networkCapabilities;
5047 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaif4bc12f2021-03-09 20:49:48 +08005048 TYPE_NONE, new CallbackHandler(handler));
Junyu Lai23568a42021-01-19 11:10:56 +00005049 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005050
5051 /**
5052 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
5053 * OnSetOemNetworkPreferenceListener)}.
James Mattis7a253542021-01-26 16:23:52 -08005054 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005055 */
James Mattis7a253542021-01-26 16:23:52 -08005056 @SystemApi
5057 public interface OnSetOemNetworkPreferenceListener {
James Mattis6e6fabf2021-01-10 14:24:24 -08005058 /**
5059 * Called when setOemNetworkPreference() successfully completes.
5060 */
5061 void onComplete();
5062 }
5063
5064 /**
5065 * Used by automotive devices to set the network preferences used to direct traffic at an
5066 * application level as per the given OemNetworkPreferences. An example use-case would be an
5067 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5068 * vehicle via a particular network.
5069 *
5070 * Calling this will overwrite the existing preference.
5071 *
5072 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5073 * @param executor the executor on which listener will be invoked.
5074 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5075 * communicate completion of setOemNetworkPreference(). This will only be
5076 * called once upon successful completion of setOemNetworkPreference().
5077 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5078 * @throws SecurityException if missing the appropriate permissions.
5079 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005080 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005081 */
James Mattis7a253542021-01-26 16:23:52 -08005082 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005083 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005084 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005085 @Nullable @CallbackExecutor final Executor executor,
5086 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5087 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5088 if (null != listener) {
5089 Objects.requireNonNull(executor, "Executor must be non-null");
5090 }
5091 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5092 new IOnSetOemNetworkPreferenceListener.Stub() {
5093 @Override
5094 public void onComplete() {
5095 executor.execute(listener::onComplete);
5096 }
5097 };
5098
5099 try {
5100 mService.setOemNetworkPreference(preference, listenerInternal);
5101 } catch (RemoteException e) {
5102 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5103 throw e.rethrowFromSystemServer();
5104 }
5105 }
lucaslin1a6095c2021-03-12 00:46:33 +08005106
5107 // The first network ID of IPSec tunnel interface.
5108 private static final int TUN_INTF_NETID_START = 0xFC00;
5109 // The network ID range of IPSec tunnel interface.
5110 private static final int TUN_INTF_NETID_RANGE = 0x0400;
5111
5112 /**
5113 * Get the network ID range reserved for IPSec tunnel interfaces.
5114 *
5115 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5116 * @hide
5117 */
5118 @SystemApi(client = MODULE_LIBRARIES)
5119 @NonNull
5120 public static Range<Integer> getIpSecNetIdRange() {
5121 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5122 }
lucaslin8f026612021-03-12 17:56:09 +08005123
5124 /**
5125 * Get private DNS mode from settings.
5126 *
lucaslin11626622021-03-16 17:11:14 +08005127 * @param context The Context to get its ContentResolver to query the private DNS mode from
5128 * settings.
lucaslin8f026612021-03-12 17:56:09 +08005129 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5130 *
5131 * @hide
5132 */
5133 @SystemApi(client = MODULE_LIBRARIES)
5134 @NonNull
5135 @PrivateDnsMode
lucaslin11626622021-03-16 17:11:14 +08005136 public static String getPrivateDnsMode(@NonNull Context context) {
5137 final ContentResolver cr = context.getContentResolver();
lucaslin8f026612021-03-12 17:56:09 +08005138 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5139 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5140 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5141 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5142 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5143 return mode;
5144 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005145}