blob: 3a9731f26225a256c7263e7b54cf35c08deaceea [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Project28527d22009-03-03 19:31:44 -080016package android.net;
17
Junyu Lai23568a42021-01-19 11:10:56 +000018import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
paulhu79260c22021-03-17 20:30:33 +080019import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_DEFAULT_MODE;
20import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE;
Junyu Lai23568a42021-01-19 11:10:56 +000021import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaid1a78162021-01-11 16:53:38 +080022import static android.net.NetworkRequest.Type.LISTEN;
junyulai8cae3c72021-03-12 20:05:08 +080023import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
junyulaid1a78162021-01-11 16:53:38 +080024import static android.net.NetworkRequest.Type.REQUEST;
25import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +090026import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Bright60f02ed2020-06-15 16:10:01 -070027import static android.net.QosCallback.QosCallbackRegistrationException;
junyulai48a59382019-01-15 11:32:44 +080028
junyulaia86defc2018-12-27 17:25:29 +080029import android.annotation.CallbackExecutor;
Felipe Lemed16384b2016-01-22 09:44:57 -080030import android.annotation.IntDef;
Chalard Jean42a9c292019-01-07 19:26:34 +090031import android.annotation.NonNull;
Robin Lee33c73e22016-01-05 18:03:46 +000032import android.annotation.Nullable;
Jeff Sharkey2ac62992017-04-24 11:18:03 -060033import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080034import android.annotation.SdkConstant;
35import android.annotation.SdkConstant.SdkConstantType;
lucaslin50205af2021-03-12 16:11:27 +080036import android.annotation.StringDef;
Junyu Lai23568a42021-01-19 11:10:56 +000037import android.annotation.SuppressLint;
Udam Saini53b71ee2016-01-04 12:16:14 -080038import android.annotation.SystemApi;
Jeff Sharkeyb8c73032017-06-02 17:36:26 -060039import android.annotation.SystemService;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070040import android.app.PendingIntent;
Lorenzo Colitti60104f52021-03-18 00:54:57 +090041import android.app.admin.DevicePolicyManager;
Artur Satayevb9ea02f2019-12-10 17:47:52 +000042import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti60104f52021-03-18 00:54:57 +090043import android.content.ComponentName;
lucaslin50205af2021-03-12 16:11:27 +080044import android.content.ContentResolver;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070045import android.content.Context;
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -070046import android.content.Intent;
junyulaia86defc2018-12-27 17:25:29 +080047import android.net.IpSecManager.UdpEncapsulationSocket;
48import android.net.SocketKeepalive.Callback;
markchien10ddd022020-01-20 19:31:56 +080049import android.net.TetheringManager.StartTetheringCallback;
markchien75721e42020-01-21 13:11:06 +080050import android.net.TetheringManager.TetheringEventCallback;
markchien10ddd022020-01-20 19:31:56 +080051import android.net.TetheringManager.TetheringRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -080052import android.net.wifi.WifiNetworkSuggestion;
Robert Greenwalt2034b912009-08-12 16:08:25 -070053import android.os.Binder;
Mathew Inwoodac5968e2018-12-20 15:30:45 +000054import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070055import android.os.Build.VERSION_CODES;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080056import android.os.Bundle;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070057import android.os.Handler;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080058import android.os.IBinder;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070059import android.os.Looper;
60import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070061import android.os.Messenger;
junyulai61143782019-03-04 22:45:36 +080062import android.os.ParcelFileDescriptor;
Cody Kestingb5c7abd2020-04-15 12:33:28 -070063import android.os.PersistableBundle;
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +090064import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.os.RemoteException;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080066import android.os.ResultReceiver;
Hugo Benichi145e3792017-05-11 13:16:17 +090067import android.os.ServiceSpecificException;
Chalard Jean03433052021-02-25 17:23:40 +090068import android.os.UserHandle;
Jeff Sharkey971cd162011-08-29 16:02:57 -070069import android.provider.Settings;
Wink Saville02eb35c2014-12-05 11:10:30 -080070import android.telephony.SubscriptionManager;
Meng Wang91311c02019-11-18 17:10:00 -080071import android.telephony.TelephonyManager;
lucaslin50205af2021-03-12 16:11:27 +080072import android.text.TextUtils;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080073import android.util.ArrayMap;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070074import android.util.Log;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090075import android.util.Range;
Erik Kline50068e52017-01-26 18:08:28 +090076import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080077
markchien75721e42020-01-21 13:11:06 +080078import com.android.internal.annotations.GuardedBy;
Robert Greenwalt3d6c9582014-05-21 20:04:36 -070079
Paul Jensen99c36662014-08-27 12:38:45 -040080import libcore.net.event.NetworkEventDispatcher;
81
junyulai61143782019-03-04 22:45:36 +080082import java.io.IOException;
83import java.io.UncheckedIOException;
Felipe Lemed16384b2016-01-22 09:44:57 -080084import java.lang.annotation.Retention;
85import java.lang.annotation.RetentionPolicy;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090086import java.net.DatagramSocket;
Jeremy Klein04863332015-12-28 15:11:58 -080087import java.net.InetAddress;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -070088import java.net.InetSocketAddress;
junyulaic7ea1242019-01-08 20:04:33 +080089import java.net.Socket;
Hugo Benichi45a49542017-03-06 09:17:06 +090090import java.util.ArrayList;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090091import java.util.Collection;
Jeremy Klein04863332015-12-28 15:11:58 -080092import java.util.HashMap;
Hugo Benichi45a49542017-03-06 09:17:06 +090093import java.util.List;
94import java.util.Map;
markchien75721e42020-01-21 13:11:06 +080095import java.util.Objects;
junyulaia86defc2018-12-27 17:25:29 +080096import java.util.concurrent.Executor;
junyulai9f872232019-01-16 20:23:34 +080097import java.util.concurrent.ExecutorService;
98import java.util.concurrent.Executors;
99import java.util.concurrent.RejectedExecutionException;
Jeremy Klein04863332015-12-28 15:11:58 -0800100
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101/**
102 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600103 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800104 * <p>
105 * The primary responsibilities of this class are to:
106 * <ol>
107 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
108 * <li>Send broadcast intents when network connectivity changes</li>
109 * <li>Attempt to "fail over" to another network when connectivity to a network
110 * is lost</li>
111 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
112 * state of the available networks</li>
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700113 * <li>Provide an API that allows applications to request and select networks for their data
114 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800115 * </ol>
116 */
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600117@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700118public class ConnectivityManager {
119 private static final String TAG = "ConnectivityManager";
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +0900120 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700121
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700123 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800124 * been established or lost. The NetworkInfo for the affected network is
125 * sent as an extra; it should be consulted to see what kind of
126 * connectivity event occurred.
127 * <p/>
Mark Lue1682a02016-12-05 10:57:55 -0800128 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
129 * broadcast if they declare the broadcast receiver in their manifest. Apps
130 * will still receive broadcasts if they register their
131 * {@link android.content.BroadcastReceiver} with
132 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
133 * and that context is still valid.
134 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135 * If this is a connection that was the result of failing over from a
136 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
137 * set to true.
138 * <p/>
139 * For a loss of connectivity, if the connectivity manager is attempting
140 * to connect (or has already connected) to another network, the
141 * NetworkInfo for the new network is also passed as an extra. This lets
142 * any receivers of the broadcast know that they should not necessarily
143 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt26744a52013-02-15 10:56:35 -0800144 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145 * the failover attempt succeeded (and so there is still overall data
146 * connectivity), or that the failover attempt failed, meaning that all
147 * connectivity has been lost.
148 * <p/>
149 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
150 * is set to {@code true} if there are no connected networks at all.
Chalard Jeanae2424a2018-02-10 05:33:50 +0900151 *
152 * @deprecated apps should use the more versatile {@link #requestNetwork},
153 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
154 * functions instead for faster and more detailed updates about the network
155 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800157 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jeanae2424a2018-02-10 05:33:50 +0900158 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700160
The Android Open Source Project28527d22009-03-03 19:31:44 -0800161 /**
Paul Jensened4d55c2015-02-27 22:55:47 -0500162 * The device has connected to a network that has presented a captive
163 * portal, which is blocking Internet connectivity. The user was presented
164 * with a notification that network sign in is required,
165 * and the user invoked the notification's action indicating they
Paul Jensen4173cce2015-05-22 10:50:39 -0400166 * desire to sign in to the network. Apps handling this activity should
Paul Jensened4d55c2015-02-27 22:55:47 -0500167 * facilitate signing in to the network. This action includes a
168 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
169 * the network presenting the captive portal; all communication with the
170 * captive portal must be done using this {@code Network} object.
171 * <p/>
Paul Jensen4173cce2015-05-22 10:50:39 -0400172 * This activity includes a {@link CaptivePortal} extra named
173 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
174 * outcomes of the captive portal sign in to the system:
175 * <ul>
176 * <li> When the app handling this action believes the user has signed in to
177 * the network and the captive portal has been dismissed, the app should
178 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
179 * reevaluate the network. If reevaluation finds the network no longer
180 * subject to a captive portal, the network may become the default active
Chalard Jean73d9db72018-06-04 16:52:49 +0900181 * data network.</li>
Paul Jensen4173cce2015-05-22 10:50:39 -0400182 * <li> When the app handling this action believes the user explicitly wants
Paul Jensened4d55c2015-02-27 22:55:47 -0500183 * to ignore the captive portal and the network, the app should call
Paul Jensen4173cce2015-05-22 10:50:39 -0400184 * {@link CaptivePortal#ignoreNetwork}. </li>
185 * </ul>
Paul Jensened4d55c2015-02-27 22:55:47 -0500186 */
187 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
188 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
189
190 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800191 * The lookup key for a {@link NetworkInfo} object. Retrieve with
192 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700193 *
Chalard Jeancc47b522019-01-11 16:47:53 +0900194 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
195 * can't accurately represent modern network characteristics.
196 * Please obtain information about networks from the {@link NetworkCapabilities}
197 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700199 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800200 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700201
The Android Open Source Project28527d22009-03-03 19:31:44 -0800202 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700203 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700204 *
205 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeancc47b522019-01-11 16:47:53 +0900206 * @deprecated The network type is not rich enough to represent the characteristics
207 * of modern networks. Please use {@link NetworkCapabilities} instead,
208 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700209 */
Chalard Jeancc47b522019-01-11 16:47:53 +0900210 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700211 public static final String EXTRA_NETWORK_TYPE = "networkType";
212
213 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214 * The lookup key for a boolean that indicates whether a connect event
215 * is for a network to which the connectivity manager was failing over
216 * following a disconnect on another network.
217 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai5c2f6262018-12-13 12:47:51 +0800218 *
219 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220 */
junyulai5c2f6262018-12-13 12:47:51 +0800221 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222 public static final String EXTRA_IS_FAILOVER = "isFailover";
223 /**
224 * The lookup key for a {@link NetworkInfo} object. This is supplied when
225 * there is another network that it may be possible to connect to. Retrieve with
226 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800227 *
228 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229 */
junyulai5c2f6262018-12-13 12:47:51 +0800230 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
232 /**
233 * The lookup key for a boolean that indicates whether there is a
234 * complete lack of connectivity, i.e., no network is available.
235 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
236 */
237 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
238 /**
239 * The lookup key for a string that indicates why an attempt to connect
240 * to a network failed. The string has no particular structure. It is
241 * intended to be used in notifications presented to users. Retrieve
242 * it with {@link android.content.Intent#getStringExtra(String)}.
243 */
244 public static final String EXTRA_REASON = "reason";
245 /**
246 * The lookup key for a string that provides optionally supplied
247 * extra information about the network state. The information
248 * may be passed up from the lower networking layers, and its
249 * meaning may be specific to a particular network type. Retrieve
250 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800251 *
252 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800253 */
junyulai5c2f6262018-12-13 12:47:51 +0800254 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800255 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700256 /**
257 * The lookup key for an int that provides information about
258 * our connection to the internet at large. 0 indicates no connection,
259 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700260 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700261 * {@hide}
262 */
263 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800264 /**
Paul Jensen4173cce2015-05-22 10:50:39 -0400265 * The lookup key for a {@link CaptivePortal} object included with the
266 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
267 * object can be used to either indicate to the system that the captive
268 * portal has been dismissed or that the user does not want to pursue
269 * signing in to captive portal. Retrieve it with
270 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensened4d55c2015-02-27 22:55:47 -0500271 */
Paul Jensen4173cce2015-05-22 10:50:39 -0400272 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist0f3b4442015-09-22 15:54:32 -0700273
274 /**
275 * Key for passing a URL to the captive portal login activity.
276 */
277 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
278
Paul Jensened4d55c2015-02-27 22:55:47 -0500279 /**
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900280 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
281 * portal login activity.
282 * {@hide}
283 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900284 @SystemApi
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900285 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
286 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
287
288 /**
Hugo Benichidce21c52016-12-14 08:23:40 +0900289 * Key for passing a user agent string to the captive portal login activity.
290 * {@hide}
291 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900292 @SystemApi
Hugo Benichidce21c52016-12-14 08:23:40 +0900293 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
294 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
295
296 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700297 * Broadcast action to indicate the change of data activity status
298 * (idle or active) on a network in a recent period.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800299 * The network becomes active when data transmission is started, or
300 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700301 * {@hide}
302 */
303 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean73d9db72018-06-04 16:52:49 +0900304 public static final String ACTION_DATA_ACTIVITY_CHANGE =
305 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700306 /**
307 * The lookup key for an enum that indicates the network device type on which this data activity
308 * change happens.
309 * {@hide}
310 */
311 public static final String EXTRA_DEVICE_TYPE = "deviceType";
312 /**
313 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
314 * it is actively sending or receiving data and {@code false} means it is idle.
315 * {@hide}
316 */
317 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma601fba92014-03-12 18:42:23 -0700318 /**
319 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
320 * {@hide}
321 */
322 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700323
324 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800325 * Broadcast Action: The setting for background data usage has changed
326 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
327 * <p>
328 * If an application uses the network in the background, it should listen
329 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700330 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800331 * <p>
332 *
333 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
334 * of background data depends on several combined factors, and
335 * this broadcast is no longer sent. Instead, when background
336 * data is unavailable, {@link #getActiveNetworkInfo()} will now
337 * appear disconnected. During first boot after a platform
338 * upgrade, this broadcast will be sent once if
339 * {@link #getBackgroundDataSetting()} was {@code false} before
340 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800341 */
342 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800343 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800344 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
345 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
346
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700347 /**
348 * Broadcast Action: The network connection may not be good
349 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
350 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
351 * the network and it's condition.
352 * @hide
353 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800354 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100355 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700356 public static final String INET_CONDITION_ACTION =
357 "android.net.conn.INET_CONDITION_ACTION";
358
Robert Greenwalt2034b912009-08-12 16:08:25 -0700359 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800360 * Broadcast Action: A tetherable connection has come or gone.
361 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline449ccfe2017-04-17 16:47:23 +0900362 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
363 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt26744a52013-02-15 10:56:35 -0800364 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
365 * the current state of tethering. Each include a list of
366 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800367 * @hide
368 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800369 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000370 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800371 public static final String ACTION_TETHER_STATE_CHANGED =
markchien1f523702019-12-25 19:40:32 +0800372 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800373
374 /**
375 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800376 * gives a String[] listing all the interfaces configured for
377 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800378 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000379 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800380 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800381
382 /**
383 * @hide
Erik Kline449ccfe2017-04-17 16:47:23 +0900384 * gives a String[] listing all the interfaces currently in local-only
385 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800386 */
markchien1f523702019-12-25 19:40:32 +0800387 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline449ccfe2017-04-17 16:47:23 +0900388
389 /**
390 * @hide
391 * gives a String[] listing all the interfaces currently tethered
392 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
393 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000394 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800395 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800396
397 /**
398 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800399 * gives a String[] listing all the interfaces we tried to tether and
400 * failed. Use {@link #getLastTetherError} to find the error code
401 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800402 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000403 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800404 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800405
406 /**
Russell Brenner4774b022013-02-12 10:03:14 -0800407 * Broadcast Action: The captive portal tracker has finished its test.
408 * Sent only while running Setup Wizard, in lieu of showing a user
409 * notification.
410 * @hide
411 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800412 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner4774b022013-02-12 10:03:14 -0800413 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
414 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
415 /**
416 * The lookup key for a boolean that indicates whether a captive portal was detected.
417 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
418 * @hide
419 */
420 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
421
422 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900423 * Action used to display a dialog that asks the user whether to connect to a network that is
424 * not validated. This intent is used to start the dialog in settings via startActivity.
425 *
426 * @hide
427 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800428 @SystemApi(client = MODULE_LIBRARIES)
429 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900430
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 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800437 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900438 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslin1a0ca5f2021-03-04 17:09:51 +0800439 "android.net.action.PROMPT_LOST_VALIDATION";
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900440
441 /**
lucaslin25a50472019-03-12 13:08:03 +0800442 * Action used to display a dialog that asks the user whether to stay connected to a network
443 * that has not validated. This intent is used to start the dialog in settings via
444 * startActivity.
445 *
446 * @hide
447 */
lucaslin1a0ca5f2021-03-04 17:09:51 +0800448 @SystemApi(client = MODULE_LIBRARIES)
lucaslin25a50472019-03-12 13:08:03 +0800449 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslin1a0ca5f2021-03-04 17:09:51 +0800450 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
lucaslin25a50472019-03-12 13:08:03 +0800451
452 /**
paulhu164c97d2021-04-07 16:18:13 +0800453 * Clear DNS Cache Action: This is broadcast when networks have changed and old
454 * DNS entries should be cleared.
455 * @hide
456 */
457 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
458 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
459 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
460
461 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800462 * Invalid tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900463 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800464 * @hide
465 */
markchien1f523702019-12-25 19:40:32 +0800466 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800467
468 /**
469 * Wifi tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900470 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800471 * @hide
472 */
473 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900474 public static final int TETHERING_WIFI = 0;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800475
476 /**
477 * USB tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900478 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800479 * @hide
480 */
481 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900482 public static final int TETHERING_USB = 1;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800483
484 /**
485 * Bluetooth tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900486 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800487 * @hide
488 */
489 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900490 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800491
492 /**
Jimmy Chen87db1542019-07-15 18:03:23 +0800493 * Wifi P2p tethering type.
494 * Wifi P2p tethering is set through events automatically, and don't
495 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
496 * @hide
497 */
markchien1f523702019-12-25 19:40:32 +0800498 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chen87db1542019-07-15 18:03:23 +0800499
500 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800501 * Extra used for communicating with the TetherService. Includes the type of tethering to
502 * enable if any.
503 * @hide
504 */
markchien75721e42020-01-21 13:11:06 +0800505 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800506
507 /**
508 * Extra used for communicating with the TetherService. Includes the type of tethering for
509 * which to cancel provisioning.
510 * @hide
511 */
markchien75721e42020-01-21 13:11:06 +0800512 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800513
514 /**
515 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
516 * provisioning.
517 * @hide
518 */
markchien75721e42020-01-21 13:11:06 +0800519 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800520
521 /**
522 * Tells the TetherService to run a provision check now.
523 * @hide
524 */
markchien75721e42020-01-21 13:11:06 +0800525 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800526
527 /**
528 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
529 * which will receive provisioning results. Can be left empty.
530 * @hide
531 */
markchien75721e42020-01-21 13:11:06 +0800532 public static final String EXTRA_PROVISION_CALLBACK =
533 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800534
535 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800536 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700537 * @hide
538 */
paulhu62af6122020-01-13 16:46:45 +0800539 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700540 public static final int TYPE_NONE = -1;
541
542 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900543 * A Mobile data connection. Devices may support more than one.
544 *
545 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
546 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
547 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700548 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900549 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700550 public static final int TYPE_MOBILE = 0;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900551
Robert Greenwalt2034b912009-08-12 16:08:25 -0700552 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900553 * A WIFI data connection. Devices may support more than one.
554 *
555 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
556 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
557 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700558 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900559 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700560 public static final int TYPE_WIFI = 1;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900561
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800563 * An MMS-specific Mobile data connection. This network type may use the
564 * same network interface as {@link #TYPE_MOBILE} or it may use a different
565 * one. This is used by applications needing to talk to the carrier's
566 * Multimedia Messaging Service servers.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900567 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900568 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900569 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900570 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700572 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700573 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900574
Robert Greenwalt2034b912009-08-12 16:08:25 -0700575 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800576 * A SUPL-specific Mobile data connection. This network type may use the
577 * same network interface as {@link #TYPE_MOBILE} or it may use a different
578 * one. This is used by applications needing to talk to the carrier's
579 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900580 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900581 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900582 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900583 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700585 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700586 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900587
Robert Greenwalt2034b912009-08-12 16:08:25 -0700588 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800589 * A DUN-specific Mobile data connection. This network type may use the
590 * same network interface as {@link #TYPE_MOBILE} or it may use a different
591 * one. This is sometimes by the system when setting up an upstream connection
592 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900593 *
594 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
595 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
596 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700597 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900598 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700599 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900600
Robert Greenwalt2034b912009-08-12 16:08:25 -0700601 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800602 * A High Priority Mobile data connection. This network type uses the
603 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900604 * is different.
605 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900606 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
607 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
608 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700609 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700610 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700611 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900612
jshbfa81722010-03-11 15:04:43 -0800613 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900614 * A WiMAX data connection.
615 *
616 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
617 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
618 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800619 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900620 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800621 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800622
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800623 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900624 * A Bluetooth data connection.
625 *
626 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
627 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
628 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800629 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900630 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800631 public static final int TYPE_BLUETOOTH = 7;
632
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700633 /**
Chiachang Wang7d5f3782020-07-28 13:53:09 +0800634 * Fake data connection. This should not be used on shipping devices.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900635 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700636 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900637 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800638 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800639
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700640 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900641 * An Ethernet data connection.
642 *
643 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
644 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
645 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700646 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900647 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800648 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700649
Wink Savilleb7c92c72011-03-12 14:52:01 -0800650 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800651 * Over the air Administration.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900652 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800653 * {@hide}
654 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900655 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900656 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800657 public static final int TYPE_MOBILE_FOTA = 10;
658
659 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800660 * IP Multimedia Subsystem.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900661 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800662 * {@hide}
663 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900664 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100665 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800666 public static final int TYPE_MOBILE_IMS = 11;
667
668 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800669 * Carrier Branded Services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900670 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800671 * {@hide}
672 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900673 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900674 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800675 public static final int TYPE_MOBILE_CBS = 12;
676
repo syncf5de5572011-07-29 23:55:49 -0700677 /**
678 * A Wi-Fi p2p connection. Only requesting processes will have access to
679 * the peers connected.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900680 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700681 * {@hide}
682 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900683 @Deprecated
paulhu028732e2020-01-15 15:38:23 +0800684 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700685 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800686
Wink Saville70dbdcc2013-07-29 15:00:57 -0700687 /**
688 * The network to use for initially attaching to the network
Chalard Jean5acb7b72018-03-08 13:54:53 +0900689 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville70dbdcc2013-07-29 15:00:57 -0700690 * {@hide}
691 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900692 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100693 @UnsupportedAppUsage
Wink Saville70dbdcc2013-07-29 15:00:57 -0700694 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700695
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900696 /**
Robert Greenwalt9db5f3c2015-07-09 14:49:35 -0700697 * Emergency PDN connection for emergency services. This
698 * may include IMS and MMS in emergency situations.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900699 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram201d45f2014-06-26 11:03:44 -0700700 * {@hide}
701 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900702 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900703 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram201d45f2014-06-26 11:03:44 -0700704 public static final int TYPE_MOBILE_EMERGENCY = 15;
705
Hui Lu07f29332014-01-15 11:05:36 -0500706 /**
707 * The network that uses proxy to achieve connectivity.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900708 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu07f29332014-01-15 11:05:36 -0500709 * {@hide}
710 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900711 @Deprecated
Remi NGUYEN VANdaeafee2020-11-30 19:23:45 +0900712 @SystemApi
Hui Lu07f29332014-01-15 11:05:36 -0500713 public static final int TYPE_PROXY = 16;
Wink Saville70dbdcc2013-07-29 15:00:57 -0700714
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700715 /**
716 * A virtual network using one or more native bearers.
717 * It may or may not be providing security services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900718 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700719 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900720 @Deprecated
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700721 public static final int TYPE_VPN = 17;
Hui Lu07f29332014-01-15 11:05:36 -0500722
Benedict Wong80156022018-11-14 17:40:55 -0800723 /**
724 * A network that is exclusively meant to be used for testing
725 *
726 * @deprecated Use {@link NetworkCapabilities} instead.
727 * @hide
728 */
729 @Deprecated
730 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700731
Chalard Jean74fe1c72020-03-25 01:24:04 +0900732 /**
733 * @deprecated Use {@link NetworkCapabilities} instead.
734 * @hide
735 */
736 @Deprecated
737 @Retention(RetentionPolicy.SOURCE)
738 @IntDef(prefix = { "TYPE_" }, value = {
739 TYPE_NONE,
740 TYPE_MOBILE,
741 TYPE_WIFI,
742 TYPE_MOBILE_MMS,
743 TYPE_MOBILE_SUPL,
744 TYPE_MOBILE_DUN,
745 TYPE_MOBILE_HIPRI,
746 TYPE_WIMAX,
747 TYPE_BLUETOOTH,
748 TYPE_DUMMY,
749 TYPE_ETHERNET,
750 TYPE_MOBILE_FOTA,
751 TYPE_MOBILE_IMS,
752 TYPE_MOBILE_CBS,
753 TYPE_WIFI_P2P,
754 TYPE_MOBILE_IA,
755 TYPE_MOBILE_EMERGENCY,
756 TYPE_PROXY,
757 TYPE_VPN,
758 TYPE_TEST
759 })
760 public @interface LegacyNetworkType {}
761
Chalard Jean1f42df12019-11-21 14:48:00 +0900762 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
763 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
764 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
765 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
766 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
767
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700768 /** {@hide} */
Benedict Wong80156022018-11-14 17:40:55 -0800769 public static final int MAX_RADIO_TYPE = TYPE_TEST;
770
771 /** {@hide} */
772 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800773
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900774 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
775
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800776 /**
777 * If you want to set the default network preference,you can directly
778 * change the networkAttributes array in framework's config.xml.
779 *
780 * @deprecated Since we support so many more networks now, the single
781 * network default network preference can't really express
Robert Greenwalt26744a52013-02-15 10:56:35 -0800782 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800783 * networkAttributes in config.xml. You can determine
Robert Greenwalt1ee3d2c2012-12-07 09:56:50 -0800784 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800785 * from an App.
786 */
787 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800788 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
789
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700790 /**
Robert Greenwalta1402df2014-03-19 17:56:12 -0700791 * @hide
792 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900793 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltc34f83b2014-06-08 16:42:59 -0700794
Paul Jensen0478ace2014-07-11 12:28:19 -0400795 /**
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900796 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
797 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean73d9db72018-06-04 16:52:49 +0900798 * registered from those that were already unregistered.
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900799 * @hide
800 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900801 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900802 new NetworkRequest.Builder().clearCapabilities().build();
803
804 /**
Paul Jensen0478ace2014-07-11 12:28:19 -0400805 * A NetID indicating no Network is selected.
806 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
807 * @hide
808 */
809 public static final int NETID_UNSET = 0;
810
Erik Kline1ecdd962017-10-30 15:29:44 +0900811 /**
812 * Private DNS Mode values.
813 *
814 * The "private_dns_mode" global setting stores a String value which is
815 * expected to be one of the following.
816 */
817
818 /**
819 * @hide
820 */
lucaslin50205af2021-03-12 16:11:27 +0800821 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900822 public static final String PRIVATE_DNS_MODE_OFF = "off";
823 /**
824 * @hide
825 */
lucaslin50205af2021-03-12 16:11:27 +0800826 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900827 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
828 /**
829 * @hide
830 */
lucaslin50205af2021-03-12 16:11:27 +0800831 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900832 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin50205af2021-03-12 16:11:27 +0800833
834 /** @hide */
835 @Retention(RetentionPolicy.SOURCE)
836 @StringDef(value = {
837 PRIVATE_DNS_MODE_OFF,
838 PRIVATE_DNS_MODE_OPPORTUNISTIC,
839 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
840 })
841 public @interface PrivateDnsMode {}
Erik Kline1ecdd962017-10-30 15:29:44 +0900842
Sudheer Shanka457dfd52021-03-23 08:12:28 +0000843 /**
844 * Flag to indicate that an app is not subject to any restrictions that could result in its
845 * network access blocked.
846 *
847 * @hide
848 */
849 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
850 public static final int BLOCKED_REASON_NONE = 0;
851
852 /**
853 * Flag to indicate that an app is subject to Battery saver restrictions that would
854 * result in its network access being blocked.
855 *
856 * @hide
857 */
858 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
859 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
860
861 /**
862 * Flag to indicate that an app is subject to Doze restrictions that would
863 * result in its network access being blocked.
864 *
865 * @hide
866 */
867 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
868 public static final int BLOCKED_REASON_DOZE = 1 << 1;
869
870 /**
871 * Flag to indicate that an app is subject to App Standby restrictions that would
872 * result in its network access being blocked.
873 *
874 * @hide
875 */
876 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
877 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
878
879 /**
880 * Flag to indicate that an app is subject to Restricted mode restrictions that would
881 * result in its network access being blocked.
882 *
883 * @hide
884 */
885 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
886 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
887
888 /**
Lorenzo Colitti60104f52021-03-18 00:54:57 +0900889 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
890 * is not currently connected.
891 *
892 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
893 *
894 * @hide
895 */
896 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
897 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
898
899 /**
Sudheer Shanka457dfd52021-03-23 08:12:28 +0000900 * Flag to indicate that an app is subject to Data saver restrictions that would
901 * result in its metered network access being blocked.
902 *
903 * @hide
904 */
905 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
906 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
907
908 /**
909 * Flag to indicate that an app is subject to user restrictions that would
910 * result in its metered network access being blocked.
911 *
912 * @hide
913 */
914 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
915 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
916
917 /**
918 * Flag to indicate that an app is subject to Device admin restrictions that would
919 * result in its metered network access being blocked.
920 *
921 * @hide
922 */
923 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
924 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
925
926 /**
927 * @hide
928 */
929 @Retention(RetentionPolicy.SOURCE)
930 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
931 BLOCKED_REASON_NONE,
932 BLOCKED_REASON_BATTERY_SAVER,
933 BLOCKED_REASON_DOZE,
934 BLOCKED_REASON_APP_STANDBY,
935 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia37eaff2021-03-25 23:17:36 +0900936 BLOCKED_REASON_LOCKDOWN_VPN,
Sudheer Shanka457dfd52021-03-23 08:12:28 +0000937 BLOCKED_METERED_REASON_DATA_SAVER,
938 BLOCKED_METERED_REASON_USER_RESTRICTED,
939 BLOCKED_METERED_REASON_ADMIN_DISABLED,
940 })
941 public @interface BlockedReason {}
942
Lorenzo Colitti60104f52021-03-18 00:54:57 +0900943 /**
944 * Set of blocked reasons that are only applicable on metered networks.
945 *
946 * @hide
947 */
948 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
949 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
950
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900951 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700952 private final IConnectivityManager mService;
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +0900953
Paul Jensen12131352014-12-10 15:12:18 -0500954 /**
955 * A kludge to facilitate static access where a Context pointer isn't available, like in the
956 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
957 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
958 * methods that take a Context argument.
959 */
960 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800961
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +0900962 private final Context mContext;
963
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +0000964 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800965
Robert Greenwalt26744a52013-02-15 10:56:35 -0800966 /**
967 * Tests if a given integer represents a valid network type.
968 * @param networkType the type to be tested
969 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen1c9f2e42015-05-06 10:42:25 -0400970 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
971 * validate a network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800972 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700973 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700974 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900975 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800976 }
977
Robert Greenwalt26744a52013-02-15 10:56:35 -0800978 /**
979 * Returns a non-localized string representing a given network type.
980 * ONLY used for debugging output.
981 * @param type the type needing naming
982 * @return a String for the given type, or a string version of the type ("87")
983 * if no name is known.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900984 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800985 * {@hide}
986 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900987 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000988 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700989 public static String getNetworkTypeName(int type) {
990 switch (type) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900991 case TYPE_NONE:
992 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700993 case TYPE_MOBILE:
994 return "MOBILE";
995 case TYPE_WIFI:
996 return "WIFI";
997 case TYPE_MOBILE_MMS:
998 return "MOBILE_MMS";
999 case TYPE_MOBILE_SUPL:
1000 return "MOBILE_SUPL";
1001 case TYPE_MOBILE_DUN:
1002 return "MOBILE_DUN";
1003 case TYPE_MOBILE_HIPRI:
1004 return "MOBILE_HIPRI";
1005 case TYPE_WIMAX:
1006 return "WIMAX";
1007 case TYPE_BLUETOOTH:
1008 return "BLUETOOTH";
1009 case TYPE_DUMMY:
1010 return "DUMMY";
1011 case TYPE_ETHERNET:
1012 return "ETHERNET";
1013 case TYPE_MOBILE_FOTA:
1014 return "MOBILE_FOTA";
1015 case TYPE_MOBILE_IMS:
1016 return "MOBILE_IMS";
1017 case TYPE_MOBILE_CBS:
1018 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -07001019 case TYPE_WIFI_P2P:
1020 return "WIFI_P2P";
Wink Saville70dbdcc2013-07-29 15:00:57 -07001021 case TYPE_MOBILE_IA:
1022 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -07001023 case TYPE_MOBILE_EMERGENCY:
1024 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -05001025 case TYPE_PROXY:
1026 return "PROXY";
Erik Klineb1ff7002014-11-19 17:23:41 +09001027 case TYPE_VPN:
1028 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -07001029 default:
1030 return Integer.toString(type);
1031 }
1032 }
1033
Robert Greenwalt26744a52013-02-15 10:56:35 -08001034 /**
Aaron Huangdfba5d12020-06-27 07:18:23 +08001035 * @hide
Aaron Huangdfba5d12020-06-27 07:18:23 +08001036 */
lucaslin8c121bf2021-03-17 14:16:01 +08001037 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huangdfba5d12020-06-27 07:18:23 +08001038 public void systemReady() {
1039 try {
1040 mService.systemReady();
1041 } catch (RemoteException e) {
1042 throw e.rethrowFromSystemServer();
1043 }
1044 }
1045
1046 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001047 * Checks if a given type uses the cellular data connection.
1048 * This should be replaced in the future by a network property.
1049 * @param networkType the type to check
1050 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09001051 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001052 * {@hide}
1053 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09001054 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001055 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001056 public static boolean isNetworkTypeMobile(int networkType) {
1057 switch (networkType) {
1058 case TYPE_MOBILE:
1059 case TYPE_MOBILE_MMS:
1060 case TYPE_MOBILE_SUPL:
1061 case TYPE_MOBILE_DUN:
1062 case TYPE_MOBILE_HIPRI:
1063 case TYPE_MOBILE_FOTA:
1064 case TYPE_MOBILE_IMS:
1065 case TYPE_MOBILE_CBS:
Wink Saville70dbdcc2013-07-29 15:00:57 -07001066 case TYPE_MOBILE_IA:
Ram201d45f2014-06-26 11:03:44 -07001067 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -07001068 return true;
1069 default:
1070 return false;
1071 }
1072 }
1073
Robert Greenwalt26744a52013-02-15 10:56:35 -08001074 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001075 * Checks if the given network type is backed by a Wi-Fi radio.
1076 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001077 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001078 * @hide
1079 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09001080 @Deprecated
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001081 public static boolean isNetworkTypeWifi(int networkType) {
1082 switch (networkType) {
1083 case TYPE_WIFI:
1084 case TYPE_WIFI_P2P:
1085 return true;
1086 default:
1087 return false;
1088 }
1089 }
1090
1091 /**
Chalard Jean03433052021-02-25 17:23:40 +09001092 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1093 * Specify that the traffic for this user should by follow the default rules.
1094 * @hide
1095 */
Chalard Jean560d4032021-03-17 14:33:24 +09001096 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09001097 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1098
1099 /**
1100 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1101 * Specify that the traffic for this user should by default go on a network with
1102 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1103 * if no such network is available.
1104 * @hide
1105 */
Chalard Jean560d4032021-03-17 14:33:24 +09001106 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09001107 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1108
1109 /** @hide */
1110 @Retention(RetentionPolicy.SOURCE)
1111 @IntDef(value = {
1112 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1113 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1114 })
1115 public @interface ProfileNetworkPreference {
1116 }
1117
1118 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001119 * Specifies the preferred network type. When the device has more
1120 * than one type available the preferred network type will be used.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001121 *
1122 * @param preference the network type to prefer over all others. It is
1123 * unspecified what happens to the old preferred network in the
1124 * overall ordering.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001125 * @deprecated Functionality has been removed as it no longer makes sense,
1126 * with many more than two networks - we'd need an array to express
1127 * preference. Instead we use dynamic network properties of
1128 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001129 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001130 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001131 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001132 }
1133
Robert Greenwalt26744a52013-02-15 10:56:35 -08001134 /**
1135 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001136 *
1137 * @return an integer representing the preferred network type
1138 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001139 * @deprecated Functionality has been removed as it no longer makes sense,
1140 * with many more than two networks - we'd need an array to express
1141 * preference. Instead we use dynamic network properties of
1142 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001143 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001144 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001145 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001146 public int getNetworkPreference() {
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001147 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001148 }
1149
Scott Mainf58b7d82011-10-06 19:02:28 -07001150 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001151 * Returns details about the currently active default data network. When
1152 * connected, this network is the default route for outgoing connections.
1153 * You should always check {@link NetworkInfo#isConnected()} before initiating
1154 * network traffic. This may return {@code null} when there is no default
1155 * network.
Chalard Jean7c85ba42018-03-29 17:45:24 +09001156 * Note that if the default network is a VPN, this method will return the
1157 * NetworkInfo for one of its underlying networks instead, or null if the
1158 * VPN agent did not specify any. Apps interested in learning about VPNs
1159 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001160 *
1161 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001162 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001163 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001164 */
junyulai5c2f6262018-12-13 12:47:51 +08001165 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001166 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001167 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001168 public NetworkInfo getActiveNetworkInfo() {
1169 try {
1170 return mService.getActiveNetworkInfo();
1171 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001172 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001173 }
1174 }
1175
Robert Greenwalt26744a52013-02-15 10:56:35 -08001176 /**
Paul Jensenc2569432015-02-13 14:18:39 -05001177 * Returns a {@link Network} object corresponding to the currently active
1178 * default data network. In the event that the current active default data
1179 * network disconnects, the returned {@code Network} object will no longer
1180 * be usable. This will return {@code null} when there is no default
1181 * network.
1182 *
1183 * @return a {@link Network} object for the current default network or
1184 * {@code null} if no default network is currently active
Paul Jensenc2569432015-02-13 14:18:39 -05001185 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001186 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001187 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001188 public Network getActiveNetwork() {
1189 try {
1190 return mService.getActiveNetwork();
1191 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001192 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001193 }
1194 }
1195
1196 /**
Robin Leeda4d2e22016-03-24 12:07:00 +00001197 * Returns a {@link Network} object corresponding to the currently active
1198 * default data network for a specific UID. In the event that the default data
1199 * network disconnects, the returned {@code Network} object will no longer
1200 * be usable. This will return {@code null} when there is no default
1201 * network for the UID.
Robin Leeda4d2e22016-03-24 12:07:00 +00001202 *
1203 * @return a {@link Network} object for the current default network for the
1204 * given UID or {@code null} if no default network is currently active
lifr5f1c1102021-03-30 21:04:53 +08001205 *
1206 * @hide
Robin Leeda4d2e22016-03-24 12:07:00 +00001207 */
paulhuec0a9632019-08-12 16:25:11 +08001208 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001209 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001210 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001211 return getActiveNetworkForUid(uid, false);
1212 }
1213
1214 /** {@hide} */
1215 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001216 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001217 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001218 } catch (RemoteException e) {
1219 throw e.rethrowFromSystemServer();
1220 }
1221 }
1222
1223 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001224 * Adds or removes a requirement for given UID ranges to use the VPN.
1225 *
1226 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1227 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1228 * otherwise have permission to bypass the VPN (e.g., because they have the
1229 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1230 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1231 * set to {@code false}, a previously-added restriction is removed.
1232 * <p>
1233 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1234 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1235 * remove a previously-added range, the exact range must be removed as is.
1236 * <p>
1237 * The changes are applied asynchronously and may not have been applied by the time the method
1238 * returns. Apps will be notified about any changes that apply to them via
1239 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1240 * effect.
1241 * <p>
1242 * This method should be called only by the VPN code.
1243 *
1244 * @param ranges the UID ranges to restrict
1245 * @param requireVpn whether the specified UID ranges must use a VPN
1246 *
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001247 * @hide
1248 */
1249 @RequiresPermission(anyOf = {
1250 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001251 android.Manifest.permission.NETWORK_STACK,
1252 android.Manifest.permission.NETWORK_SETTINGS})
1253 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001254 public void setRequireVpnForUids(boolean requireVpn,
1255 @NonNull Collection<Range<Integer>> ranges) {
1256 Objects.requireNonNull(ranges);
1257 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1258 // This method is not necessarily expected to be used outside the system server, so
1259 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1260 // stack process, or by tests.
1261 UidRange[] rangesArray = new UidRange[ranges.size()];
1262 int index = 0;
1263 for (Range<Integer> range : ranges) {
1264 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1265 }
1266 try {
1267 mService.setRequireVpnForUids(requireVpn, rangesArray);
1268 } catch (RemoteException e) {
1269 throw e.rethrowFromSystemServer();
1270 }
1271 }
1272
1273 /**
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001274 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1275 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1276 * but is still supported for backwards compatibility.
1277 * <p>
1278 * This type of VPN is assumed always to use the system default network, and must always declare
1279 * exactly one underlying network, which is the network that was the default when the VPN
1280 * connected.
1281 * <p>
1282 * Calling this method with {@code true} enables legacy behaviour, specifically:
1283 * <ul>
1284 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1285 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1286 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1287 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1288 * underlying the VPN.</li>
1289 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1290 * similarly replaced by the VPN network state.</li>
1291 * <li>Information on current network interfaces passed to NetworkStatsService will not
1292 * include any VPN interfaces.</li>
1293 * </ul>
1294 *
1295 * @param enabled whether legacy lockdown VPN is enabled or disabled
1296 *
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001297 * @hide
1298 */
1299 @RequiresPermission(anyOf = {
1300 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001301 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001302 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin5140e482021-03-22 11:51:27 +08001303 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001304 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1305 try {
1306 mService.setLegacyLockdownVpnEnabled(enabled);
1307 } catch (RemoteException e) {
1308 throw e.rethrowFromSystemServer();
1309 }
1310 }
1311
1312 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001313 * Returns details about the currently active default data network
1314 * for a given uid. This is for internal use only to avoid spying
1315 * other apps.
1316 *
1317 * @return a {@link NetworkInfo} object for the current default network
1318 * for the given uid or {@code null} if no default network is
1319 * available for the specified uid.
1320 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001321 * {@hide}
1322 */
paulhuec0a9632019-08-12 16:25:11 +08001323 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001324 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001325 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001326 return getActiveNetworkInfoForUid(uid, false);
1327 }
1328
1329 /** {@hide} */
1330 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001331 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001332 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001333 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001334 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001335 }
1336 }
1337
Robert Greenwalt26744a52013-02-15 10:56:35 -08001338 /**
1339 * Returns connection status information about a particular
1340 * network type.
1341 *
1342 * @param networkType integer specifying which networkType in
1343 * which you're interested.
1344 * @return a {@link NetworkInfo} object for the requested
1345 * network type or {@code null} if the type is not
Chalard Jean7c85ba42018-03-29 17:45:24 +09001346 * supported by the device. If {@code networkType} is
1347 * TYPE_VPN and a VPN is active for the calling app,
1348 * then this method will try to return one of the
1349 * underlying networks for the VPN or null if the
1350 * VPN agent didn't specify any.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001351 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001352 * @deprecated This method does not support multiple connected networks
1353 * of the same type. Use {@link #getAllNetworks} and
1354 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001355 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001356 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001357 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001358 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001359 public NetworkInfo getNetworkInfo(int networkType) {
1360 try {
1361 return mService.getNetworkInfo(networkType);
1362 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001363 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001364 }
1365 }
1366
Robert Greenwalt26744a52013-02-15 10:56:35 -08001367 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001368 * Returns connection status information about a particular
1369 * Network.
1370 *
1371 * @param network {@link Network} specifying which network
1372 * in which you're interested.
1373 * @return a {@link NetworkInfo} object for the requested
1374 * network or {@code null} if the {@code Network}
1375 * is not valid.
junyulai5c2f6262018-12-13 12:47:51 +08001376 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001377 */
junyulai5c2f6262018-12-13 12:47:51 +08001378 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001379 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001380 @Nullable
1381 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001382 return getNetworkInfoForUid(network, Process.myUid(), false);
1383 }
1384
1385 /** {@hide} */
1386 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001387 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001388 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001389 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001390 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001391 }
1392 }
1393
1394 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001395 * Returns connection status information about all network
1396 * types supported by the device.
1397 *
1398 * @return an array of {@link NetworkInfo} objects. Check each
1399 * {@link NetworkInfo#getType} for which type each applies.
1400 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001401 * @deprecated This method does not support multiple connected networks
1402 * of the same type. Use {@link #getAllNetworks} and
1403 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001404 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001405 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001406 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001407 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001408 public NetworkInfo[] getAllNetworkInfo() {
1409 try {
1410 return mService.getAllNetworkInfo();
1411 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001412 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001413 }
1414 }
1415
Robert Greenwalt26744a52013-02-15 10:56:35 -08001416 /**
junyulai57840802021-03-03 12:09:05 +08001417 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1418 * connected.
1419 * @hide
1420 */
1421 @SystemApi(client = MODULE_LIBRARIES)
1422 @RequiresPermission(anyOf = {
1423 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1424 android.Manifest.permission.NETWORK_STACK,
1425 android.Manifest.permission.NETWORK_SETTINGS})
1426 @NonNull
1427 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1428 try {
1429 return mService.getAllNetworkStateSnapshot();
1430 } catch (RemoteException e) {
1431 throw e.rethrowFromSystemServer();
1432 }
1433 }
1434
1435 /**
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001436 * Returns the {@link Network} object currently serving a given type, or
1437 * null if the given type is not connected.
1438 *
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001439 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04001440 * @deprecated This method does not support multiple connected networks
1441 * of the same type. Use {@link #getAllNetworks} and
1442 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001443 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001444 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001445 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001446 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001447 public Network getNetworkForType(int networkType) {
1448 try {
1449 return mService.getNetworkForType(networkType);
1450 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001451 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001452 }
1453 }
1454
1455 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001456 * Returns an array of all {@link Network} currently tracked by the
1457 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001458 *
1459 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001460 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001461 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001462 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001463 public Network[] getAllNetworks() {
1464 try {
1465 return mService.getAllNetworks();
1466 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001467 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001468 }
1469 }
1470
1471 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001472 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001473 * the Networks that applications run by the given user will use by default.
1474 * @hide
1475 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001476 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001477 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1478 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001479 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001480 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001481 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001482 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001483 }
1484 }
1485
1486 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001487 * Returns the IP information for the current default network.
1488 *
1489 * @return a {@link LinkProperties} object describing the IP info
1490 * for the current default network, or {@code null} if there
1491 * is no current default network.
1492 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001493 * {@hide}
Chalard Jeancc47b522019-01-11 16:47:53 +09001494 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1495 * value of {@link #getActiveNetwork()} instead. In particular,
1496 * this method will return non-null LinkProperties even if the
1497 * app is blocked by policy from using this network.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001498 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001499 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-01-11 16:47:53 +09001500 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001501 public LinkProperties getActiveLinkProperties() {
1502 try {
1503 return mService.getActiveLinkProperties();
1504 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001505 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001506 }
1507 }
1508
Robert Greenwalt26744a52013-02-15 10:56:35 -08001509 /**
1510 * Returns the IP information for a given network type.
1511 *
1512 * @param networkType the network type of interest.
1513 * @return a {@link LinkProperties} object describing the IP info
1514 * for the given networkType, or {@code null} if there is
1515 * no current default network.
1516 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001517 * {@hide}
Paul Jensena8e6dc62015-03-18 12:23:02 -04001518 * @deprecated This method does not support multiple connected networks
1519 * of the same type. Use {@link #getAllNetworks},
1520 * {@link #getNetworkInfo(android.net.Network)}, and
1521 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001522 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001523 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001524 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001525 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001526 public LinkProperties getLinkProperties(int networkType) {
1527 try {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001528 return mService.getLinkPropertiesForType(networkType);
1529 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001530 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001531 }
1532 }
1533
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001534 /**
1535 * Get the {@link LinkProperties} for the given {@link Network}. This
1536 * will return {@code null} if the network is unknown.
1537 *
1538 * @param network The {@link Network} object identifying the network in question.
1539 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001540 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001541 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001542 @Nullable
1543 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001544 try {
1545 return mService.getLinkProperties(network);
1546 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001547 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001548 }
1549 }
1550
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001551 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001552 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001553 * will return {@code null} if the network is unknown.
1554 *
Roshan Pius7992afd2020-12-22 15:10:42 -08001555 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1556 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1557 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1558 * this location sensitive information (subject to app's location permissions) will be
1559 * noted by system. To include any location sensitive data in {@link TransportInfo},
1560 * use a {@link NetworkCallback} with
1561 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1562 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001563 * @param network The {@link Network} object identifying the network in question.
Roshan Pius7992afd2020-12-22 15:10:42 -08001564 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001565 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001566 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001567 @Nullable
1568 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001569 try {
Roshan Piusc97d8062020-12-17 14:53:09 -08001570 return mService.getNetworkCapabilities(
1571 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001572 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001573 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001574 }
1575 }
1576
Robert Greenwalt26744a52013-02-15 10:56:35 -08001577 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001578 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001579 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1580 * portal is present.
1581 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1582 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1583 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001584 * The system network validation may be using different strategies to detect captive portals,
1585 * so this method does not necessarily return a URL used by the system. It only returns a URL
1586 * that may be relevant for other components trying to detect captive portals.
paulhuec0a9632019-08-12 16:25:11 +08001587 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001588 * @hide
paulhuec0a9632019-08-12 16:25:11 +08001589 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1590 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001591 */
paulhuec0a9632019-08-12 16:25:11 +08001592 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001593 @SystemApi
paulhuec0a9632019-08-12 16:25:11 +08001594 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001595 public String getCaptivePortalServerUrl() {
1596 try {
1597 return mService.getCaptivePortalServerUrl();
1598 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001599 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001600 }
1601 }
1602
1603 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001604 * Tells the underlying networking system that the caller wants to
1605 * begin using the named feature. The interpretation of {@code feature}
1606 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001607 *
1608 * <p>This method requires the caller to hold either the
1609 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1610 * or the ability to modify system settings as determined by
1611 * {@link android.provider.Settings.System#canWrite}.</p>
1612 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001613 * @param networkType specifies which network the request pertains to
1614 * @param feature the name of the feature to be used
1615 * @return an integer value representing the outcome of the request.
1616 * The interpretation of this value is specific to each networking
1617 * implementation+feature combination, except that the value {@code -1}
1618 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001619 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001620 * @deprecated Deprecated in favor of the cleaner
1621 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001622 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001623 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001624 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001625 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001626 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001627 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001628 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001629 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1630 if (netCap == null) {
1631 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1632 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001633 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001634 }
1635
1636 NetworkRequest request = null;
1637 synchronized (sLegacyRequests) {
1638 LegacyRequest l = sLegacyRequests.get(netCap);
1639 if (l != null) {
1640 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1641 renewRequestLocked(l);
1642 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001643 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001644 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001645 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001646 }
1647 }
1648
1649 request = requestNetworkForFeatureLocked(netCap);
1650 }
1651 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001652 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001653 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001654 } else {
1655 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001656 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001657 }
1658 }
1659
1660 /**
1661 * Tells the underlying networking system that the caller is finished
1662 * using the named feature. The interpretation of {@code feature}
1663 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001664 *
1665 * <p>This method requires the caller to hold either the
1666 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1667 * or the ability to modify system settings as determined by
1668 * {@link android.provider.Settings.System#canWrite}.</p>
1669 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001670 * @param networkType specifies which network the request pertains to
1671 * @param feature the name of the feature that is no longer needed
1672 * @return an integer value representing the outcome of the request.
1673 * The interpretation of this value is specific to each networking
1674 * implementation+feature combination, except that the value {@code -1}
1675 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001676 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001677 * @deprecated Deprecated in favor of the cleaner
1678 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001679 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001680 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001681 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001682 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001683 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001684 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001685 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001686 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1687 if (netCap == null) {
1688 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1689 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001690 return -1;
1691 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001692
Paul Jensen034dea32014-12-17 10:39:34 -05001693 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001694 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001695 }
1696 return 1;
1697 }
1698
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001699 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001700 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1701 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001702 switch (feature) {
1703 case "enableCBS":
1704 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1705 case "enableDUN":
1706 case "enableDUNAlways":
1707 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1708 case "enableFOTA":
1709 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1710 case "enableHIPRI":
1711 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1712 case "enableIMS":
1713 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1714 case "enableMMS":
1715 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1716 case "enableSUPL":
1717 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1718 default:
1719 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001720 }
Erik Kline50068e52017-01-26 18:08:28 +09001721 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1722 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001723 }
1724 return null;
1725 }
1726
Robert Greenwalt5a367872014-06-02 15:32:02 -07001727 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001728 if (netCap == null) return TYPE_NONE;
1729 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1730 return TYPE_MOBILE_CBS;
1731 }
1732 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1733 return TYPE_MOBILE_IMS;
1734 }
1735 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1736 return TYPE_MOBILE_FOTA;
1737 }
1738 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1739 return TYPE_MOBILE_DUN;
1740 }
1741 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1742 return TYPE_MOBILE_SUPL;
1743 }
1744 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1745 return TYPE_MOBILE_MMS;
1746 }
1747 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1748 return TYPE_MOBILE_HIPRI;
1749 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001750 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1751 return TYPE_WIFI_P2P;
1752 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001753 return TYPE_NONE;
1754 }
1755
1756 private static class LegacyRequest {
1757 NetworkCapabilities networkCapabilities;
1758 NetworkRequest networkRequest;
1759 int expireSequenceNumber;
1760 Network currentNetwork;
1761 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001762
1763 private void clearDnsBinding() {
1764 if (currentNetwork != null) {
1765 currentNetwork = null;
1766 setProcessDefaultNetworkForHostResolution(null);
1767 }
1768 }
1769
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001770 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001771 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001772 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001773 currentNetwork = network;
1774 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001775 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001776 }
1777 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001778 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001779 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001780 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1781 }
1782 };
1783 }
1784
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001785 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001786 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1787 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001788
1789 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1790 synchronized (sLegacyRequests) {
1791 LegacyRequest l = sLegacyRequests.get(netCap);
1792 if (l != null) return l.networkRequest;
1793 }
1794 return null;
1795 }
1796
1797 private void renewRequestLocked(LegacyRequest l) {
1798 l.expireSequenceNumber++;
1799 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1800 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1801 }
1802
1803 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1804 int ourSeqNum = -1;
1805 synchronized (sLegacyRequests) {
1806 LegacyRequest l = sLegacyRequests.get(netCap);
1807 if (l == null) return;
1808 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001809 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001810 }
1811 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1812 }
1813
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001814 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001815 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1816 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001817 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001818 try {
1819 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001820 } catch (RemoteException e) {
1821 throw e.rethrowFromSystemServer();
1822 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001823 LegacyRequest l = new LegacyRequest();
1824 l.networkCapabilities = netCap;
1825 l.delay = delay;
1826 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001827 l.networkRequest = sendRequestForNetwork(
1828 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001829 if (l.networkRequest == null) return null;
1830 sLegacyRequests.put(netCap, l);
1831 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1832 return l.networkRequest;
1833 }
1834
1835 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1836 if (delay >= 0) {
1837 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001838 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001839 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1840 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001841 }
1842 }
1843
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001844 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001845 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1846 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001847 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001848 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001849 }
Paul Jensen034dea32014-12-17 10:39:34 -05001850 if (l == null) return false;
1851 unregisterNetworkCallback(l.networkCallback);
1852 l.clearDnsBinding();
1853 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001854 }
1855
Erik Kline50068e52017-01-26 18:08:28 +09001856 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1857 static {
1858 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1859 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1860 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1861 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1862 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1863 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1864 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1865 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1866 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1867 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1868 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1869 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1870 }
1871
1872 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1873 static {
1874 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1875 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1876 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1877 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1878 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1879 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1880 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1881 }
1882
1883 /**
1884 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1885 * instance suitable for registering a request or callback. Throws an
1886 * IllegalArgumentException if no mapping from the legacy type to
1887 * NetworkCapabilities is known.
1888 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001889 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1890 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001891 * @hide
1892 */
1893 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1894 final NetworkCapabilities nc = new NetworkCapabilities();
1895
1896 // Map from type to transports.
1897 final int NOT_FOUND = -1;
1898 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001899 if (transport == NOT_FOUND) {
1900 throw new IllegalArgumentException("unknown legacy type: " + type);
1901 }
Erik Kline50068e52017-01-26 18:08:28 +09001902 nc.addTransportType(transport);
1903
1904 // Map from type to capabilities.
1905 nc.addCapability(sLegacyTypeToCapability.get(
1906 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1907 nc.maybeMarkCapabilitiesRestricted();
1908 return nc;
1909 }
1910
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001911 /** @hide */
1912 public static class PacketKeepaliveCallback {
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001913 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayevfc03a992019-11-15 19:12:49 +00001914 public PacketKeepaliveCallback() {
1915 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001916 /** The requested keepalive was successfully started. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001917 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001918 public void onStarted() {}
1919 /** The keepalive was successfully stopped. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001920 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001921 public void onStopped() {}
1922 /** An error occurred. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001923 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001924 public void onError(int error) {}
1925 }
1926
1927 /**
1928 * Allows applications to request that the system periodically send specific packets on their
1929 * behalf, using hardware offload to save battery power.
1930 *
1931 * To request that the system send keepalives, call one of the methods that return a
1932 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1933 * passing in a non-null callback. If the callback is successfully started, the callback's
1934 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1935 * specifying one of the {@code ERROR_*} constants in this class.
1936 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001937 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1938 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1939 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001940 *
junyulaia86defc2018-12-27 17:25:29 +08001941 * @deprecated Use {@link SocketKeepalive} instead.
1942 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001943 * @hide
1944 */
1945 public class PacketKeepalive {
1946
1947 private static final String TAG = "PacketKeepalive";
1948
1949 /** @hide */
1950 public static final int SUCCESS = 0;
1951
1952 /** @hide */
1953 public static final int NO_KEEPALIVE = -1;
1954
1955 /** @hide */
1956 public static final int BINDER_DIED = -10;
1957
1958 /** The specified {@code Network} is not connected. */
1959 public static final int ERROR_INVALID_NETWORK = -20;
1960 /** The specified IP addresses are invalid. For example, the specified source IP address is
1961 * not configured on the specified {@code Network}. */
1962 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1963 /** The requested port is invalid. */
1964 public static final int ERROR_INVALID_PORT = -22;
1965 /** The packet length is invalid (e.g., too long). */
1966 public static final int ERROR_INVALID_LENGTH = -23;
1967 /** The packet transmission interval is invalid (e.g., too short). */
1968 public static final int ERROR_INVALID_INTERVAL = -24;
1969
1970 /** The hardware does not support this request. */
1971 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001972 /** The hardware returned an error. */
1973 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001974
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001975 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001976 public static final int NATT_PORT = 4500;
1977
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001978 /** The minimum interval in seconds between keepalive packet transmissions */
1979 public static final int MIN_INTERVAL = 10;
1980
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001981 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001982 private final ISocketKeepaliveCallback mCallback;
1983 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001984
1985 private volatile Integer mSlot;
1986
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001987 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001988 public void stop() {
1989 try {
junyulai9f872232019-01-16 20:23:34 +08001990 mExecutor.execute(() -> {
1991 try {
1992 if (mSlot != null) {
1993 mService.stopKeepalive(mNetwork, mSlot);
1994 }
1995 } catch (RemoteException e) {
1996 Log.e(TAG, "Error stopping packet keepalive: ", e);
1997 throw e.rethrowFromSystemServer();
1998 }
1999 });
2000 } catch (RejectedExecutionException e) {
2001 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002002 }
2003 }
2004
2005 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002006 Objects.requireNonNull(network, "network cannot be null");
2007 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002008 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08002009 mExecutor = Executors.newSingleThreadExecutor();
2010 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002011 @Override
junyulai9f872232019-01-16 20:23:34 +08002012 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08002013 final long token = Binder.clearCallingIdentity();
2014 try {
2015 mExecutor.execute(() -> {
2016 mSlot = slot;
2017 callback.onStarted();
2018 });
2019 } finally {
2020 Binder.restoreCallingIdentity(token);
2021 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002022 }
junyulai9f872232019-01-16 20:23:34 +08002023
2024 @Override
2025 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08002026 final long token = Binder.clearCallingIdentity();
2027 try {
2028 mExecutor.execute(() -> {
2029 mSlot = null;
2030 callback.onStopped();
2031 });
2032 } finally {
2033 Binder.restoreCallingIdentity(token);
2034 }
junyulai9f872232019-01-16 20:23:34 +08002035 mExecutor.shutdown();
2036 }
2037
2038 @Override
2039 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08002040 final long token = Binder.clearCallingIdentity();
2041 try {
2042 mExecutor.execute(() -> {
2043 mSlot = null;
2044 callback.onError(error);
2045 });
2046 } finally {
2047 Binder.restoreCallingIdentity(token);
2048 }
junyulai9f872232019-01-16 20:23:34 +08002049 mExecutor.shutdown();
2050 }
2051
2052 @Override
2053 public void onDataReceived() {
2054 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2055 // this callback when data is received.
2056 }
2057 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002058 }
2059 }
2060
2061 /**
2062 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2063 *
junyulaia86defc2018-12-27 17:25:29 +08002064 * @deprecated Use {@link #createSocketKeepalive} instead.
2065 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002066 * @hide
2067 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002068 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002069 public PacketKeepalive startNattKeepalive(
2070 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2071 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2072 final PacketKeepalive k = new PacketKeepalive(network, callback);
2073 try {
junyulai9f872232019-01-16 20:23:34 +08002074 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002075 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2076 } catch (RemoteException e) {
2077 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08002078 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002079 }
2080 return k;
2081 }
2082
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002083 // Construct an invalid fd.
2084 private ParcelFileDescriptor createInvalidFd() {
2085 final int invalidFd = -1;
2086 return ParcelFileDescriptor.adoptFd(invalidFd);
2087 }
2088
The Android Open Source Project28527d22009-03-03 19:31:44 -08002089 /**
junyulaia86defc2018-12-27 17:25:29 +08002090 * Request that keepalives be started on a IPsec NAT-T socket.
2091 *
2092 * @param network The {@link Network} the socket is on.
2093 * @param socket The socket that needs to be kept alive.
2094 * @param source The source address of the {@link UdpEncapsulationSocket}.
2095 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2096 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2097 * must run callback sequentially, otherwise the order of callbacks cannot be
2098 * guaranteed.
2099 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2100 * changes. Must be extended by applications that use this API.
2101 *
junyulaic7ea1242019-01-08 20:04:33 +08002102 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2103 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08002104 **/
junyulai61143782019-03-04 22:45:36 +08002105 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08002106 @NonNull UdpEncapsulationSocket socket,
2107 @NonNull InetAddress source,
2108 @NonNull InetAddress destination,
2109 @NonNull @CallbackExecutor Executor executor,
2110 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002111 ParcelFileDescriptor dup;
2112 try {
junyulaic4fb2482019-03-27 11:00:37 +08002113 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2114 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08002115 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2116 } catch (IOException ignored) {
2117 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2118 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002119 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002120 }
2121 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2122 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08002123 }
2124
2125 /**
2126 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2127 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2128 *
2129 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08002130 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2131 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2132 * from that port.
junyulai48a59382019-01-15 11:32:44 +08002133 * @param source The source address of the {@link UdpEncapsulationSocket}.
2134 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2135 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2136 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2137 * must run callback sequentially, otherwise the order of callbacks cannot be
2138 * guaranteed.
2139 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2140 * changes. Must be extended by applications that use this API.
2141 *
junyulaic7ea1242019-01-08 20:04:33 +08002142 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2143 * given socket.
junyulai48a59382019-01-15 11:32:44 +08002144 * @hide
2145 */
2146 @SystemApi
2147 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002148 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2149 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08002150 @NonNull InetAddress source,
2151 @NonNull InetAddress destination,
2152 @NonNull @CallbackExecutor Executor executor,
2153 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002154 ParcelFileDescriptor dup;
2155 try {
junyulaic4fb2482019-03-27 11:00:37 +08002156 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08002157 dup = pfd.dup();
2158 } catch (IOException ignored) {
2159 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2160 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002161 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002162 }
2163 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VAN642d6ab2021-03-11 10:56:49 +00002164 -1 /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08002165 }
2166
2167 /**
junyulaic7ea1242019-01-08 20:04:33 +08002168 * Request that keepalives be started on a TCP socket.
2169 * The socket must be established.
2170 *
2171 * @param network The {@link Network} the socket is on.
2172 * @param socket The socket that needs to be kept alive.
2173 * @param executor The executor on which callback will be invoked. This implementation assumes
2174 * the provided {@link Executor} runs the callbacks in sequence with no
2175 * concurrency. Failing this, no guarantee of correctness can be made. It is
2176 * the responsibility of the caller to ensure the executor provides this
2177 * guarantee. A simple way of creating such an executor is with the standard
2178 * tool {@code Executors.newSingleThreadExecutor}.
2179 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2180 * changes. Must be extended by applications that use this API.
2181 *
2182 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2183 * given socket.
2184 * @hide
2185 */
2186 @SystemApi
2187 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002188 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002189 @NonNull Socket socket,
2190 @NonNull Executor executor,
2191 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002192 ParcelFileDescriptor dup;
2193 try {
2194 dup = ParcelFileDescriptor.fromSocket(socket);
2195 } catch (UncheckedIOException ignored) {
2196 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2197 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002198 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002199 }
2200 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002201 }
2202
2203 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002204 * Ensure that a network route exists to deliver traffic to the specified
2205 * host via the specified network interface. An attempt to add a route that
2206 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002207 *
2208 * <p>This method requires the caller to hold either the
2209 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2210 * or the ability to modify system settings as determined by
2211 * {@link android.provider.Settings.System#canWrite}.</p>
2212 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002213 * @param networkType the type of the network over which traffic to the specified
2214 * host is to be routed
2215 * @param hostAddress the IP address of the host to which the route is desired
2216 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002217 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002218 * @deprecated Deprecated in favor of the
2219 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2220 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002221 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002222 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002223 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002224 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002225 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002226 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002227 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002228 }
2229
2230 /**
2231 * Ensure that a network route exists to deliver traffic to the specified
2232 * host via the specified network interface. An attempt to add a route that
2233 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002234 *
2235 * <p>This method requires the caller to hold either the
2236 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2237 * or the ability to modify system settings as determined by
2238 * {@link android.provider.Settings.System#canWrite}.</p>
2239 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002240 * @param networkType the type of the network over which traffic to the specified
2241 * host is to be routed
2242 * @param hostAddress the IP address of the host to which the route is desired
2243 * @return {@code true} on success, {@code false} on failure
2244 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002245 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002246 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002247 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002248 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002249 @UnsupportedAppUsage
lucaslin5140e482021-03-22 11:51:27 +08002250 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002251 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002252 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002253 try {
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002254 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2255 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002256 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002257 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002258 }
2259 }
2260
2261 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002262 * @return the context's attribution tag
2263 */
2264 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2265 private @Nullable String getAttributionTag() {
2266 return mContext.getAttributionTag();
2267 }
2268
2269 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002270 * Returns the value of the setting for background data usage. If false,
2271 * applications should not use the network if the application is not in the
2272 * foreground. Developers should respect this setting, and check the value
2273 * of this before performing any background data operations.
2274 * <p>
2275 * All applications that have background services that use the network
2276 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002277 * <p>
Scott Main50589142011-10-06 18:32:43 -07002278 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002279 * background data depends on several combined factors, and this method will
2280 * always return {@code true}. Instead, when background data is unavailable,
2281 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002282 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002283 * @return Whether background data usage is allowed.
2284 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002285 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002286 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002287 // assume that background data is allowed; final authority is
2288 // NetworkInfo which may be blocked.
2289 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002290 }
2291
2292 /**
2293 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002294 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002295 * @param allowBackgroundData Whether an application should use data while
2296 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002297 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002298 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2299 * @see #getBackgroundDataSetting()
2300 * @hide
2301 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002302 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002303 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002304 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002305 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002306 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002307
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002308 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002309 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002310 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002311 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002312 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002313 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002314 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002315 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2316 if (tm != null) {
2317 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2318 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2319 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2320 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2321 + " retVal=" + retVal);
2322 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002323 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002324 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002325 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002326 }
2327
The Android Open Source Project28527d22009-03-03 19:31:44 -08002328 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002329 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002330 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002331 */
2332 public interface OnNetworkActiveListener {
2333 /**
2334 * Called on the main thread of the process to report that the current data network
2335 * has become active, and it is now a good time to perform any pending network
2336 * operations. Note that this listener only tells you when the network becomes
2337 * active; if at any other time you want to know whether it is active (and thus okay
2338 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002339 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002340 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002341 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002342 }
2343
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002344 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002345 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002346
2347 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002348 * Start listening to reports when the system's default data network is active, meaning it is
2349 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2350 * to determine the current state of the system's default network after registering the
2351 * listener.
2352 * <p>
2353 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002354 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002355 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002356 *
2357 * @param l The listener to be told when the network is active.
2358 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002359 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002360 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2361 @Override
2362 public void onNetworkActive() throws RemoteException {
2363 l.onNetworkActive();
2364 }
2365 };
2366
2367 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002368 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002369 mNetworkActivityListeners.put(l, rl);
2370 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002371 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002372 }
2373 }
2374
2375 /**
2376 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002377 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002378 *
2379 * @param l Previously registered listener.
2380 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002381 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002382 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002383 if (rl == null) {
2384 throw new IllegalArgumentException("Listener was not registered.");
2385 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002386 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002387 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002388 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002389 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002390 }
2391 }
2392
2393 /**
2394 * Return whether the data network is currently active. An active network means that
2395 * it is currently in a high power state for performing data transmission. On some
2396 * types of networks, it may be expensive to move and stay in such a state, so it is
2397 * more power efficient to batch network traffic together when the radio is already in
2398 * this state. This method tells you whether right now is currently a good time to
2399 * initiate network traffic, as the network is already active.
2400 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002401 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002402 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002403 return mService.isDefaultNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002404 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002405 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002406 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002407 }
2408
2409 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002410 * {@hide}
2411 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002412 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002413 mContext = Objects.requireNonNull(context, "missing context");
2414 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002415 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002416 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002417 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002418
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002419 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002420 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002421 public static ConnectivityManager from(Context context) {
2422 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2423 }
2424
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002425 /** @hide */
2426 public NetworkRequest getDefaultRequest() {
2427 try {
2428 // This is not racy as the default request is final in ConnectivityService.
2429 return mService.getDefaultRequest();
2430 } catch (RemoteException e) {
2431 throw e.rethrowFromSystemServer();
2432 }
2433 }
2434
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002435 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002436 * Check if the package is a allowed to write settings. This also accounts that such an access
2437 * happened.
2438 *
2439 * @return {@code true} iff the package is allowed to write settings.
2440 */
2441 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2442 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2443 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2444 boolean throwException) {
2445 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2446 callingAttributionTag, throwException);
2447 }
2448
2449 /**
Paul Jensen12131352014-12-10 15:12:18 -05002450 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2451 * situations where a Context pointer is unavailable.
2452 * @hide
2453 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002454 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002455 static ConnectivityManager getInstanceOrNull() {
2456 return sInstance;
2457 }
2458
2459 /**
2460 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2461 * situations where a Context pointer is unavailable.
2462 * @hide
2463 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002464 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002465 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002466 private static ConnectivityManager getInstance() {
2467 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002468 throw new IllegalStateException("No ConnectivityManager yet constructed");
2469 }
Paul Jensen895c3942015-03-10 10:54:12 -04002470 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002471 }
2472
2473 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002474 * Get the set of tetherable, available interfaces. This list is limited by
2475 * device configuration and current interface existence.
2476 *
2477 * @return an array of 0 or more Strings of tetherable interface names.
2478 *
markchien75721e42020-01-21 13:11:06 +08002479 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002480 * {@hide}
2481 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002482 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002483 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002484 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002485 public String[] getTetherableIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002486 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002487 }
2488
2489 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002490 * Get the set of tethered interfaces.
2491 *
2492 * @return an array of 0 or more String of currently tethered interface names.
2493 *
markchien75721e42020-01-21 13:11:06 +08002494 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002495 * {@hide}
2496 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002497 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002498 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002499 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002500 public String[] getTetheredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002501 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002502 }
2503
2504 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002505 * Get the set of interface names which attempted to tether but
2506 * failed. Re-attempting to tether may cause them to reset to the Tethered
2507 * state. Alternatively, causing the interface to be destroyed and recreated
2508 * may cause them to reset to the available state.
2509 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2510 * information on the cause of the errors.
2511 *
2512 * @return an array of 0 or more String indicating the interface names
2513 * which failed to tether.
2514 *
markchien75721e42020-01-21 13:11:06 +08002515 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002516 * {@hide}
2517 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002518 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002519 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002520 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002521 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002522 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002523 }
2524
2525 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002526 * Get the set of tethered dhcp ranges.
2527 *
markchien9e046242020-02-06 19:23:26 +08002528 * @deprecated This method is not supported.
2529 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002530 * {@hide}
2531 */
paulhuec0a9632019-08-12 16:25:11 +08002532 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien75721e42020-01-21 13:11:06 +08002533 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002534 public String[] getTetheredDhcpRanges() {
markchien9e046242020-02-06 19:23:26 +08002535 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002536 }
2537
2538 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002539 * Attempt to tether the named interface. This will setup a dhcp server
2540 * on the interface, forward and NAT IP packets and forward DNS requests
2541 * to the best active upstream network interface. Note that if no upstream
2542 * IP network interface is available, dhcp will still run and traffic will be
2543 * allowed between the tethered devices and this device, though upstream net
2544 * access will of course fail until an upstream network interface becomes
2545 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002546 *
2547 * <p>This method requires the caller to hold either the
2548 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2549 * or the ability to modify system settings as determined by
2550 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002551 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002552 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2553 * and WifiStateMachine which need direct access. All other clients should use
2554 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2555 * logic.</p>
2556 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002557 * @param iface the interface name to tether.
2558 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002559 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002560 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002561 * {@hide}
2562 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002563 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien10ddd022020-01-20 19:31:56 +08002564 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002565 public int tether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002566 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002567 }
2568
2569 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002570 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002571 *
2572 * <p>This method requires the caller to hold either the
2573 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2574 * or the ability to modify system settings as determined by
2575 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002576 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002577 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2578 * and WifiStateMachine which need direct access. All other clients should use
2579 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2580 * logic.</p>
2581 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002582 * @param iface the interface name to untether.
2583 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2584 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002585 * {@hide}
2586 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002587 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002588 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002589 public int untether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002590 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002591 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002592
2593 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002594 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002595 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002596 * due to device configuration.
2597 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002598 * <p>If this app does not have permission to use this API, it will always
2599 * return false rather than throw an exception.</p>
2600 *
2601 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2602 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2603 *
2604 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2605 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2606 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002607 * @return a boolean - {@code true} indicating Tethering is supported.
2608 *
markchien75721e42020-01-21 13:11:06 +08002609 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002610 * {@hide}
2611 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002612 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002613 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2614 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002615 public boolean isTetheringSupported() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002616 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002617 }
2618
2619 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002620 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien10ddd022020-01-20 19:31:56 +08002621 *
2622 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002623 * @hide
2624 */
2625 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002626 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002627 public static abstract class OnStartTetheringCallback {
2628 /**
2629 * Called when tethering has been successfully started.
2630 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002631 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002632
2633 /**
2634 * Called when starting tethering failed.
2635 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002636 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002637 }
2638
2639 /**
2640 * Convenient overload for
2641 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2642 * handler to run on the current thread's {@link Looper}.
markchien10ddd022020-01-20 19:31:56 +08002643 *
2644 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002645 * @hide
2646 */
2647 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002648 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002649 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002650 public void startTethering(int type, boolean showProvisioningUi,
2651 final OnStartTetheringCallback callback) {
2652 startTethering(type, showProvisioningUi, callback, null);
2653 }
2654
2655 /**
2656 * Runs tether provisioning for the given type if needed and then starts tethering if
2657 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2658 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2659 * schedules tether provisioning re-checks if appropriate.
2660 *
2661 * @param type The type of tethering to start. Must be one of
2662 * {@link ConnectivityManager.TETHERING_WIFI},
2663 * {@link ConnectivityManager.TETHERING_USB}, or
2664 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2665 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2666 * is one. This should be true the first time this function is called and also any time
2667 * the user can see this UI. It gives users information from their carrier about the
2668 * check failing and how they can sign up for tethering if possible.
2669 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2670 * of the result of trying to tether.
2671 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien10ddd022020-01-20 19:31:56 +08002672 *
2673 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002674 * @hide
2675 */
2676 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002677 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002678 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002679 public void startTethering(int type, boolean showProvisioningUi,
2680 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002681 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002682
markchien10ddd022020-01-20 19:31:56 +08002683 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002684 @Override
markchien10ddd022020-01-20 19:31:56 +08002685 public void execute(Runnable command) {
2686 if (handler == null) {
2687 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002688 } else {
markchien10ddd022020-01-20 19:31:56 +08002689 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002690 }
2691 }
2692 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002693
markchien10ddd022020-01-20 19:31:56 +08002694 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2695 @Override
2696 public void onTetheringStarted() {
2697 callback.onTetheringStarted();
2698 }
2699
2700 @Override
markchien68b67842020-03-19 13:37:43 +08002701 public void onTetheringFailed(final int error) {
markchien10ddd022020-01-20 19:31:56 +08002702 callback.onTetheringFailed();
2703 }
2704 };
2705
2706 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien68b67842020-03-19 13:37:43 +08002707 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien10ddd022020-01-20 19:31:56 +08002708
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002709 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002710 }
2711
2712 /**
2713 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2714 * applicable.
2715 *
2716 * @param type The type of tethering to stop. Must be one of
2717 * {@link ConnectivityManager.TETHERING_WIFI},
2718 * {@link ConnectivityManager.TETHERING_USB}, or
2719 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien75721e42020-01-21 13:11:06 +08002720 *
2721 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002722 * @hide
2723 */
2724 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002725 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002726 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002727 public void stopTethering(int type) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002728 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002729 }
2730
2731 /**
markchiena005c992019-02-27 14:56:11 +08002732 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2733 * upstream status.
2734 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002735 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien75721e42020-01-21 13:11:06 +08002736 * @hide
markchiena005c992019-02-27 14:56:11 +08002737 */
2738 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002739 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002740 public abstract static class OnTetheringEventCallback {
2741
2742 /**
2743 * Called when tethering upstream changed. This can be called multiple times and can be
2744 * called any time.
2745 *
2746 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2747 * have any upstream.
2748 */
2749 public void onUpstreamChanged(@Nullable Network network) {}
2750 }
2751
markchien75721e42020-01-21 13:11:06 +08002752 @GuardedBy("mTetheringEventCallbacks")
2753 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2754 mTetheringEventCallbacks = new ArrayMap<>();
2755
markchiena005c992019-02-27 14:56:11 +08002756 /**
2757 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002758 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002759 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2760 * with a null argument. The same callback object cannot be registered twice.
2761 *
2762 * @param executor the executor on which callback will be invoked.
2763 * @param callback the callback to be called when tethering has change events.
markchien75721e42020-01-21 13:11:06 +08002764 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002765 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002766 * @hide
2767 */
2768 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002769 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002770 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2771 public void registerTetheringEventCallback(
2772 @NonNull @CallbackExecutor Executor executor,
2773 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002774 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchiena005c992019-02-27 14:56:11 +08002775
markchien75721e42020-01-21 13:11:06 +08002776 final TetheringEventCallback tetherCallback =
2777 new TetheringEventCallback() {
2778 @Override
2779 public void onUpstreamChanged(@Nullable Network network) {
2780 callback.onUpstreamChanged(network);
2781 }
2782 };
2783
2784 synchronized (mTetheringEventCallbacks) {
2785 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002786 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002787 }
markchiena005c992019-02-27 14:56:11 +08002788 }
2789
2790 /**
2791 * Remove tethering event callback previously registered with
2792 * {@link #registerTetheringEventCallback}.
2793 *
2794 * @param callback previously registered callback.
markchien75721e42020-01-21 13:11:06 +08002795 *
2796 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002797 * @hide
2798 */
2799 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002800 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002801 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2802 public void unregisterTetheringEventCallback(
2803 @NonNull final OnTetheringEventCallback callback) {
markchien75721e42020-01-21 13:11:06 +08002804 Objects.requireNonNull(callback, "The callback must be non-null");
2805 synchronized (mTetheringEventCallbacks) {
2806 final TetheringEventCallback tetherCallback =
2807 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002808 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002809 }
markchiena005c992019-02-27 14:56:11 +08002810 }
2811
2812
2813 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002814 * Get the list of regular expressions that define any tetherable
2815 * USB network interfaces. If USB tethering is not supported by the
2816 * device, this list should be empty.
2817 *
2818 * @return an array of 0 or more regular expression Strings defining
2819 * what interfaces are considered tetherable usb interfaces.
2820 *
markchien75721e42020-01-21 13:11:06 +08002821 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002822 * {@hide}
2823 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002824 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002825 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002826 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002827 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002828 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002829 }
2830
2831 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002832 * Get the list of regular expressions that define any tetherable
2833 * Wifi network interfaces. If Wifi tethering is not supported by the
2834 * device, this list should be empty.
2835 *
2836 * @return an array of 0 or more regular expression Strings defining
2837 * what interfaces are considered tetherable wifi interfaces.
2838 *
markchien75721e42020-01-21 13:11:06 +08002839 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002840 * {@hide}
2841 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002842 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002843 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002844 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002845 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002846 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002847 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002848
Danica Chang96567052010-08-11 14:54:43 -07002849 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002850 * Get the list of regular expressions that define any tetherable
2851 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2852 * device, this list should be empty.
2853 *
2854 * @return an array of 0 or more regular expression Strings defining
2855 * what interfaces are considered tetherable bluetooth interfaces.
2856 *
markchien75721e42020-01-21 13:11:06 +08002857 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2858 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002859 * {@hide}
2860 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002861 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002862 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002863 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002864 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002865 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002866 }
2867
Mike Lockwooded4a1742011-07-19 13:04:47 -07002868 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002869 * Attempt to both alter the mode of USB and Tethering of USB. A
2870 * utility method to deal with some of the complexity of USB - will
2871 * attempt to switch to Rndis and subsequently tether the resulting
2872 * interface on {@code true} or turn off tethering and switch off
2873 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002874 *
2875 * <p>This method requires the caller to hold either the
2876 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2877 * or the ability to modify system settings as determined by
2878 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002879 *
2880 * @param enable a boolean - {@code true} to enable tethering
2881 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002882 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002883 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002884 * {@hide}
2885 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002886 @UnsupportedAppUsage
markchien10ddd022020-01-20 19:31:56 +08002887 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002888 public int setUsbTethering(boolean enable) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002889 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002890 }
2891
markchien75721e42020-01-21 13:11:06 +08002892 /**
2893 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2894 * {@hide}
2895 */
markchien5bd499c2019-01-16 17:44:13 +08002896 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002897 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002898 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien75721e42020-01-21 13:11:06 +08002899 /**
2900 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2901 * {@hide}
2902 */
2903 @Deprecated
2904 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2905 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2906 /**
2907 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2908 * {@hide}
2909 */
2910 @Deprecated
2911 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2912 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2913 /**
2914 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2915 * {@hide}
2916 */
2917 @Deprecated
2918 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2919 /**
2920 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2921 * {@hide}
2922 */
2923 @Deprecated
2924 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2925 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2926 /**
markchien68b67842020-03-19 13:37:43 +08002927 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002928 * {@hide}
2929 */
2930 @Deprecated
markchien68b67842020-03-19 13:37:43 +08002931 public static final int TETHER_ERROR_MASTER_ERROR =
2932 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien75721e42020-01-21 13:11:06 +08002933 /**
2934 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2935 * {@hide}
2936 */
2937 @Deprecated
2938 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2939 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2940 /**
2941 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2942 * {@hide}
2943 */
2944 @Deprecated
2945 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2946 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2947 /**
markchien68b67842020-03-19 13:37:43 +08002948 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002949 * {@hide}
2950 */
2951 @Deprecated
2952 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002953 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002954 /**
markchien68b67842020-03-19 13:37:43 +08002955 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002956 * {@hide}
2957 */
2958 @Deprecated
2959 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002960 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002961 /**
2962 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2963 * {@hide}
2964 */
2965 @Deprecated
2966 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2967 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2968 /**
markchien68b67842020-03-19 13:37:43 +08002969 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien75721e42020-01-21 13:11:06 +08002970 * {@hide}
2971 */
markchien5bd499c2019-01-16 17:44:13 +08002972 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002973 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002974 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien75721e42020-01-21 13:11:06 +08002975 /**
2976 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2977 * {@hide}
2978 */
2979 @Deprecated
2980 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2981 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2982 /**
2983 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2984 * {@hide}
2985 */
markchien5bd499c2019-01-16 17:44:13 +08002986 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002987 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002988 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002989
2990 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002991 * Get a more detailed error code after a Tethering or Untethering
2992 * request asynchronously failed.
2993 *
2994 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002995 * @return error The error code of the last error tethering or untethering the named
2996 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002997 *
markchien75721e42020-01-21 13:11:06 +08002998 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002999 * {@hide}
3000 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003001 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00003002 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien75721e42020-01-21 13:11:06 +08003003 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003004 public int getLastTetherError(String iface) {
markchien68b67842020-03-19 13:37:43 +08003005 int error = mTetheringManager.getLastTetherError(iface);
3006 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3007 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3008 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3009 // instead.
3010 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3011 }
3012 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003013 }
3014
markchiendd41c822019-03-06 16:25:00 +08003015 /** @hide */
3016 @Retention(RetentionPolicy.SOURCE)
3017 @IntDef(value = {
3018 TETHER_ERROR_NO_ERROR,
3019 TETHER_ERROR_PROVISION_FAILED,
3020 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3021 })
3022 public @interface EntitlementResultCode {
3023 }
3024
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003025 /**
markchiendd41c822019-03-06 16:25:00 +08003026 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08003027 * entitlement succeeded.
markchien75721e42020-01-21 13:11:06 +08003028 *
3029 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08003030 * @hide
3031 */
3032 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003033 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08003034 public interface OnTetheringEntitlementResultListener {
3035 /**
3036 * Called to notify entitlement result.
3037 *
3038 * @param resultCode an int value of entitlement result. It may be one of
3039 * {@link #TETHER_ERROR_NO_ERROR},
3040 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3041 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3042 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07003043 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08003044 }
3045
3046 /**
markchien5bd499c2019-01-16 17:44:13 +08003047 * Get the last value of the entitlement check on this downstream. If the cached value is
3048 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3049 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3050 * guaranteed that the UI-based entitlement check will complete in any specific time period
3051 * and may in fact never complete. Any successful entitlement check the platform performs for
3052 * any reason will update the cached value.
3053 *
3054 * @param type the downstream type of tethering. Must be one of
3055 * {@link #TETHERING_WIFI},
3056 * {@link #TETHERING_USB}, or
3057 * {@link #TETHERING_BLUETOOTH}.
3058 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08003059 * @param executor the executor on which callback will be invoked.
3060 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3061 * notify the caller of the result of entitlement check. The listener may be called zero
3062 * or one time.
markchien75721e42020-01-21 13:11:06 +08003063 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08003064 * {@hide}
3065 */
3066 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003067 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08003068 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08003069 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3070 @NonNull @CallbackExecutor Executor executor,
3071 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003072 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchiendd41c822019-03-06 16:25:00 +08003073 ResultReceiver wrappedListener = new ResultReceiver(null) {
3074 @Override
3075 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslin9cc04192021-03-04 09:38:21 +08003076 final long token = Binder.clearCallingIdentity();
3077 try {
3078 executor.execute(() -> {
3079 listener.onTetheringEntitlementResult(resultCode);
3080 });
3081 } finally {
3082 Binder.restoreCallingIdentity(token);
3083 }
markchiendd41c822019-03-06 16:25:00 +08003084 }
3085 };
3086
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00003087 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienb0bb7862019-12-16 20:15:20 +08003088 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08003089 }
3090
3091 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003092 * Report network connectivity status. This is currently used only
3093 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003094 * <p>This method requires the caller to hold the permission
3095 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003096 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003097 * @param networkType The type of network you want to report on
3098 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09003099 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003100 * {@hide}
3101 */
3102 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003103 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003104 try {
3105 mService.reportInetCondition(networkType, percentage);
3106 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003107 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003108 }
3109 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003110
3111 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003112 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07003113 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003114 * the framework to re-evaluate network connectivity and/or switch to another
3115 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003116 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003117 * @param network The {@link Network} the application was attempting to use
3118 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04003119 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3120 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003121 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003122 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09003123 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003124 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003125 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04003126 // One of these will be ignored because it matches system's current state.
3127 // The other will trigger the necessary reevaluation.
3128 mService.reportNetworkConnectivity(network, true);
3129 mService.reportNetworkConnectivity(network, false);
3130 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003131 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003132 }
3133 }
3134
3135 /**
3136 * Report to the framework whether a network has working connectivity.
3137 * This provides a hint to the system that a particular network is providing
3138 * working connectivity or not. In response the framework may re-evaluate
3139 * the network's connectivity and might take further action thereafter.
3140 *
3141 * @param network The {@link Network} the application was attempting to use
3142 * or {@code null} to indicate the current default network.
3143 * @param hasConnectivity {@code true} if the application was able to successfully access the
3144 * Internet using {@code network} or {@code false} if not.
3145 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003146 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003147 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003148 try {
3149 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003150 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003151 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003152 }
3153 }
3154
3155 /**
Chalard Jeanaac3b872021-03-17 17:03:34 +09003156 * Set a network-independent global HTTP proxy.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003157 *
Chalard Jeanaac3b872021-03-17 17:03:34 +09003158 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3159 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3160 * accessing any network, regardless of what the settings for that network are.
3161 *
3162 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3163 * proxy is likely to break networking on multiple networks. This method is only meant
3164 * for device policy clients looking to do general internal filtering or similar use cases.
3165 *
3166 * {@see #getGlobalProxy}
3167 * {@see LinkProperties#getHttpProxy}
3168 *
3169 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3170 * method with a {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003171 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003172 */
Chalard Jeanaac3b872021-03-17 17:03:34 +09003173 // Used by Device Policy Manager to set the global proxy.
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003174 @SystemApi(client = MODULE_LIBRARIES)
paulhuec0a9632019-08-12 16:25:11 +08003175 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeanaac3b872021-03-17 17:03:34 +09003176 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003177 try {
3178 mService.setGlobalProxy(p);
3179 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003180 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003181 }
3182 }
3183
3184 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003185 * Retrieve any network-independent global HTTP proxy.
3186 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003187 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003188 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003189 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003190 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003191 @SystemApi(client = MODULE_LIBRARIES)
3192 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04003193 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003194 try {
3195 return mService.getGlobalProxy();
3196 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003197 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003198 }
3199 }
3200
3201 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003202 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3203 * network-specific HTTP proxy. If {@code network} is null, the
3204 * network-specific proxy returned is the proxy of the default active
3205 * network.
3206 *
3207 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3208 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3209 * or when {@code network} is {@code null},
3210 * the {@code ProxyInfo} for the default active network. Returns
3211 * {@code null} when no proxy applies or the caller doesn't have
3212 * permission to use {@code network}.
3213 * @hide
3214 */
3215 public ProxyInfo getProxyForNetwork(Network network) {
3216 try {
3217 return mService.getProxyForNetwork(network);
3218 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003219 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003220 }
3221 }
3222
3223 /**
Paul Jensen12131352014-12-10 15:12:18 -05003224 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3225 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003226 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003227 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003228 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003229 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003230 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003231 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003232 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003233 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003234 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003235 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003236
3237 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003238 * Returns true if the hardware supports the given network type
3239 * else it returns false. This doesn't indicate we have coverage
3240 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003241 * hardware supports it. For example a GSM phone without a SIM
3242 * should still return {@code true} for mobile data, but a wifi only
3243 * tablet would return {@code false}.
3244 *
3245 * @param networkType The network type we'd like to check
3246 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003247 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003248 * @hide
3249 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003250 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003251 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003252 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003253 public boolean isNetworkSupported(int networkType) {
3254 try {
3255 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003256 } catch (RemoteException e) {
3257 throw e.rethrowFromSystemServer();
3258 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003259 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003260
3261 /**
3262 * Returns if the currently active data network is metered. A network is
3263 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003264 * that connection due to monetary costs, data limitations or
3265 * battery/performance issues. You should check this before doing large
3266 * data transfers, and warn the user or delay the operation until another
3267 * network is available.
3268 *
3269 * @return {@code true} if large transfers should be avoided, otherwise
3270 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003271 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003272 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003273 public boolean isActiveNetworkMetered() {
3274 try {
3275 return mService.isActiveNetworkMetered();
3276 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003277 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003278 }
3279 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003280
Robert Greenwalt26744a52013-02-15 10:56:35 -08003281 /**
Sarah Chincab74db2020-11-25 12:15:14 -08003282 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003283 *
Sarah Chincab74db2020-11-25 12:15:14 -08003284 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003285 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003286 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003287 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003288 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003289 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003290 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003291 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003292 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003293 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003294 }
3295 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003296
3297 /**
3298 * Set the value for enabling/disabling airplane mode
3299 *
3300 * @param enable whether to enable airplane mode or not
3301 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003302 * @hide
3303 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003304 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003305 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003306 android.Manifest.permission.NETWORK_SETTINGS,
3307 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3308 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003309 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003310 public void setAirplaneMode(boolean enable) {
3311 try {
3312 mService.setAirplaneMode(enable);
3313 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003314 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003315 }
3316 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003317
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003318 /**
3319 * Registers the specified {@link NetworkProvider}.
3320 * Each listener must only be registered once. The listener can be unregistered with
3321 * {@link #unregisterNetworkProvider}.
3322 *
3323 * @param provider the provider to register
3324 * @return the ID of the provider. This ID must be used by the provider when registering
3325 * {@link android.net.NetworkAgent}s.
3326 * @hide
3327 */
3328 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003329 @RequiresPermission(anyOf = {
3330 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3331 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003332 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3333 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003334 throw new IllegalStateException("NetworkProviders can only be registered once");
3335 }
3336
3337 try {
3338 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3339 provider.getName());
3340 provider.setProviderId(providerId);
3341 } catch (RemoteException e) {
3342 throw e.rethrowFromSystemServer();
3343 }
3344 return provider.getProviderId();
3345 }
3346
3347 /**
3348 * Unregisters the specified NetworkProvider.
3349 *
3350 * @param provider the provider to unregister
3351 * @hide
3352 */
3353 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003354 @RequiresPermission(anyOf = {
3355 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3356 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003357 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3358 try {
3359 mService.unregisterNetworkProvider(provider.getMessenger());
3360 } catch (RemoteException e) {
3361 throw e.rethrowFromSystemServer();
3362 }
3363 provider.setProviderId(NetworkProvider.ID_NONE);
3364 }
3365
Chalard Jean1ef1d902021-01-05 08:40:09 +09003366 /**
3367 * Register or update a network offer with ConnectivityService.
3368 *
3369 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jeand7268cd2021-03-24 17:43:10 +09003370 * them to networking requests made by apps or the system. A callback identifies an offer
3371 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3372 * score and the capabilities of the network it might be able to bring up ; these act as
3373 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jean1ef1d902021-01-05 08:40:09 +09003374 * provider.
3375 *
3376 * The provider is under no obligation to be able to bring up the network it offers at any
3377 * given time. Instead, this mechanism is meant to limit requests received by providers
3378 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3379 * the quality of the network satisfying a given request to their own offer.
3380 *
3381 * An offer can be updated by calling this again with the same callback object. This is
3382 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3383 * provider with the changes caused by the changes in the offer.
3384 *
3385 * @param provider The provider making this offer.
3386 * @param score The prospective score of the network.
3387 * @param caps The prospective capabilities of the network.
3388 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003389 * @hide exposed via the NetworkProvider class.
Chalard Jean1ef1d902021-01-05 08:40:09 +09003390 */
3391 @RequiresPermission(anyOf = {
3392 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3393 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanb004da52021-03-22 22:44:02 +09003394 public void offerNetwork(@NonNull final int providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09003395 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3396 @NonNull final INetworkOfferCallback callback) {
3397 try {
Chalard Jeanb004da52021-03-22 22:44:02 +09003398 mService.offerNetwork(providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09003399 Objects.requireNonNull(score, "null score"),
3400 Objects.requireNonNull(caps, "null caps"),
3401 Objects.requireNonNull(callback, "null callback"));
3402 } catch (RemoteException e) {
3403 throw e.rethrowFromSystemServer();
3404 }
3405 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003406
Chalard Jean1ef1d902021-01-05 08:40:09 +09003407 /**
3408 * Withdraw a network offer made with {@link #offerNetwork}.
3409 *
3410 * @param callback The callback passed at registration time. This must be the same object
3411 * that was passed to {@link #offerNetwork}
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003412 * @hide exposed via the NetworkProvider class.
Chalard Jean1ef1d902021-01-05 08:40:09 +09003413 */
3414 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3415 try {
3416 mService.unofferNetwork(Objects.requireNonNull(callback));
3417 } catch (RemoteException e) {
3418 throw e.rethrowFromSystemServer();
3419 }
3420 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003421 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003422 @RequiresPermission(anyOf = {
3423 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3424 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003425 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3426 try {
3427 mService.declareNetworkRequestUnfulfillable(request);
3428 } catch (RemoteException e) {
3429 throw e.rethrowFromSystemServer();
3430 }
3431 }
3432
Paul Jensenc2569432015-02-13 14:18:39 -05003433 /**
3434 * @hide
3435 * Register a NetworkAgent with ConnectivityService.
Chalard Jean1aea87a2019-12-13 19:47:12 +09003436 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003437 */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003438 @RequiresPermission(anyOf = {
3439 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3440 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003441 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeandd753522020-12-21 18:36:52 +09003442 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3443 int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003444 try {
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003445 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003446 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003447 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003448 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003449 }
3450
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003451 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003452 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3453 * changes. Should be extended by applications wanting notifications.
3454 *
3455 * A {@code NetworkCallback} is registered by calling
3456 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3457 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003458 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003459 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3460 * A {@code NetworkCallback} should be registered at most once at any time.
3461 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003462 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003463 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003464 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003465 * No flags associated with this callback.
3466 * @hide
3467 */
3468 public static final int FLAG_NONE = 0;
3469 /**
3470 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3471 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3472 * <p>
3473 * These include:
3474 * <li> Some transport info instances (retrieved via
3475 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3476 * contain location sensitive information.
3477 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3478 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3479 * </p>
3480 * <p>
3481 * Note:
3482 * <li> Retrieving this location sensitive information (subject to app's location
3483 * permissions) will be noted by system. </li>
3484 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3485 * not include location sensitive info.
3486 * </p>
3487 */
Roshan Piusf75ffaa2021-03-11 21:16:44 -08003488 // Note: Some existing fields which are location sensitive may still be included without
3489 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Pius7992afd2020-12-22 15:10:42 -08003490 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3491
3492 /** @hide */
3493 @Retention(RetentionPolicy.SOURCE)
3494 @IntDef(flag = true, prefix = "FLAG_", value = {
3495 FLAG_NONE,
3496 FLAG_INCLUDE_LOCATION_INFO
3497 })
3498 public @interface Flag { }
3499
3500 /**
3501 * All the valid flags for error checking.
3502 */
3503 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3504
3505 public NetworkCallback() {
3506 this(FLAG_NONE);
3507 }
3508
3509 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003510 if ((flags & VALID_FLAGS) != flags) {
3511 throw new IllegalArgumentException("Invalid flags");
3512 }
Roshan Pius7992afd2020-12-22 15:10:42 -08003513 mFlags = flags;
3514 }
3515
3516 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003517 * Called when the framework connects to a new network to evaluate whether it satisfies this
3518 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3519 * callback. There is no guarantee that this new network will satisfy any requests, or that
3520 * the network will stay connected for longer than the time necessary to evaluate it.
3521 * <p>
3522 * Most applications <b>should not</b> act on this callback, and should instead use
3523 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3524 * the framework in properly evaluating the network &mdash; for example, an application that
3525 * can automatically log in to a captive portal without user intervention.
3526 *
3527 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003528 *
3529 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003530 */
paulhua9a6e2a2019-03-22 16:35:06 +08003531 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003532
3533 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003534 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003535 * This callback may be called more than once if the {@link Network} that is
3536 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003537 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003538 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003539 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3540 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003541 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003542 * @hide
3543 */
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003544 public final void onAvailable(@NonNull Network network,
paulhua9a6e2a2019-03-22 16:35:06 +08003545 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003546 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003547 // Internally only this method is called when a new network is available, and
3548 // it calls the callback in the same way and order that older versions used
3549 // to call so as not to change the behavior.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003550 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3551 onBlockedStatusChanged(network, blocked);
3552 }
3553
3554 /**
3555 * Legacy variant of onAvailable that takes a boolean blocked reason.
3556 *
3557 * This method has never been public API, but it's not final, so there may be apps that
3558 * implemented it and rely on it being called. Do our best not to break them.
3559 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3560 * this method is called. There does not seem to be a way to avoid this.
3561 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3562 *
3563 * @hide
3564 */
3565 public void onAvailable(@NonNull Network network,
3566 @NonNull NetworkCapabilities networkCapabilities,
3567 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003568 onAvailable(network);
3569 if (!networkCapabilities.hasCapability(
3570 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3571 onNetworkSuspended(network);
3572 }
3573 onCapabilitiesChanged(network, networkCapabilities);
3574 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003575 // No call to onBlockedStatusChanged here. That is done by the caller.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003576 }
3577
3578 /**
3579 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003580 *
3581 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3582 * be available at the same time, and onAvailable will be called for each of these as they
3583 * appear.
3584 *
3585 * <p>For callbacks registered with {@link #requestNetwork} and
3586 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3587 * is the new best network for this request and is now tracked by this callback ; this
3588 * callback will no longer receive method calls about other networks that may have been
3589 * passed to this method previously. The previously-best network may have disconnected, or
3590 * it may still be around and the newly-best network may simply be better.
3591 *
3592 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3593 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3594 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3595 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3596 *
3597 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3598 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3599 * this callback as this is prone to race conditions (there is no guarantee the objects
3600 * returned by these methods will be current). Instead, wait for a call to
3601 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3602 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3603 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003604 *
3605 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003606 */
paulhua9a6e2a2019-03-22 16:35:06 +08003607 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003608
3609 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003610 * Called when the network is about to be lost, typically because there are no outstanding
3611 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3612 * with the new replacement network for graceful handover. This method is not guaranteed
3613 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3614 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003615 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003616 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3617 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3618 * this callback as this is prone to race conditions ; calling these methods while in a
3619 * callback may return an outdated or even a null object.
3620 *
3621 * @param network The {@link Network} that is about to be lost.
3622 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3623 * connected for graceful handover; note that the network may still
3624 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003625 */
paulhua9a6e2a2019-03-22 16:35:06 +08003626 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003627
3628 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003629 * Called when a network disconnects or otherwise no longer satisfies this request or
3630 * callback.
3631 *
3632 * <p>If the callback was registered with requestNetwork() or
3633 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3634 * returned by onAvailable() when that network is lost and no other network satisfies
3635 * the criteria of the request.
3636 *
3637 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3638 * each network which no longer satisfies the criteria of the callback.
3639 *
3640 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3641 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3642 * this callback as this is prone to race conditions ; calling these methods while in a
3643 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003644 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003645 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003646 */
paulhua9a6e2a2019-03-22 16:35:06 +08003647 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003648
3649 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003650 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003651 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3652 * requested network request cannot be fulfilled (whether or not a timeout was
3653 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003654 * {@link NetworkRequest} will have already been removed and released, as if
3655 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003656 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003657 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003658
3659 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003660 * Called when the network corresponding to this request changes capabilities but still
3661 * satisfies the requested criteria.
3662 *
3663 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3664 * to be called immediately after {@link #onAvailable}.
3665 *
3666 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3667 * ConnectivityManager methods in this callback as this is prone to race conditions :
3668 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003669 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003670 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius7992afd2020-12-22 15:10:42 -08003671 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003672 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003673 */
paulhua9a6e2a2019-03-22 16:35:06 +08003674 public void onCapabilitiesChanged(@NonNull Network network,
3675 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003676
3677 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003678 * Called when the network corresponding to this request changes {@link LinkProperties}.
3679 *
3680 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3681 * to be called immediately after {@link #onAvailable}.
3682 *
3683 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3684 * ConnectivityManager methods in this callback as this is prone to race conditions :
3685 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003686 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003687 * @param network The {@link Network} whose link properties have changed.
3688 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003689 */
paulhua9a6e2a2019-03-22 16:35:06 +08003690 public void onLinkPropertiesChanged(@NonNull Network network,
3691 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003692
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003693 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003694 * Called when the network the framework connected to for this request suspends data
3695 * transmission temporarily.
3696 *
3697 * <p>This generally means that while the TCP connections are still live temporarily
3698 * network data fails to transfer. To give a specific example, this is used on cellular
3699 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3700 * means read operations on sockets on this network will block once the buffers are
3701 * drained, and write operations will block once the buffers are full.
3702 *
3703 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3704 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3705 * this callback as this is prone to race conditions (there is no guarantee the objects
3706 * returned by these methods will be current).
3707 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003708 * @hide
3709 */
paulhua9a6e2a2019-03-22 16:35:06 +08003710 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003711
3712 /**
3713 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003714 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3715 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003716
3717 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3718 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3719 * this callback as this is prone to race conditions : calling these methods while in a
3720 * callback may return an outdated or even a null object.
3721 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003722 * @hide
3723 */
paulhua9a6e2a2019-03-22 16:35:06 +08003724 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003725
junyulai5ab727b2018-08-07 19:50:45 +08003726 /**
3727 * Called when access to the specified network is blocked or unblocked.
3728 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003729 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3730 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3731 * this callback as this is prone to race conditions : calling these methods while in a
3732 * callback may return an outdated or even a null object.
3733 *
junyulai5ab727b2018-08-07 19:50:45 +08003734 * @param network The {@link Network} whose blocked status has changed.
3735 * @param blocked The blocked status of this {@link Network}.
3736 */
junyulai61143782019-03-04 22:45:36 +08003737 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003738
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003739 /**
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09003740 * Called when access to the specified network is blocked or unblocked, or the reason for
3741 * access being blocked changes.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003742 *
3743 * If a NetworkCallback object implements this method,
3744 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3745 *
3746 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3747 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3748 * this callback as this is prone to race conditions : calling these methods while in a
3749 * callback may return an outdated or even a null object.
3750 *
3751 * @param network The {@link Network} whose blocked status has changed.
3752 * @param blocked The blocked status of this {@link Network}.
3753 * @hide
3754 */
3755 @SystemApi(client = MODULE_LIBRARIES)
3756 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3757 onBlockedStatusChanged(network, blocked != 0);
3758 }
3759
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003760 private NetworkRequest networkRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -08003761 private final int mFlags;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003762 }
3763
Hugo Benichi145e3792017-05-11 13:16:17 +09003764 /**
3765 * Constant error codes used by ConnectivityService to communicate about failures and errors
3766 * across a Binder boundary.
3767 * @hide
3768 */
3769 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003770 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003771 }
3772
3773 /** @hide */
3774 public static class TooManyRequestsException extends RuntimeException {}
3775
3776 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3777 switch (e.errorCode) {
3778 case Errors.TOO_MANY_REQUESTS:
3779 return new TooManyRequestsException();
3780 default:
3781 Log.w(TAG, "Unknown service error code " + e.errorCode);
3782 return new RuntimeException(e);
3783 }
3784 }
3785
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003786 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003787 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003788 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003789 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003790 /** @hide arg1 = TTL */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003791 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003792 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003793 public static final int CALLBACK_LOST = 4;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003794 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003795 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003796 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003797 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003798 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003799 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003800 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003801 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003802 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003803 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003804 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003805 public static final int CALLBACK_RESUMED = 10;
junyulai5ab727b2018-08-07 19:50:45 +08003806 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003807 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003808
Erik Kline66721822015-11-25 12:49:38 +09003809 /** @hide */
3810 public static String getCallbackName(int whichCallback) {
3811 switch (whichCallback) {
3812 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3813 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3814 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3815 case CALLBACK_LOST: return "CALLBACK_LOST";
3816 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3817 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3818 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003819 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3820 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3821 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003822 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003823 default:
3824 return Integer.toString(whichCallback);
3825 }
3826 }
3827
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003828 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003829 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003830 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003831
Hugo Benichife3325f2016-07-06 22:53:17 +09003832 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003833 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003834 }
3835
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003836 CallbackHandler(Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003837 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003838 }
3839
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003840 @Override
3841 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003842 if (message.what == EXPIRE_LEGACY_REQUEST) {
3843 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3844 return;
3845 }
3846
3847 final NetworkRequest request = getObject(message, NetworkRequest.class);
3848 final Network network = getObject(message, Network.class);
3849 final NetworkCallback callback;
3850 synchronized (sCallbacks) {
3851 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003852 if (callback == null) {
3853 Log.w(TAG,
3854 "callback not found for " + getCallbackName(message.what) + " message");
3855 return;
3856 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003857 if (message.what == CALLBACK_UNAVAIL) {
3858 sCallbacks.remove(request);
3859 callback.networkRequest = ALREADY_UNREGISTERED;
3860 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003861 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003862 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003863 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003864 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003865
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003866 switch (message.what) {
3867 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003868 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003869 break;
3870 }
3871 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003872 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3873 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003874 callback.onAvailable(network, cap, lp, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003875 break;
3876 }
3877 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003878 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003879 break;
3880 }
3881 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003882 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003883 break;
3884 }
3885 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003886 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003887 break;
3888 }
3889 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003890 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3891 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003892 break;
3893 }
3894 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003895 LinkProperties lp = getObject(message, LinkProperties.class);
3896 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003897 break;
3898 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003899 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003900 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003901 break;
3902 }
3903 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003904 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003905 break;
3906 }
junyulai5ab727b2018-08-07 19:50:45 +08003907 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003908 callback.onBlockedStatusChanged(network, message.arg1);
junyulai5ab727b2018-08-07 19:50:45 +08003909 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003910 }
3911 }
3912
Hugo Benichife3325f2016-07-06 22:53:17 +09003913 private <T> T getObject(Message msg, Class<T> c) {
3914 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003915 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003916 }
3917
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003918 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003919 synchronized (sCallbacks) {
3920 if (sCallbackHandler == null) {
3921 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003922 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003923 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003924 }
3925 }
3926
Hugo Benichiec180d52017-02-03 14:18:44 +09003927 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3928 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003929
Lorenzo Colittib199b962021-03-12 22:48:07 +09003930 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3931 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3932 CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003933 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003934 checkCallbackNotNull(callback);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003935 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3936 throw new IllegalArgumentException("null NetworkCapabilities");
3937 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003938 final NetworkRequest request;
Roshan Piusd26ae412020-01-16 12:17:17 -08003939 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003940 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003941 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003942 if (callback.networkRequest != null
3943 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003944 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3945 // and requests (http://b/20701525).
3946 Log.e(TAG, "NetworkCallback was already registered");
3947 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003948 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003949 Binder binder = new Binder();
Roshan Pius7992afd2020-12-22 15:10:42 -08003950 final int callbackFlags = callback.mFlags;
junyulaid1a78162021-01-11 16:53:38 +08003951 if (reqType == LISTEN) {
Roshan Piusd26ae412020-01-16 12:17:17 -08003952 request = mService.listenForNetwork(
Roshan Pius7992afd2020-12-22 15:10:42 -08003953 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08003954 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003955 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003956 request = mService.requestNetwork(
Lorenzo Colittib199b962021-03-12 22:48:07 +09003957 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3958 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003959 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003960 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003961 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003962 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003963 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003964 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003965 } catch (RemoteException e) {
3966 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003967 } catch (ServiceSpecificException e) {
3968 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003969 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003970 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003971 }
3972
Lorenzo Colittib199b962021-03-12 22:48:07 +09003973 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3974 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3975 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3976 legacyType, handler);
3977 }
3978
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003979 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003980 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003981 *
markchien0fe11402020-03-18 21:16:15 +08003982 * This API is only for use in internal system code that requests networks with legacy type and
3983 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchien769c5752020-01-14 12:54:40 +08003984 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003985 *
markchien769c5752020-01-14 12:54:40 +08003986 * @param request {@link NetworkRequest} describing this request.
markchien769c5752020-01-14 12:54:40 +08003987 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3988 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3989 * be a positive value (i.e. >0).
3990 * @param legacyType to specify the network type(#TYPE_*).
3991 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien0fe11402020-03-18 21:16:15 +08003992 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3993 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003994 *
3995 * @hide
3996 */
markchien769c5752020-01-14 12:54:40 +08003997 @SystemApi
markchien0fe11402020-03-18 21:16:15 +08003998 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003999 public void requestNetwork(@NonNull NetworkRequest request,
markchien0fe11402020-03-18 21:16:15 +08004000 int timeoutMs, int legacyType, @NonNull Handler handler,
4001 @NonNull NetworkCallback networkCallback) {
4002 if (legacyType == TYPE_NONE) {
4003 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4004 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004005 CallbackHandler cbHandler = new CallbackHandler(handler);
4006 NetworkCapabilities nc = request.networkCapabilities;
4007 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09004008 }
4009
4010 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004011 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004012 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004013 * <p>This method will attempt to find the best network that matches the passed
4014 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4015 * criteria. The platform will evaluate which network is the best at its own discretion.
4016 * Throughput, latency, cost per byte, policy, user preference and other considerations
4017 * may be factored in the decision of what is considered the best network.
4018 *
4019 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4020 * matching this request, while always attempting to match the request to a better network if
4021 * possible. If a better match is found, the platform will switch this request to the now-best
4022 * network and inform the app of the newly best network by invoking
4023 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4024 * will not try to maintain any other network than the best one currently matching the request:
4025 * a network not matching any network request may be disconnected at any time.
4026 *
4027 * <p>For example, an application could use this method to obtain a connected cellular network
4028 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4029 * radio to consume additional power. Or, an application could inform the system that it wants
4030 * a network supporting sending MMSes and have the system let it know about the currently best
4031 * MMS-supporting network through the provided {@link NetworkCallback}.
4032 *
4033 * <p>The status of the request can be followed by listening to the various callbacks described
4034 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4035 * used to direct traffic to the network (although accessing some networks may be subject to
4036 * holding specific permissions). Callers will learn about the specific characteristics of the
4037 * network through
4038 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4039 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4040 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4041 * matching the request at any given time; therefore when a better network matching the request
4042 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4043 * with the new network after which no further updates are given about the previously-best
4044 * network, unless it becomes the best again at some later time. All callbacks are invoked
4045 * in order on the same thread, which by default is a thread created by the framework running
4046 * in the app.
4047 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4048 * callbacks are invoked.
4049 *
4050 * <p>This{@link NetworkRequest} will live until released via
4051 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4052 * which point the system may let go of the network at any time.
4053 *
4054 * <p>A version of this method which takes a timeout is
4055 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4056 * wait for a limited amount of time for the network to become unavailable.
4057 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004058 * <p>It is presently unsupported to request a network with mutable
4059 * {@link NetworkCapabilities} such as
4060 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4061 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4062 * as these {@code NetworkCapabilities} represent states that a particular
4063 * network may never attain, and whether a network will attain these states
4064 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09004065 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004066 *
4067 * <p>This method requires the caller to hold either the
4068 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4069 * or the ability to modify system settings as determined by
4070 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004071 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004072 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4073 * number of outstanding requests to 100 per app (identified by their UID), shared with
4074 * all variants of this method, of {@link #registerNetworkCallback} as well as
4075 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4076 * Requesting a network with this method will count toward this limit. If this limit is
4077 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4078 * make sure to unregister the callbacks with
4079 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4080 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004081 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004082 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4083 * the callback must not be shared - it uniquely specifies this request.
4084 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004085 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4086 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004087 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004088 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004089 public void requestNetwork(@NonNull NetworkRequest request,
4090 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004091 requestNetwork(request, networkCallback, getDefaultHandler());
4092 }
4093
4094 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004095 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004096 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004097 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4098 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004099 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004100 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004101 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4102 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004103 *
4104 * @param request {@link NetworkRequest} describing this request.
4105 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4106 * the callback must not be shared - it uniquely specifies this request.
4107 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004108 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004109 public void requestNetwork(@NonNull NetworkRequest request,
4110 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004111 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004112 NetworkCapabilities nc = request.networkCapabilities;
4113 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004114 }
4115
4116 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004117 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohen67e58a02017-03-01 12:47:28 -08004118 * by a timeout.
4119 *
4120 * This function behaves identically to the non-timed-out version
4121 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4122 * is not found within the given time (in milliseconds) the
4123 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4124 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4125 * not have to be released if timed-out (it is automatically released). Unregistering a
4126 * request that timed out is not an error.
4127 *
4128 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4129 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4130 * for that purpose. Calling this method will attempt to bring up the requested network.
4131 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004132 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004133 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4134 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08004135 *
4136 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004137 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4138 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004139 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4140 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4141 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08004142 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004143 public void requestNetwork(@NonNull NetworkRequest request,
4144 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004145 checkTimeout(timeoutMs);
markchien0fe11402020-03-18 21:16:15 +08004146 NetworkCapabilities nc = request.networkCapabilities;
4147 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4148 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004149 }
4150
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004151 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004152 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004153 * by a timeout.
4154 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004155 * This method behaves identically to
4156 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4157 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08004158 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004159 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004160 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4161 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004162 *
4163 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004164 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4165 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004166 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004167 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4168 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004169 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004170 public void requestNetwork(@NonNull NetworkRequest request,
4171 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004172 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004173 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004174 NetworkCapabilities nc = request.networkCapabilities;
4175 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004176 }
4177
4178 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004179 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004180 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004181 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08004182 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04004183 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4184 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004185 */
Erik Klinefb087f12014-11-19 12:12:24 +09004186 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004187
4188 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004189 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004190 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004191 * {@link android.content.Intent#getParcelableExtra(String)}.
4192 */
Erik Klinefb087f12014-11-19 12:12:24 +09004193 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004194
4195
4196 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004197 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004198 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08004199 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004200 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004201 * the request may outlive the calling application and get called back when a suitable
4202 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004203 * <p>
4204 * The operation is an Intent broadcast that goes to a broadcast receiver that
4205 * you registered with {@link Context#registerReceiver} or through the
4206 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4207 * <p>
4208 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09004209 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4210 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004211 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004212 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004213 * Intent to reserve the network or it will be released shortly after the Intent
4214 * is processed.
4215 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04004216 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004217 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004218 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004219 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08004220 * The request may be released normally by calling
4221 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004222 * <p>It is presently unsupported to request a network with either
4223 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4224 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4225 * as these {@code NetworkCapabilities} represent states that a particular
4226 * network may never attain, and whether a network will attain these states
4227 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09004228 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004229 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004230 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4231 * number of outstanding requests to 100 per app (identified by their UID), shared with
4232 * all variants of this method, of {@link #registerNetworkCallback} as well as
4233 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4234 * Requesting a network with this method will count toward this limit. If this limit is
4235 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4236 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4237 * or {@link #releaseNetworkRequest(PendingIntent)}.
4238 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004239 * <p>This method requires the caller to hold either the
4240 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4241 * or the ability to modify system settings as determined by
4242 * {@link android.provider.Settings.System#canWrite}.</p>
4243 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004244 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004245 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004246 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08004247 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004248 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4249 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004250 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004251 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004252 public void requestNetwork(@NonNull NetworkRequest request,
4253 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004254 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004255 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004256 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004257 mService.pendingRequestForNetwork(
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07004258 request.networkCapabilities, operation, mContext.getOpPackageName(),
4259 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004260 } catch (RemoteException e) {
4261 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004262 } catch (ServiceSpecificException e) {
4263 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004264 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004265 }
4266
4267 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004268 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4269 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004270 * This method has the same behavior as
4271 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004272 * releasing network resources and disconnecting.
4273 *
4274 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4275 * PendingIntent passed to
4276 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4277 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4278 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004279 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004280 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004281 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004282 try {
4283 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004284 } catch (RemoteException e) {
4285 throw e.rethrowFromSystemServer();
4286 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004287 }
4288
Hugo Benichiff4bf602017-05-09 15:19:01 +09004289 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004290 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004291 }
4292
4293 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004294 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004295 }
4296
4297 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004298 if (timeoutMs <= 0) {
4299 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4300 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004301 }
4302
4303 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004304 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004305 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004306 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4307 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004308 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004309 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4310 * number of outstanding requests to 100 per app (identified by their UID), shared with
4311 * all variants of this method, of {@link #requestNetwork} as well as
4312 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4313 * Requesting a network with this method will count toward this limit. If this limit is
4314 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4315 * make sure to unregister the callbacks with
4316 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4317 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004318 * @param request {@link NetworkRequest} describing this request.
4319 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4320 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004321 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004322 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004323 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004324 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004325 public void registerNetworkCallback(@NonNull NetworkRequest request,
4326 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004327 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4328 }
4329
4330 /**
4331 * Registers to receive notifications about all networks which satisfy the given
4332 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004333 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4334 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004335 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004336 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4337 * number of outstanding requests to 100 per app (identified by their UID), shared with
4338 * all variants of this method, of {@link #requestNetwork} as well as
4339 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4340 * Requesting a network with this method will count toward this limit. If this limit is
4341 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4342 * make sure to unregister the callbacks with
4343 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4344 *
4345 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004346 * @param request {@link NetworkRequest} describing this request.
4347 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4348 * networks change state.
4349 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004350 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004351 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004352 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004353 public void registerNetworkCallback(@NonNull NetworkRequest request,
4354 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004355 CallbackHandler cbHandler = new CallbackHandler(handler);
4356 NetworkCapabilities nc = request.networkCapabilities;
4357 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004358 }
4359
4360 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004361 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4362 * {@link NetworkRequest}.
4363 *
4364 * This function behaves identically to the version that takes a NetworkCallback, but instead
4365 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4366 * the request may outlive the calling application and get called back when a suitable
4367 * network is found.
4368 * <p>
4369 * The operation is an Intent broadcast that goes to a broadcast receiver that
4370 * you registered with {@link Context#registerReceiver} or through the
4371 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4372 * <p>
4373 * The operation Intent is delivered with two extras, a {@link Network} typed
4374 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4375 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4376 * the original requests parameters.
4377 * <p>
4378 * If there is already a request for this Intent registered (with the equality of
4379 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4380 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4381 * <p>
4382 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004383 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004384 *
4385 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4386 * number of outstanding requests to 100 per app (identified by their UID), shared with
4387 * all variants of this method, of {@link #requestNetwork} as well as
4388 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4389 * Requesting a network with this method will count toward this limit. If this limit is
4390 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4391 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4392 * or {@link #releaseNetworkRequest(PendingIntent)}.
4393 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004394 * @param request {@link NetworkRequest} describing this request.
4395 * @param operation Action to perform when the network is available (corresponds
4396 * to the {@link NetworkCallback#onAvailable} call. Typically
4397 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004398 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004399 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004400 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004401 public void registerNetworkCallback(@NonNull NetworkRequest request,
4402 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004403 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004404 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004405 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004406 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004407 request.networkCapabilities, operation, mContext.getOpPackageName(),
4408 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004409 } catch (RemoteException e) {
4410 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004411 } catch (ServiceSpecificException e) {
4412 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004413 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004414 }
4415
4416 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004417 * Registers to receive notifications about changes in the application's default network. This
4418 * may be a physical network or a virtual network, such as a VPN that applies to the
4419 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004420 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004421 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004422 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4423 * number of outstanding requests to 100 per app (identified by their UID), shared with
4424 * all variants of this method, of {@link #requestNetwork} as well as
4425 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4426 * Requesting a network with this method will count toward this limit. If this limit is
4427 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4428 * make sure to unregister the callbacks with
4429 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4430 *
Erik Klinee0aed632016-03-16 15:31:39 +09004431 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004432 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004433 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004434 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004435 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004436 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004437 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004438 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4439 }
4440
4441 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004442 * Registers to receive notifications about changes in the application's default network. This
4443 * may be a physical network or a virtual network, such as a VPN that applies to the
4444 * application. The callbacks will continue to be called until either the application exits or
4445 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4446 *
4447 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4448 * number of outstanding requests to 100 per app (identified by their UID), shared with
4449 * all variants of this method, of {@link #requestNetwork} as well as
4450 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4451 * Requesting a network with this method will count toward this limit. If this limit is
4452 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4453 * make sure to unregister the callbacks with
4454 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4455 *
4456 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4457 * application's default network changes.
4458 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4459 * @throws RuntimeException if the app already has too many callbacks registered.
4460 */
4461 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4462 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4463 @NonNull Handler handler) {
Lorenzo Colittib199b962021-03-12 22:48:07 +09004464 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4465 }
4466
4467 /**
4468 * Registers to receive notifications about changes in the default network for the specified
4469 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4470 * UID. The callbacks will continue to be called until either the application exits or
4471 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4472 *
4473 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4474 * number of outstanding requests to 100 per app (identified by their UID), shared with
4475 * all variants of this method, of {@link #requestNetwork} as well as
4476 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4477 * Requesting a network with this method will count toward this limit. If this limit is
4478 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4479 * make sure to unregister the callbacks with
4480 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4481 *
4482 * @param uid the UID for which to track default network changes.
4483 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4484 * UID's default network changes.
4485 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4486 * @throws RuntimeException if the app already has too many callbacks registered.
4487 * @hide
4488 */
Lorenzo Colitti3949d6e2021-03-22 18:23:21 +09004489 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittib199b962021-03-12 22:48:07 +09004490 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4491 @RequiresPermission(anyOf = {
4492 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4493 android.Manifest.permission.NETWORK_SETTINGS})
4494 public void registerDefaultNetworkCallbackAsUid(int uid,
4495 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004496 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colittib199b962021-03-12 22:48:07 +09004497 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004498 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4499 }
4500
4501 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004502 * Registers to receive notifications about changes in the system default network. The callbacks
4503 * will continue to be called until either the application exits or
4504 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004505 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004506 * This method should not be used to determine networking state seen by applications, because in
4507 * many cases, most or even all application traffic may not use the default network directly,
4508 * and traffic from different applications may go on different networks by default. As an
4509 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4510 * and not onto the system default network. Applications or system components desiring to do
4511 * determine network state as seen by applications should use other methods such as
4512 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4513 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004514 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4515 * number of outstanding requests to 100 per app (identified by their UID), shared with
4516 * all variants of this method, of {@link #requestNetwork} as well as
4517 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4518 * Requesting a network with this method will count toward this limit. If this limit is
4519 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4520 * make sure to unregister the callbacks with
4521 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4522 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004523 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4524 * system default network changes.
4525 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004526 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004527 *
4528 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004529 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004530 @SystemApi(client = MODULE_LIBRARIES)
4531 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4532 @RequiresPermission(anyOf = {
4533 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4534 android.Manifest.permission.NETWORK_SETTINGS})
4535 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004536 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004537 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004538 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004539 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004540 }
4541
4542 /**
junyulaibd622262021-03-15 11:48:48 +08004543 * Registers to receive notifications about the best matching network which satisfy the given
4544 * {@link NetworkRequest}. The callbacks will continue to be called until
4545 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4546 * called.
4547 *
4548 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4549 * number of outstanding requests to 100 per app (identified by their UID), shared with
4550 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4551 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4552 * Requesting a network with this method will count toward this limit. If this limit is
4553 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4554 * make sure to unregister the callbacks with
4555 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4556 *
4557 *
4558 * @param request {@link NetworkRequest} describing this request.
4559 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4560 * networks change state.
4561 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4562 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai6b0a6a22021-03-05 15:51:17 +08004563 */
junyulai6b0a6a22021-03-05 15:51:17 +08004564 @SuppressLint("ExecutorRegistration")
4565 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4566 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4567 final NetworkCapabilities nc = request.networkCapabilities;
4568 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai8cae3c72021-03-12 20:05:08 +08004569 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai6b0a6a22021-03-05 15:51:17 +08004570 }
4571
4572 /**
fenglu73169332015-04-21 17:12:05 -07004573 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4574 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4575 * network connection for updated bandwidth information. The caller will be notified via
4576 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004577 * method assumes that the caller has previously called
4578 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4579 * changes.
fenglu76564332015-03-20 11:29:56 -07004580 *
fenglu41808e82015-04-27 14:28:04 -07004581 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004582 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004583 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004584 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004585 try {
fenglu73169332015-04-21 17:12:05 -07004586 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004587 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004588 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004589 }
4590 }
4591
4592 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004593 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004594 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4595 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4596 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004597 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4598 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004599 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004600 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4601 * triggering it as soon as this call returns.
4602 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004603 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004604 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004605 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004606 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004607 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004608 final List<NetworkRequest> reqs = new ArrayList<>();
4609 // Find all requests associated to this callback and stop callback triggers immediately.
4610 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4611 synchronized (sCallbacks) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004612 if (networkCallback.networkRequest == null) {
4613 throw new IllegalArgumentException("NetworkCallback was not registered");
4614 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07004615 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4616 Log.d(TAG, "NetworkCallback was already unregistered");
4617 return;
4618 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004619 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4620 if (e.getValue() == networkCallback) {
4621 reqs.add(e.getKey());
4622 }
4623 }
4624 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4625 for (NetworkRequest r : reqs) {
4626 try {
4627 mService.releaseNetworkRequest(r);
4628 } catch (RemoteException e) {
4629 throw e.rethrowFromSystemServer();
4630 }
4631 // Only remove mapping if rpc was successful.
4632 sCallbacks.remove(r);
4633 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004634 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004635 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004636 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004637
4638 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004639 * Unregisters a callback previously registered via
4640 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4641 *
4642 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4643 * PendingIntent passed to
4644 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4645 * Cannot be null.
4646 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004647 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004648 releaseNetworkRequest(operation);
4649 }
4650
4651 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004652 * Informs the system whether it should switch to {@code network} regardless of whether it is
4653 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4654 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4655 * the system default network regardless of any other network that's currently connected. If
4656 * {@code always} is true, then the choice is remembered, so that the next time the user
4657 * connects to this network, the system will switch to it.
4658 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004659 * @param network The network to accept.
4660 * @param accept Whether to accept the network even if unvalidated.
4661 * @param always Whether to remember this choice in the future.
4662 *
4663 * @hide
4664 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004665 @SystemApi(client = MODULE_LIBRARIES)
4666 @RequiresPermission(anyOf = {
4667 android.Manifest.permission.NETWORK_SETTINGS,
4668 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4669 android.Manifest.permission.NETWORK_STACK,
4670 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4671 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004672 try {
4673 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004674 } catch (RemoteException e) {
4675 throw e.rethrowFromSystemServer();
4676 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004677 }
4678
4679 /**
lucaslin25a50472019-03-12 13:08:03 +08004680 * Informs the system whether it should consider the network as validated even if it only has
4681 * partial connectivity. If {@code accept} is true, then the network will be considered as
4682 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4683 * is remembered, so that the next time the user connects to this network, the system will
4684 * switch to it.
4685 *
4686 * @param network The network to accept.
4687 * @param accept Whether to consider the network as validated even if it has partial
4688 * connectivity.
4689 * @param always Whether to remember this choice in the future.
4690 *
4691 * @hide
4692 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004693 @SystemApi(client = MODULE_LIBRARIES)
4694 @RequiresPermission(anyOf = {
4695 android.Manifest.permission.NETWORK_SETTINGS,
4696 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4697 android.Manifest.permission.NETWORK_STACK,
4698 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4699 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4700 boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004701 try {
4702 mService.setAcceptPartialConnectivity(network, accept, always);
4703 } catch (RemoteException e) {
4704 throw e.rethrowFromSystemServer();
4705 }
4706 }
4707
4708 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004709 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4710 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4711 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4712 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4713 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004714 * @param network The network to accept.
4715 *
4716 * @hide
4717 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004718 @SystemApi(client = MODULE_LIBRARIES)
4719 @RequiresPermission(anyOf = {
4720 android.Manifest.permission.NETWORK_SETTINGS,
4721 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4722 android.Manifest.permission.NETWORK_STACK,
4723 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4724 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004725 try {
4726 mService.setAvoidUnvalidated(network);
4727 } catch (RemoteException e) {
4728 throw e.rethrowFromSystemServer();
4729 }
4730 }
4731
4732 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004733 * Requests that the system open the captive portal app on the specified network.
4734 *
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004735 * <p>This is to be used on networks where a captive portal was detected, as per
4736 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4737 *
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004738 * @param network The network to log into.
4739 *
4740 * @hide
4741 */
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004742 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4743 @RequiresPermission(anyOf = {
4744 android.Manifest.permission.NETWORK_SETTINGS,
4745 android.Manifest.permission.NETWORK_STACK,
4746 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4747 })
4748 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004749 try {
4750 mService.startCaptivePortalApp(network);
4751 } catch (RemoteException e) {
4752 throw e.rethrowFromSystemServer();
4753 }
4754 }
4755
4756 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004757 * Requests that the system open the captive portal app with the specified extras.
4758 *
4759 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4760 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004761 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004762 * @param appExtras Extras to include in the app start intent.
4763 * @hide
4764 */
4765 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004766 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004767 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004768 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004769 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004770 } catch (RemoteException e) {
4771 throw e.rethrowFromSystemServer();
4772 }
4773 }
4774
4775 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004776 * Determine whether the device is configured to avoid bad wifi.
4777 * @hide
4778 */
4779 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004780 @RequiresPermission(anyOf = {
4781 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4782 android.Manifest.permission.NETWORK_STACK})
4783 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004784 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004785 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004786 } catch (RemoteException e) {
4787 throw e.rethrowFromSystemServer();
4788 }
4789 }
4790
4791 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004792 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4793 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004794 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4795 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004796 *
4797 * An example of such an operation might be a time-sensitive foreground activity, such as a
4798 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4799 */
4800 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4801
4802 /**
4803 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4804 * a backup channel for traffic that is primarily going over another network.
4805 *
4806 * An example might be maintaining backup connections to peers or servers for the purpose of
4807 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4808 * on backup paths should be negligible compared to the traffic on the main path.
4809 */
4810 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4811
4812 /**
4813 * It is acceptable to use metered data to improve network latency and performance.
4814 */
4815 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4816
4817 /**
4818 * Return value to use for unmetered networks. On such networks we currently set all the flags
4819 * to true.
4820 * @hide
4821 */
4822 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4823 MULTIPATH_PREFERENCE_HANDOVER |
4824 MULTIPATH_PREFERENCE_RELIABILITY |
4825 MULTIPATH_PREFERENCE_PERFORMANCE;
4826
4827 /** @hide */
4828 @Retention(RetentionPolicy.SOURCE)
4829 @IntDef(flag = true, value = {
4830 MULTIPATH_PREFERENCE_HANDOVER,
4831 MULTIPATH_PREFERENCE_RELIABILITY,
4832 MULTIPATH_PREFERENCE_PERFORMANCE,
4833 })
4834 public @interface MultipathPreference {
4835 }
4836
4837 /**
4838 * Provides a hint to the calling application on whether it is desirable to use the
4839 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4840 * for multipath data transfer on this network when it is not the system default network.
4841 * Applications desiring to use multipath network protocols should call this method before
4842 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004843 *
4844 * @param network The network on which the application desires to use multipath data.
4845 * If {@code null}, this method will return the a preference that will generally
4846 * apply to metered networks.
4847 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4848 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004849 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004850 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004851 try {
4852 return mService.getMultipathPreference(network);
4853 } catch (RemoteException e) {
4854 throw e.rethrowFromSystemServer();
4855 }
4856 }
4857
4858 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004859 * Resets all connectivity manager settings back to factory defaults.
4860 * @hide
4861 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004862 @SystemApi(client = MODULE_LIBRARIES)
4863 @RequiresPermission(anyOf = {
4864 android.Manifest.permission.NETWORK_SETTINGS,
4865 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scottd3bb5082015-03-30 13:17:11 -07004866 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004867 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004868 mService.factoryReset();
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00004869 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004870 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004871 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004872 }
4873 }
4874
4875 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004876 * Binds the current process to {@code network}. All Sockets created in the future
4877 * (and not explicitly bound via a bound SocketFactory from
4878 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4879 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4880 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4881 * work and all host name resolutions will fail. This is by design so an application doesn't
4882 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4883 * To clear binding pass {@code null} for {@code network}. Using individually bound
4884 * Sockets created by Network.getSocketFactory().createSocket() and
4885 * performing network-specific host name resolutions via
4886 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004887 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004888 *
4889 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4890 * the current binding.
4891 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4892 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004893 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004894 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004895 // instantiated.
4896 return setProcessDefaultNetwork(network);
4897 }
4898
4899 /**
4900 * Binds the current process to {@code network}. All Sockets created in the future
4901 * (and not explicitly bound via a bound SocketFactory from
4902 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4903 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4904 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4905 * work and all host name resolutions will fail. This is by design so an application doesn't
4906 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4907 * To clear binding pass {@code null} for {@code network}. Using individually bound
4908 * Sockets created by Network.getSocketFactory().createSocket() and
4909 * performing network-specific host name resolutions via
4910 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4911 * {@code setProcessDefaultNetwork}.
4912 *
4913 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4914 * the current binding.
4915 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4916 * @deprecated This function can throw {@link IllegalStateException}. Use
4917 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4918 * is a direct replacement.
4919 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004920 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004921 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004922 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004923 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4924
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004925 if (netId != NETID_UNSET) {
4926 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004927 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004928
4929 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4930 return false;
4931 }
4932
4933 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004934 // Set HTTP proxy system properties to match network.
4935 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004936 try {
Remi NGUYEN VANa1860ff2021-02-03 10:18:20 +09004937 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004938 } catch (SecurityException e) {
4939 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4940 Log.e(TAG, "Can't set proxy properties", e);
4941 }
Paul Jensen99c36662014-08-27 12:38:45 -04004942 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN33e3abb2021-03-18 23:27:19 +09004943 InetAddressCompat.clearDnsCache();
Paul Jensen99c36662014-08-27 12:38:45 -04004944 // Must flush socket pool as idle sockets will be bound to previous network and may
4945 // cause subsequent fetches to be performed on old network.
4946 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004947 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004948
4949 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004950 }
4951
4952 /**
4953 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004954 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004955 *
4956 * @return {@code Network} to which this process is bound, or {@code null}.
4957 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004958 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004959 public Network getBoundNetworkForProcess() {
4960 // Forcing callers to call thru non-static function ensures ConnectivityManager
4961 // instantiated.
4962 return getProcessDefaultNetwork();
4963 }
4964
4965 /**
4966 * Returns the {@link Network} currently bound to this process via
4967 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4968 *
4969 * @return {@code Network} to which this process is bound, or {@code null}.
4970 * @deprecated Using this function can lead to other functions throwing
4971 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4972 * {@code getBoundNetworkForProcess} is a direct replacement.
4973 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004974 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004975 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004976 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004977 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004978 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004979 return new Network(netId);
4980 }
4981
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004982 private void unsupportedStartingFrom(int version) {
4983 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004984 // The getApplicationInfo() call we make below is not supported in system context. Let
4985 // the call through here, and rely on the fact that ConnectivityService will refuse to
4986 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004987 return;
4988 }
4989
4990 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4991 throw new UnsupportedOperationException(
4992 "This method is not supported in target SDK version " + version + " and above");
4993 }
4994 }
4995
4996 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4997 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004998 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004999 // remove these exemptions. Note that this check is not secure, and apps can still access these
5000 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5001 // so is unsupported and may break in the future. http://b/22728205
5002 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07005003 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09005004 }
5005
Paul Jensene98c6e02014-05-29 10:12:39 -04005006 /**
5007 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04005008 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04005009 *
5010 * @param network The {@link Network} to bind host resolutions from the current process to, or
5011 * {@code null} to clear the current binding.
5012 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5013 * @hide
5014 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5015 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07005016 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00005017 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04005018 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04005019 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09005020 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04005021 }
Felipe Lemed16384b2016-01-22 09:44:57 -08005022
5023 /**
5024 * Device is not restricting metered network activity while application is running on
5025 * background.
5026 */
5027 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5028
5029 /**
5030 * Device is restricting metered network activity while application is running on background,
5031 * but application is allowed to bypass it.
5032 * <p>
5033 * In this state, application should take action to mitigate metered network access.
5034 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5035 */
5036 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5037
5038 /**
5039 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08005040 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08005041 * In this state, application should not try to use the network while running on background,
5042 * because it would be denied.
5043 */
5044 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5045
Felipe Leme6a5b7692016-01-27 14:46:39 -08005046 /**
5047 * A change in the background metered network activity restriction has occurred.
5048 * <p>
5049 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5050 * applies to them.
5051 * <p>
5052 * This is only sent to registered receivers, not manifest receivers.
5053 */
5054 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5055 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5056 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5057
Felipe Leme1b42ef92016-01-25 11:48:04 -08005058 /** @hide */
5059 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08005060 @IntDef(flag = false, value = {
5061 RESTRICT_BACKGROUND_STATUS_DISABLED,
5062 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5063 RESTRICT_BACKGROUND_STATUS_ENABLED,
5064 })
Felipe Lemed16384b2016-01-22 09:44:57 -08005065 public @interface RestrictBackgroundStatus {
5066 }
5067
Felipe Lemed16384b2016-01-22 09:44:57 -08005068 /**
5069 * Determines if the calling application is subject to metered network restrictions while
5070 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07005071 *
5072 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5073 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5074 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08005075 */
5076 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5077 try {
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09005078 return mService.getRestrictBackgroundStatusByCaller();
Felipe Lemed16384b2016-01-22 09:44:57 -08005079 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07005080 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08005081 }
5082 }
Ricky Waid53cf002018-01-23 04:09:45 +00005083
5084 /**
5085 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00005086 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5087 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00005088 *
5089 * @return Hash of network watchlist config file. Null if config does not exist.
5090 */
Chalard Jean42a9c292019-01-07 19:26:34 +09005091 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00005092 public byte[] getNetworkWatchlistConfigHash() {
5093 try {
5094 return mService.getNetworkWatchlistConfigHash();
5095 } catch (RemoteException e) {
5096 Log.e(TAG, "Unable to get watchlist config hash");
5097 throw e.rethrowFromSystemServer();
5098 }
5099 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005100
5101 /**
5102 * Returns the {@code uid} of the owner of a network connection.
5103 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08005104 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5105 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005106 * @param local The local {@link InetSocketAddress} of a connection.
5107 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005108 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08005109 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5110 * android.os.Process#INVALID_UID} if the connection is not found.
5111 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5112 * user.
5113 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005114 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08005115 public int getConnectionOwnerUid(
5116 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005117 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5118 try {
5119 return mService.getConnectionOwnerUid(connectionInfo);
5120 } catch (RemoteException e) {
5121 throw e.rethrowFromSystemServer();
5122 }
5123 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09005124
5125 private void printStackTrace() {
5126 if (DEBUG) {
5127 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5128 final StringBuffer sb = new StringBuffer();
5129 for (int i = 3; i < callStack.length; i++) {
5130 final String stackTrace = callStack[i].toString();
5131 if (stackTrace == null || stackTrace.contains("android.os")) {
5132 break;
5133 }
5134 sb.append(" [").append(stackTrace).append("]");
5135 }
5136 Log.d(TAG, "StackLog:" + sb.toString());
5137 }
5138 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005139
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09005140 /** @hide */
5141 public TestNetworkManager startOrGetTestNetworkManager() {
5142 final IBinder tnBinder;
5143 try {
5144 tnBinder = mService.startOrGetTestNetworkService();
5145 } catch (RemoteException e) {
5146 throw e.rethrowFromSystemServer();
5147 }
5148
5149 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5150 }
5151
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09005152 /** @hide */
5153 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5154 return new ConnectivityDiagnosticsManager(mContext, mService);
5155 }
5156
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005157 /**
5158 * Simulates a Data Stall for the specified Network.
5159 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09005160 * <p>This method should only be used for tests.
5161 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005162 * <p>The caller must be the owner of the specified Network.
5163 *
5164 * @param detectionMethod The detection method used to identify the Data Stall.
5165 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
5166 * @param network The Network for which a Data Stall is being simluated.
5167 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5168 * @throws SecurityException if the caller is not the owner of the given network.
5169 * @hide
5170 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09005171 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005172 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5173 android.Manifest.permission.NETWORK_STACK})
5174 public void simulateDataStall(int detectionMethod, long timestampMillis,
5175 @NonNull Network network, @NonNull PersistableBundle extras) {
5176 try {
5177 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5178 } catch (RemoteException e) {
5179 e.rethrowFromSystemServer();
5180 }
5181 }
James Mattisdcea9fb2020-10-28 21:48:54 -07005182
Daniel Bright60f02ed2020-06-15 16:10:01 -07005183 @NonNull
5184 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5185
5186 /**
5187 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5188 * receive available QoS events related to the {@link Network} and local ip + port
5189 * specified within socketInfo.
5190 * <p/>
5191 * The same {@link QosCallback} must be unregistered before being registered a second time,
5192 * otherwise {@link QosCallbackRegistrationException} is thrown.
5193 * <p/>
5194 * This API does not, in itself, require any permission if called with a network that is not
5195 * restricted. However, the underlying implementation currently only supports the IMS network,
5196 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5197 * useful, because they'd never be called back on networks that they would have access to.
5198 *
5199 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5200 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5201 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5202 * @throws RuntimeException if the app already has too many callbacks registered.
5203 *
5204 * Exceptions after the time of registration is passed through
5205 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5206 *
5207 * @param socketInfo the socket information used to match QoS events
Daniel Bright60f02ed2020-06-15 16:10:01 -07005208 * @param executor The executor on which the callback will be invoked. The provided
5209 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Brightb953a3e2021-03-10 11:51:50 -08005210 * callbacks cannot be guaranteed.onQosCallbackRegistered
5211 * @param callback receives qos events that satisfy socketInfo
Daniel Bright60f02ed2020-06-15 16:10:01 -07005212 *
5213 * @hide
5214 */
5215 @SystemApi
5216 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Brightb953a3e2021-03-10 11:51:50 -08005217 @CallbackExecutor @NonNull final Executor executor,
5218 @NonNull final QosCallback callback) {
Daniel Bright60f02ed2020-06-15 16:10:01 -07005219 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005220 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Brightb953a3e2021-03-10 11:51:50 -08005221 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005222
5223 try {
5224 synchronized (mQosCallbackConnections) {
5225 if (getQosCallbackConnection(callback) == null) {
5226 final QosCallbackConnection connection =
5227 new QosCallbackConnection(this, callback, executor);
5228 mQosCallbackConnections.add(connection);
5229 mService.registerQosSocketCallback(socketInfo, connection);
5230 } else {
5231 Log.e(TAG, "registerQosCallback: Callback already registered");
5232 throw new QosCallbackRegistrationException();
5233 }
5234 }
5235 } catch (final RemoteException e) {
5236 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5237
5238 // The same unregister method method is called for consistency even though nothing
5239 // will be sent to the ConnectivityService since the callback was never successfully
5240 // registered.
5241 unregisterQosCallback(callback);
5242 e.rethrowFromSystemServer();
5243 } catch (final ServiceSpecificException e) {
5244 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5245 unregisterQosCallback(callback);
5246 throw convertServiceException(e);
5247 }
5248 }
5249
5250 /**
5251 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5252 * events once unregistered and can be registered a second time.
5253 * <p/>
5254 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5255 *
5256 * @param callback the callback being unregistered
5257 *
5258 * @hide
5259 */
5260 @SystemApi
5261 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5262 Objects.requireNonNull(callback, "The callback must be non-null");
5263 try {
5264 synchronized (mQosCallbackConnections) {
5265 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5266 if (connection != null) {
5267 connection.stopReceivingMessages();
5268 mService.unregisterQosCallback(connection);
5269 mQosCallbackConnections.remove(connection);
5270 } else {
5271 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5272 }
5273 }
5274 } catch (final RemoteException e) {
5275 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5276 e.rethrowFromSystemServer();
5277 }
5278 }
5279
5280 /**
5281 * Gets the connection related to the callback.
5282 *
5283 * @param callback the callback to look up
5284 * @return the related connection
5285 */
5286 @Nullable
5287 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5288 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5289 // Checking by reference here is intentional
5290 if (connection.getCallback() == callback) {
5291 return connection;
5292 }
5293 }
5294 return null;
5295 }
Junyu Lai23568a42021-01-19 11:10:56 +00005296
5297 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08005298 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Lai23568a42021-01-19 11:10:56 +00005299 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5300 * be used to request that the system provide a network without causing the network to be
5301 * in the foreground.
5302 *
5303 * <p>This method will attempt to find the best network that matches the passed
5304 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5305 * criteria. The platform will evaluate which network is the best at its own discretion.
5306 * Throughput, latency, cost per byte, policy, user preference and other considerations
5307 * may be factored in the decision of what is considered the best network.
5308 *
5309 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5310 * matching this request, while always attempting to match the request to a better network if
5311 * possible. If a better match is found, the platform will switch this request to the now-best
5312 * network and inform the app of the newly best network by invoking
5313 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5314 * will not try to maintain any other network than the best one currently matching the request:
5315 * a network not matching any network request may be disconnected at any time.
5316 *
5317 * <p>For example, an application could use this method to obtain a connected cellular network
5318 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5319 * radio to consume additional power. Or, an application could inform the system that it wants
5320 * a network supporting sending MMSes and have the system let it know about the currently best
5321 * MMS-supporting network through the provided {@link NetworkCallback}.
5322 *
5323 * <p>The status of the request can be followed by listening to the various callbacks described
5324 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5325 * used to direct traffic to the network (although accessing some networks may be subject to
5326 * holding specific permissions). Callers will learn about the specific characteristics of the
5327 * network through
5328 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5329 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5330 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5331 * matching the request at any given time; therefore when a better network matching the request
5332 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5333 * with the new network after which no further updates are given about the previously-best
5334 * network, unless it becomes the best again at some later time. All callbacks are invoked
5335 * in order on the same thread, which by default is a thread created by the framework running
5336 * in the app.
5337 *
5338 * <p>This{@link NetworkRequest} will live until released via
5339 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5340 * which point the system may let go of the network at any time.
5341 *
5342 * <p>It is presently unsupported to request a network with mutable
5343 * {@link NetworkCapabilities} such as
5344 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5345 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5346 * as these {@code NetworkCapabilities} represent states that a particular
5347 * network may never attain, and whether a network will attain these states
5348 * is unknown prior to bringing up the network so the framework does not
5349 * know how to go about satisfying a request with these capabilities.
5350 *
5351 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5352 * number of outstanding requests to 100 per app (identified by their UID), shared with
5353 * all variants of this method, of {@link #registerNetworkCallback} as well as
5354 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5355 * Requesting a network with this method will count toward this limit. If this limit is
5356 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5357 * make sure to unregister the callbacks with
5358 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5359 *
5360 * @param request {@link NetworkRequest} describing this request.
5361 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5362 * If null, the callback is invoked on the default internal Handler.
5363 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5364 * the callback must not be shared - it uniquely specifies this request.
5365 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5366 * @throws SecurityException if missing the appropriate permissions.
5367 * @throws RuntimeException if the app already has too many callbacks registered.
5368 *
5369 * @hide
5370 */
5371 @SystemApi(client = MODULE_LIBRARIES)
5372 @SuppressLint("ExecutorRegistration")
5373 @RequiresPermission(anyOf = {
5374 android.Manifest.permission.NETWORK_SETTINGS,
5375 android.Manifest.permission.NETWORK_STACK,
5376 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5377 })
5378 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaif4bc12f2021-03-09 20:49:48 +08005379 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Lai23568a42021-01-19 11:10:56 +00005380 final NetworkCapabilities nc = request.networkCapabilities;
5381 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaif4bc12f2021-03-09 20:49:48 +08005382 TYPE_NONE, new CallbackHandler(handler));
Junyu Lai23568a42021-01-19 11:10:56 +00005383 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005384
5385 /**
James Mattis6e6fabf2021-01-10 14:24:24 -08005386 * Used by automotive devices to set the network preferences used to direct traffic at an
5387 * application level as per the given OemNetworkPreferences. An example use-case would be an
5388 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5389 * vehicle via a particular network.
5390 *
5391 * Calling this will overwrite the existing preference.
5392 *
5393 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5394 * @param executor the executor on which listener will be invoked.
5395 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5396 * communicate completion of setOemNetworkPreference(). This will only be
5397 * called once upon successful completion of setOemNetworkPreference().
5398 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5399 * @throws SecurityException if missing the appropriate permissions.
5400 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005401 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005402 */
James Mattis7a253542021-01-26 16:23:52 -08005403 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005404 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005405 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005406 @Nullable @CallbackExecutor final Executor executor,
Chalard Jeancc9ad152021-03-03 16:37:13 +09005407 @Nullable final Runnable listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08005408 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5409 if (null != listener) {
5410 Objects.requireNonNull(executor, "Executor must be non-null");
5411 }
Chalard Jeancc9ad152021-03-03 16:37:13 +09005412 final IOnCompleteListener listenerInternal = listener == null ? null :
5413 new IOnCompleteListener.Stub() {
James Mattis6e6fabf2021-01-10 14:24:24 -08005414 @Override
5415 public void onComplete() {
Chalard Jeancc9ad152021-03-03 16:37:13 +09005416 executor.execute(listener::run);
James Mattis6e6fabf2021-01-10 14:24:24 -08005417 }
5418 };
5419
5420 try {
5421 mService.setOemNetworkPreference(preference, listenerInternal);
5422 } catch (RemoteException e) {
5423 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5424 throw e.rethrowFromSystemServer();
5425 }
5426 }
lucaslin1a6095c2021-03-12 00:46:33 +08005427
Chalard Jean03433052021-02-25 17:23:40 +09005428 /**
5429 * Request that a user profile is put by default on a network matching a given preference.
5430 *
5431 * See the documentation for the individual preferences for a description of the supported
5432 * behaviors.
5433 *
5434 * @param profile the profile concerned.
5435 * @param preference the preference for this profile.
5436 * @param executor an executor to execute the listener on. Optional if listener is null.
5437 * @param listener an optional listener to listen for completion of the operation.
5438 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5439 * @throws SecurityException if missing the appropriate permissions.
5440 * @hide
5441 */
Chalard Jeancc9ad152021-03-03 16:37:13 +09005442 // This function is for establishing per-profile default networking and can only be called by
5443 // the device policy manager, running as the system server. It would make no sense to call it
5444 // on a context for a user because it does not establish a setting on behalf of a user, rather
5445 // it establishes a setting for a user on behalf of the DPM.
5446 @SuppressLint({"UserHandle"})
5447 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09005448 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5449 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5450 @ProfileNetworkPreference final int preference,
5451 @Nullable @CallbackExecutor final Executor executor,
5452 @Nullable final Runnable listener) {
5453 if (null != listener) {
5454 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5455 }
5456 final IOnCompleteListener proxy;
5457 if (null == listener) {
5458 proxy = null;
5459 } else {
5460 proxy = new IOnCompleteListener.Stub() {
5461 @Override
5462 public void onComplete() {
5463 executor.execute(listener::run);
5464 }
5465 };
5466 }
5467 try {
5468 mService.setProfileNetworkPreference(profile, preference, proxy);
5469 } catch (RemoteException e) {
5470 throw e.rethrowFromSystemServer();
5471 }
5472 }
5473
lucaslin1a6095c2021-03-12 00:46:33 +08005474 // The first network ID of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005475 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin1a6095c2021-03-12 00:46:33 +08005476 // The network ID range of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005477 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin1a6095c2021-03-12 00:46:33 +08005478
5479 /**
5480 * Get the network ID range reserved for IPSec tunnel interfaces.
5481 *
5482 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5483 * @hide
5484 */
5485 @SystemApi(client = MODULE_LIBRARIES)
5486 @NonNull
5487 public static Range<Integer> getIpSecNetIdRange() {
5488 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5489 }
lucaslin50205af2021-03-12 16:11:27 +08005490
5491 /**
5492 * Get private DNS mode from settings.
5493 *
lucaslin73c98602021-03-17 14:53:35 +08005494 * @param context The Context to query the private DNS mode from settings.
lucaslin50205af2021-03-12 16:11:27 +08005495 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5496 *
5497 * @hide
5498 */
5499 @SystemApi(client = MODULE_LIBRARIES)
5500 @NonNull
5501 @PrivateDnsMode
lucaslinacd3ded2021-03-16 17:11:14 +08005502 public static String getPrivateDnsMode(@NonNull Context context) {
5503 final ContentResolver cr = context.getContentResolver();
lucaslin50205af2021-03-12 16:11:27 +08005504 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5505 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5506 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5507 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5508 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5509 return mode;
5510 }
paulhu28321462021-03-25 12:36:56 +08005511
5512 /**
5513 * Set private DNS mode to settings.
5514 *
5515 * @param context The {@link Context} to set the private DNS mode.
5516 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5517 *
5518 * @hide
5519 */
5520 @SystemApi(client = MODULE_LIBRARIES)
5521 public static void setPrivateDnsMode(@NonNull Context context,
5522 @NonNull @PrivateDnsMode String mode) {
5523 if (!(mode == PRIVATE_DNS_MODE_OFF
5524 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5525 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5526 throw new IllegalArgumentException("Invalid private dns mode");
5527 }
5528 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5529 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005530}