blob: 3939c7f4410281b3594dcc322e88162ebf2e0520 [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 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800453 * Invalid tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900454 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800455 * @hide
456 */
markchien1f523702019-12-25 19:40:32 +0800457 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800458
459 /**
460 * Wifi tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900461 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800462 * @hide
463 */
464 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900465 public static final int TETHERING_WIFI = 0;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800466
467 /**
468 * USB tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900469 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800470 * @hide
471 */
472 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900473 public static final int TETHERING_USB = 1;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800474
475 /**
476 * Bluetooth tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900477 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800478 * @hide
479 */
480 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900481 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800482
483 /**
Jimmy Chen87db1542019-07-15 18:03:23 +0800484 * Wifi P2p tethering type.
485 * Wifi P2p tethering is set through events automatically, and don't
486 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
487 * @hide
488 */
markchien1f523702019-12-25 19:40:32 +0800489 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chen87db1542019-07-15 18:03:23 +0800490
491 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800492 * Extra used for communicating with the TetherService. Includes the type of tethering to
493 * enable if any.
494 * @hide
495 */
markchien75721e42020-01-21 13:11:06 +0800496 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800497
498 /**
499 * Extra used for communicating with the TetherService. Includes the type of tethering for
500 * which to cancel provisioning.
501 * @hide
502 */
markchien75721e42020-01-21 13:11:06 +0800503 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800504
505 /**
506 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
507 * provisioning.
508 * @hide
509 */
markchien75721e42020-01-21 13:11:06 +0800510 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800511
512 /**
513 * Tells the TetherService to run a provision check now.
514 * @hide
515 */
markchien75721e42020-01-21 13:11:06 +0800516 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800517
518 /**
519 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
520 * which will receive provisioning results. Can be left empty.
521 * @hide
522 */
markchien75721e42020-01-21 13:11:06 +0800523 public static final String EXTRA_PROVISION_CALLBACK =
524 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800525
526 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800527 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700528 * @hide
529 */
paulhu62af6122020-01-13 16:46:45 +0800530 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700531 public static final int TYPE_NONE = -1;
532
533 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900534 * A Mobile data connection. Devices may support more than one.
535 *
536 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
537 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
538 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700539 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900540 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700541 public static final int TYPE_MOBILE = 0;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900542
Robert Greenwalt2034b912009-08-12 16:08:25 -0700543 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900544 * A WIFI data connection. Devices may support more than one.
545 *
546 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
547 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
548 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700549 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900550 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700551 public static final int TYPE_WIFI = 1;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900552
Robert Greenwalt2034b912009-08-12 16:08:25 -0700553 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800554 * An MMS-specific Mobile data connection. This network type may use the
555 * same network interface as {@link #TYPE_MOBILE} or it may use a different
556 * one. This is used by applications needing to talk to the carrier's
557 * Multimedia Messaging Service servers.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900558 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900559 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900560 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900561 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700563 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700564 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900565
Robert Greenwalt2034b912009-08-12 16:08:25 -0700566 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800567 * A SUPL-specific Mobile data connection. This network type may use the
568 * same network interface as {@link #TYPE_MOBILE} or it may use a different
569 * one. This is used by applications needing to talk to the carrier's
570 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900571 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900572 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900573 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900574 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700575 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700576 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700577 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900578
Robert Greenwalt2034b912009-08-12 16:08:25 -0700579 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800580 * A DUN-specific Mobile data connection. This network type may use the
581 * same network interface as {@link #TYPE_MOBILE} or it may use a different
582 * one. This is sometimes by the system when setting up an upstream connection
583 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900584 *
585 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
586 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
587 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700588 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900589 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700590 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900591
Robert Greenwalt2034b912009-08-12 16:08:25 -0700592 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800593 * A High Priority Mobile data connection. This network type uses the
594 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900595 * is different.
596 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900597 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
598 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
599 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700600 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700601 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700602 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900603
jshbfa81722010-03-11 15:04:43 -0800604 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900605 * A WiMAX data connection.
606 *
607 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
608 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
609 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800610 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900611 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800612 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800613
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800614 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900615 * A Bluetooth data connection.
616 *
617 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
618 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
619 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800620 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900621 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800622 public static final int TYPE_BLUETOOTH = 7;
623
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700624 /**
Chiachang Wang7d5f3782020-07-28 13:53:09 +0800625 * Fake data connection. This should not be used on shipping devices.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900626 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700627 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900628 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800629 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800630
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700631 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900632 * An Ethernet data connection.
633 *
634 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
635 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
636 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700637 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900638 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800639 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700640
Wink Savilleb7c92c72011-03-12 14:52:01 -0800641 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800642 * Over the air Administration.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900643 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800644 * {@hide}
645 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900646 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900647 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800648 public static final int TYPE_MOBILE_FOTA = 10;
649
650 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800651 * IP Multimedia Subsystem.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900652 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800653 * {@hide}
654 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900655 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100656 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800657 public static final int TYPE_MOBILE_IMS = 11;
658
659 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800660 * Carrier Branded Services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900661 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800662 * {@hide}
663 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900664 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900665 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800666 public static final int TYPE_MOBILE_CBS = 12;
667
repo syncf5de5572011-07-29 23:55:49 -0700668 /**
669 * A Wi-Fi p2p connection. Only requesting processes will have access to
670 * the peers connected.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900671 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700672 * {@hide}
673 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900674 @Deprecated
paulhu028732e2020-01-15 15:38:23 +0800675 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700676 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800677
Wink Saville70dbdcc2013-07-29 15:00:57 -0700678 /**
679 * The network to use for initially attaching to the network
Chalard Jean5acb7b72018-03-08 13:54:53 +0900680 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville70dbdcc2013-07-29 15:00:57 -0700681 * {@hide}
682 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900683 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100684 @UnsupportedAppUsage
Wink Saville70dbdcc2013-07-29 15:00:57 -0700685 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700686
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900687 /**
Robert Greenwalt9db5f3c2015-07-09 14:49:35 -0700688 * Emergency PDN connection for emergency services. This
689 * may include IMS and MMS in emergency situations.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900690 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram201d45f2014-06-26 11:03:44 -0700691 * {@hide}
692 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900693 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900694 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram201d45f2014-06-26 11:03:44 -0700695 public static final int TYPE_MOBILE_EMERGENCY = 15;
696
Hui Lu07f29332014-01-15 11:05:36 -0500697 /**
698 * The network that uses proxy to achieve connectivity.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900699 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu07f29332014-01-15 11:05:36 -0500700 * {@hide}
701 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900702 @Deprecated
Remi NGUYEN VANdaeafee2020-11-30 19:23:45 +0900703 @SystemApi
Hui Lu07f29332014-01-15 11:05:36 -0500704 public static final int TYPE_PROXY = 16;
Wink Saville70dbdcc2013-07-29 15:00:57 -0700705
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700706 /**
707 * A virtual network using one or more native bearers.
708 * It may or may not be providing security services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900709 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700710 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900711 @Deprecated
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700712 public static final int TYPE_VPN = 17;
Hui Lu07f29332014-01-15 11:05:36 -0500713
Benedict Wong80156022018-11-14 17:40:55 -0800714 /**
715 * A network that is exclusively meant to be used for testing
716 *
717 * @deprecated Use {@link NetworkCapabilities} instead.
718 * @hide
719 */
720 @Deprecated
721 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700722
Chalard Jean74fe1c72020-03-25 01:24:04 +0900723 /**
724 * @deprecated Use {@link NetworkCapabilities} instead.
725 * @hide
726 */
727 @Deprecated
728 @Retention(RetentionPolicy.SOURCE)
729 @IntDef(prefix = { "TYPE_" }, value = {
730 TYPE_NONE,
731 TYPE_MOBILE,
732 TYPE_WIFI,
733 TYPE_MOBILE_MMS,
734 TYPE_MOBILE_SUPL,
735 TYPE_MOBILE_DUN,
736 TYPE_MOBILE_HIPRI,
737 TYPE_WIMAX,
738 TYPE_BLUETOOTH,
739 TYPE_DUMMY,
740 TYPE_ETHERNET,
741 TYPE_MOBILE_FOTA,
742 TYPE_MOBILE_IMS,
743 TYPE_MOBILE_CBS,
744 TYPE_WIFI_P2P,
745 TYPE_MOBILE_IA,
746 TYPE_MOBILE_EMERGENCY,
747 TYPE_PROXY,
748 TYPE_VPN,
749 TYPE_TEST
750 })
751 public @interface LegacyNetworkType {}
752
Chalard Jean1f42df12019-11-21 14:48:00 +0900753 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
754 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
755 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
756 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
757 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
758
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700759 /** {@hide} */
Benedict Wong80156022018-11-14 17:40:55 -0800760 public static final int MAX_RADIO_TYPE = TYPE_TEST;
761
762 /** {@hide} */
763 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800764
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900765 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
766
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800767 /**
768 * If you want to set the default network preference,you can directly
769 * change the networkAttributes array in framework's config.xml.
770 *
771 * @deprecated Since we support so many more networks now, the single
772 * network default network preference can't really express
Robert Greenwalt26744a52013-02-15 10:56:35 -0800773 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800774 * networkAttributes in config.xml. You can determine
Robert Greenwalt1ee3d2c2012-12-07 09:56:50 -0800775 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800776 * from an App.
777 */
778 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800779 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
780
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700781 /**
Robert Greenwalta1402df2014-03-19 17:56:12 -0700782 * @hide
783 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900784 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltc34f83b2014-06-08 16:42:59 -0700785
Paul Jensen0478ace2014-07-11 12:28:19 -0400786 /**
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900787 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
788 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean73d9db72018-06-04 16:52:49 +0900789 * registered from those that were already unregistered.
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900790 * @hide
791 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900792 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900793 new NetworkRequest.Builder().clearCapabilities().build();
794
795 /**
Paul Jensen0478ace2014-07-11 12:28:19 -0400796 * A NetID indicating no Network is selected.
797 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
798 * @hide
799 */
800 public static final int NETID_UNSET = 0;
801
Erik Kline1ecdd962017-10-30 15:29:44 +0900802 /**
803 * Private DNS Mode values.
804 *
805 * The "private_dns_mode" global setting stores a String value which is
806 * expected to be one of the following.
807 */
808
809 /**
810 * @hide
811 */
lucaslin50205af2021-03-12 16:11:27 +0800812 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900813 public static final String PRIVATE_DNS_MODE_OFF = "off";
814 /**
815 * @hide
816 */
lucaslin50205af2021-03-12 16:11:27 +0800817 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900818 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
819 /**
820 * @hide
821 */
lucaslin50205af2021-03-12 16:11:27 +0800822 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900823 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin50205af2021-03-12 16:11:27 +0800824
825 /** @hide */
826 @Retention(RetentionPolicy.SOURCE)
827 @StringDef(value = {
828 PRIVATE_DNS_MODE_OFF,
829 PRIVATE_DNS_MODE_OPPORTUNISTIC,
830 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
831 })
832 public @interface PrivateDnsMode {}
Erik Kline1ecdd962017-10-30 15:29:44 +0900833
Sudheer Shanka457dfd52021-03-23 08:12:28 +0000834 /**
835 * Flag to indicate that an app is not subject to any restrictions that could result in its
836 * network access blocked.
837 *
838 * @hide
839 */
840 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
841 public static final int BLOCKED_REASON_NONE = 0;
842
843 /**
844 * Flag to indicate that an app is subject to Battery saver restrictions that would
845 * result in its network access being blocked.
846 *
847 * @hide
848 */
849 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
850 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
851
852 /**
853 * Flag to indicate that an app is subject to Doze 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_DOZE = 1 << 1;
860
861 /**
862 * Flag to indicate that an app is subject to App Standby 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_APP_STANDBY = 1 << 2;
869
870 /**
871 * Flag to indicate that an app is subject to Restricted mode 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_RESTRICTED_MODE = 1 << 3;
878
879 /**
Lorenzo Colitti60104f52021-03-18 00:54:57 +0900880 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
881 * is not currently connected.
882 *
883 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
884 *
885 * @hide
886 */
887 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
888 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
889
890 /**
Sudheer Shanka457dfd52021-03-23 08:12:28 +0000891 * Flag to indicate that an app is subject to Data saver restrictions that would
892 * result in its metered network access being blocked.
893 *
894 * @hide
895 */
896 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
897 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
898
899 /**
900 * Flag to indicate that an app is subject to user 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_USER_RESTRICTED = 1 << 17;
907
908 /**
909 * Flag to indicate that an app is subject to Device admin 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_ADMIN_DISABLED = 1 << 18;
916
917 /**
918 * @hide
919 */
920 @Retention(RetentionPolicy.SOURCE)
921 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
922 BLOCKED_REASON_NONE,
923 BLOCKED_REASON_BATTERY_SAVER,
924 BLOCKED_REASON_DOZE,
925 BLOCKED_REASON_APP_STANDBY,
926 BLOCKED_REASON_RESTRICTED_MODE,
927 BLOCKED_METERED_REASON_DATA_SAVER,
928 BLOCKED_METERED_REASON_USER_RESTRICTED,
929 BLOCKED_METERED_REASON_ADMIN_DISABLED,
930 })
931 public @interface BlockedReason {}
932
Lorenzo Colitti60104f52021-03-18 00:54:57 +0900933 /**
934 * Set of blocked reasons that are only applicable on metered networks.
935 *
936 * @hide
937 */
938 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
939 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
940
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900941 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700942 private final IConnectivityManager mService;
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +0900943
Paul Jensen12131352014-12-10 15:12:18 -0500944 /**
945 * A kludge to facilitate static access where a Context pointer isn't available, like in the
946 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
947 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
948 * methods that take a Context argument.
949 */
950 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800951
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +0900952 private final Context mContext;
953
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +0000954 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800955
Robert Greenwalt26744a52013-02-15 10:56:35 -0800956 /**
957 * Tests if a given integer represents a valid network type.
958 * @param networkType the type to be tested
959 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen1c9f2e42015-05-06 10:42:25 -0400960 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
961 * validate a network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800962 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700963 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700964 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900965 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800966 }
967
Robert Greenwalt26744a52013-02-15 10:56:35 -0800968 /**
969 * Returns a non-localized string representing a given network type.
970 * ONLY used for debugging output.
971 * @param type the type needing naming
972 * @return a String for the given type, or a string version of the type ("87")
973 * if no name is known.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900974 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800975 * {@hide}
976 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900977 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000978 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700979 public static String getNetworkTypeName(int type) {
980 switch (type) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900981 case TYPE_NONE:
982 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700983 case TYPE_MOBILE:
984 return "MOBILE";
985 case TYPE_WIFI:
986 return "WIFI";
987 case TYPE_MOBILE_MMS:
988 return "MOBILE_MMS";
989 case TYPE_MOBILE_SUPL:
990 return "MOBILE_SUPL";
991 case TYPE_MOBILE_DUN:
992 return "MOBILE_DUN";
993 case TYPE_MOBILE_HIPRI:
994 return "MOBILE_HIPRI";
995 case TYPE_WIMAX:
996 return "WIMAX";
997 case TYPE_BLUETOOTH:
998 return "BLUETOOTH";
999 case TYPE_DUMMY:
1000 return "DUMMY";
1001 case TYPE_ETHERNET:
1002 return "ETHERNET";
1003 case TYPE_MOBILE_FOTA:
1004 return "MOBILE_FOTA";
1005 case TYPE_MOBILE_IMS:
1006 return "MOBILE_IMS";
1007 case TYPE_MOBILE_CBS:
1008 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -07001009 case TYPE_WIFI_P2P:
1010 return "WIFI_P2P";
Wink Saville70dbdcc2013-07-29 15:00:57 -07001011 case TYPE_MOBILE_IA:
1012 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -07001013 case TYPE_MOBILE_EMERGENCY:
1014 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -05001015 case TYPE_PROXY:
1016 return "PROXY";
Erik Klineb1ff7002014-11-19 17:23:41 +09001017 case TYPE_VPN:
1018 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -07001019 default:
1020 return Integer.toString(type);
1021 }
1022 }
1023
Robert Greenwalt26744a52013-02-15 10:56:35 -08001024 /**
Aaron Huangdfba5d12020-06-27 07:18:23 +08001025 * @hide
Aaron Huangdfba5d12020-06-27 07:18:23 +08001026 */
lucaslin8c121bf2021-03-17 14:16:01 +08001027 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huangdfba5d12020-06-27 07:18:23 +08001028 public void systemReady() {
1029 try {
1030 mService.systemReady();
1031 } catch (RemoteException e) {
1032 throw e.rethrowFromSystemServer();
1033 }
1034 }
1035
1036 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001037 * Checks if a given type uses the cellular data connection.
1038 * This should be replaced in the future by a network property.
1039 * @param networkType the type to check
1040 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09001041 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001042 * {@hide}
1043 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09001044 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001045 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001046 public static boolean isNetworkTypeMobile(int networkType) {
1047 switch (networkType) {
1048 case TYPE_MOBILE:
1049 case TYPE_MOBILE_MMS:
1050 case TYPE_MOBILE_SUPL:
1051 case TYPE_MOBILE_DUN:
1052 case TYPE_MOBILE_HIPRI:
1053 case TYPE_MOBILE_FOTA:
1054 case TYPE_MOBILE_IMS:
1055 case TYPE_MOBILE_CBS:
Wink Saville70dbdcc2013-07-29 15:00:57 -07001056 case TYPE_MOBILE_IA:
Ram201d45f2014-06-26 11:03:44 -07001057 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -07001058 return true;
1059 default:
1060 return false;
1061 }
1062 }
1063
Robert Greenwalt26744a52013-02-15 10:56:35 -08001064 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001065 * Checks if the given network type is backed by a Wi-Fi radio.
1066 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001067 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001068 * @hide
1069 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09001070 @Deprecated
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001071 public static boolean isNetworkTypeWifi(int networkType) {
1072 switch (networkType) {
1073 case TYPE_WIFI:
1074 case TYPE_WIFI_P2P:
1075 return true;
1076 default:
1077 return false;
1078 }
1079 }
1080
1081 /**
Chalard Jean03433052021-02-25 17:23:40 +09001082 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1083 * Specify that the traffic for this user should by follow the default rules.
1084 * @hide
1085 */
Chalard Jean560d4032021-03-17 14:33:24 +09001086 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09001087 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1088
1089 /**
1090 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1091 * Specify that the traffic for this user should by default go on a network with
1092 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1093 * if no such network is available.
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_ENTERPRISE = 1;
1098
1099 /** @hide */
1100 @Retention(RetentionPolicy.SOURCE)
1101 @IntDef(value = {
1102 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1103 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1104 })
1105 public @interface ProfileNetworkPreference {
1106 }
1107
1108 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001109 * Specifies the preferred network type. When the device has more
1110 * than one type available the preferred network type will be used.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001111 *
1112 * @param preference the network type to prefer over all others. It is
1113 * unspecified what happens to the old preferred network in the
1114 * overall ordering.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001115 * @deprecated Functionality has been removed as it no longer makes sense,
1116 * with many more than two networks - we'd need an array to express
1117 * preference. Instead we use dynamic network properties of
1118 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001119 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001120 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001121 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001122 }
1123
Robert Greenwalt26744a52013-02-15 10:56:35 -08001124 /**
1125 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001126 *
1127 * @return an integer representing the preferred network type
1128 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001129 * @deprecated Functionality has been removed as it no longer makes sense,
1130 * with many more than two networks - we'd need an array to express
1131 * preference. Instead we use dynamic network properties of
1132 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001133 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001134 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001135 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001136 public int getNetworkPreference() {
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001137 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001138 }
1139
Scott Mainf58b7d82011-10-06 19:02:28 -07001140 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001141 * Returns details about the currently active default data network. When
1142 * connected, this network is the default route for outgoing connections.
1143 * You should always check {@link NetworkInfo#isConnected()} before initiating
1144 * network traffic. This may return {@code null} when there is no default
1145 * network.
Chalard Jean7c85ba42018-03-29 17:45:24 +09001146 * Note that if the default network is a VPN, this method will return the
1147 * NetworkInfo for one of its underlying networks instead, or null if the
1148 * VPN agent did not specify any. Apps interested in learning about VPNs
1149 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001150 *
1151 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001152 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001153 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001154 */
junyulai5c2f6262018-12-13 12:47:51 +08001155 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001156 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001157 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001158 public NetworkInfo getActiveNetworkInfo() {
1159 try {
1160 return mService.getActiveNetworkInfo();
1161 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001162 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001163 }
1164 }
1165
Robert Greenwalt26744a52013-02-15 10:56:35 -08001166 /**
Paul Jensenc2569432015-02-13 14:18:39 -05001167 * Returns a {@link Network} object corresponding to the currently active
1168 * default data network. In the event that the current active default data
1169 * network disconnects, the returned {@code Network} object will no longer
1170 * be usable. This will return {@code null} when there is no default
1171 * network.
1172 *
1173 * @return a {@link Network} object for the current default network or
1174 * {@code null} if no default network is currently active
Paul Jensenc2569432015-02-13 14:18:39 -05001175 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001176 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001177 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001178 public Network getActiveNetwork() {
1179 try {
1180 return mService.getActiveNetwork();
1181 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001182 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001183 }
1184 }
1185
1186 /**
Robin Leeda4d2e22016-03-24 12:07:00 +00001187 * Returns a {@link Network} object corresponding to the currently active
1188 * default data network for a specific UID. In the event that the default data
1189 * network disconnects, the returned {@code Network} object will no longer
1190 * be usable. This will return {@code null} when there is no default
1191 * network for the UID.
Robin Leeda4d2e22016-03-24 12:07:00 +00001192 *
1193 * @return a {@link Network} object for the current default network for the
1194 * given UID or {@code null} if no default network is currently active
lifrb22da4e2021-03-11 20:11:09 +08001195 * TODO: b/183465229 Cleanup getActiveNetworkForUid once b/165835257 is fixed
Robin Leeda4d2e22016-03-24 12:07:00 +00001196 */
paulhuec0a9632019-08-12 16:25:11 +08001197 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001198 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001199 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001200 return getActiveNetworkForUid(uid, false);
1201 }
1202
1203 /** {@hide} */
1204 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001205 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001206 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001207 } catch (RemoteException e) {
1208 throw e.rethrowFromSystemServer();
1209 }
1210 }
1211
1212 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001213 * Adds or removes a requirement for given UID ranges to use the VPN.
1214 *
1215 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1216 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1217 * otherwise have permission to bypass the VPN (e.g., because they have the
1218 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1219 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1220 * set to {@code false}, a previously-added restriction is removed.
1221 * <p>
1222 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1223 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1224 * remove a previously-added range, the exact range must be removed as is.
1225 * <p>
1226 * The changes are applied asynchronously and may not have been applied by the time the method
1227 * returns. Apps will be notified about any changes that apply to them via
1228 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1229 * effect.
1230 * <p>
1231 * This method should be called only by the VPN code.
1232 *
1233 * @param ranges the UID ranges to restrict
1234 * @param requireVpn whether the specified UID ranges must use a VPN
1235 *
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001236 * @hide
1237 */
1238 @RequiresPermission(anyOf = {
1239 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001240 android.Manifest.permission.NETWORK_STACK,
1241 android.Manifest.permission.NETWORK_SETTINGS})
1242 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001243 public void setRequireVpnForUids(boolean requireVpn,
1244 @NonNull Collection<Range<Integer>> ranges) {
1245 Objects.requireNonNull(ranges);
1246 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1247 // This method is not necessarily expected to be used outside the system server, so
1248 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1249 // stack process, or by tests.
1250 UidRange[] rangesArray = new UidRange[ranges.size()];
1251 int index = 0;
1252 for (Range<Integer> range : ranges) {
1253 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1254 }
1255 try {
1256 mService.setRequireVpnForUids(requireVpn, rangesArray);
1257 } catch (RemoteException e) {
1258 throw e.rethrowFromSystemServer();
1259 }
1260 }
1261
1262 /**
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001263 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1264 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1265 * but is still supported for backwards compatibility.
1266 * <p>
1267 * This type of VPN is assumed always to use the system default network, and must always declare
1268 * exactly one underlying network, which is the network that was the default when the VPN
1269 * connected.
1270 * <p>
1271 * Calling this method with {@code true} enables legacy behaviour, specifically:
1272 * <ul>
1273 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1274 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1275 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1276 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1277 * underlying the VPN.</li>
1278 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1279 * similarly replaced by the VPN network state.</li>
1280 * <li>Information on current network interfaces passed to NetworkStatsService will not
1281 * include any VPN interfaces.</li>
1282 * </ul>
1283 *
1284 * @param enabled whether legacy lockdown VPN is enabled or disabled
1285 *
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001286 * @hide
1287 */
1288 @RequiresPermission(anyOf = {
1289 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001290 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001291 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin5140e482021-03-22 11:51:27 +08001292 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001293 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1294 try {
1295 mService.setLegacyLockdownVpnEnabled(enabled);
1296 } catch (RemoteException e) {
1297 throw e.rethrowFromSystemServer();
1298 }
1299 }
1300
1301 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001302 * Returns details about the currently active default data network
1303 * for a given uid. This is for internal use only to avoid spying
1304 * other apps.
1305 *
1306 * @return a {@link NetworkInfo} object for the current default network
1307 * for the given uid or {@code null} if no default network is
1308 * available for the specified uid.
1309 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001310 * {@hide}
1311 */
paulhuec0a9632019-08-12 16:25:11 +08001312 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001313 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001314 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001315 return getActiveNetworkInfoForUid(uid, false);
1316 }
1317
1318 /** {@hide} */
1319 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001320 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001321 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001322 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001323 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001324 }
1325 }
1326
Robert Greenwalt26744a52013-02-15 10:56:35 -08001327 /**
1328 * Returns connection status information about a particular
1329 * network type.
1330 *
1331 * @param networkType integer specifying which networkType in
1332 * which you're interested.
1333 * @return a {@link NetworkInfo} object for the requested
1334 * network type or {@code null} if the type is not
Chalard Jean7c85ba42018-03-29 17:45:24 +09001335 * supported by the device. If {@code networkType} is
1336 * TYPE_VPN and a VPN is active for the calling app,
1337 * then this method will try to return one of the
1338 * underlying networks for the VPN or null if the
1339 * VPN agent didn't specify any.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001340 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001341 * @deprecated This method does not support multiple connected networks
1342 * of the same type. Use {@link #getAllNetworks} and
1343 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001344 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001345 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001346 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001347 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001348 public NetworkInfo getNetworkInfo(int networkType) {
1349 try {
1350 return mService.getNetworkInfo(networkType);
1351 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001352 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001353 }
1354 }
1355
Robert Greenwalt26744a52013-02-15 10:56:35 -08001356 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001357 * Returns connection status information about a particular
1358 * Network.
1359 *
1360 * @param network {@link Network} specifying which network
1361 * in which you're interested.
1362 * @return a {@link NetworkInfo} object for the requested
1363 * network or {@code null} if the {@code Network}
1364 * is not valid.
junyulai5c2f6262018-12-13 12:47:51 +08001365 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001366 */
junyulai5c2f6262018-12-13 12:47:51 +08001367 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001368 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001369 @Nullable
1370 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001371 return getNetworkInfoForUid(network, Process.myUid(), false);
1372 }
1373
1374 /** {@hide} */
1375 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001376 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001377 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001378 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001379 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001380 }
1381 }
1382
1383 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001384 * Returns connection status information about all network
1385 * types supported by the device.
1386 *
1387 * @return an array of {@link NetworkInfo} objects. Check each
1388 * {@link NetworkInfo#getType} for which type each applies.
1389 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001390 * @deprecated This method does not support multiple connected networks
1391 * of the same type. Use {@link #getAllNetworks} and
1392 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001393 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001394 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001395 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001396 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001397 public NetworkInfo[] getAllNetworkInfo() {
1398 try {
1399 return mService.getAllNetworkInfo();
1400 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001401 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001402 }
1403 }
1404
Robert Greenwalt26744a52013-02-15 10:56:35 -08001405 /**
junyulai57840802021-03-03 12:09:05 +08001406 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1407 * connected.
1408 * @hide
1409 */
1410 @SystemApi(client = MODULE_LIBRARIES)
1411 @RequiresPermission(anyOf = {
1412 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1413 android.Manifest.permission.NETWORK_STACK,
1414 android.Manifest.permission.NETWORK_SETTINGS})
1415 @NonNull
1416 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1417 try {
1418 return mService.getAllNetworkStateSnapshot();
1419 } catch (RemoteException e) {
1420 throw e.rethrowFromSystemServer();
1421 }
1422 }
1423
1424 /**
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001425 * Returns the {@link Network} object currently serving a given type, or
1426 * null if the given type is not connected.
1427 *
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001428 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04001429 * @deprecated This method does not support multiple connected networks
1430 * of the same type. Use {@link #getAllNetworks} and
1431 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001432 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001433 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001434 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001435 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001436 public Network getNetworkForType(int networkType) {
1437 try {
1438 return mService.getNetworkForType(networkType);
1439 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001440 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001441 }
1442 }
1443
1444 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001445 * Returns an array of all {@link Network} currently tracked by the
1446 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001447 *
1448 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001449 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001450 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001451 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001452 public Network[] getAllNetworks() {
1453 try {
1454 return mService.getAllNetworks();
1455 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001456 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001457 }
1458 }
1459
1460 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001461 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001462 * the Networks that applications run by the given user will use by default.
1463 * @hide
1464 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001465 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001466 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1467 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001468 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001469 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001470 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001471 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001472 }
1473 }
1474
1475 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001476 * Returns the IP information for the current default network.
1477 *
1478 * @return a {@link LinkProperties} object describing the IP info
1479 * for the current default network, or {@code null} if there
1480 * is no current default network.
1481 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001482 * {@hide}
Chalard Jeancc47b522019-01-11 16:47:53 +09001483 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1484 * value of {@link #getActiveNetwork()} instead. In particular,
1485 * this method will return non-null LinkProperties even if the
1486 * app is blocked by policy from using this network.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001487 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001488 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-01-11 16:47:53 +09001489 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001490 public LinkProperties getActiveLinkProperties() {
1491 try {
1492 return mService.getActiveLinkProperties();
1493 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001494 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001495 }
1496 }
1497
Robert Greenwalt26744a52013-02-15 10:56:35 -08001498 /**
1499 * Returns the IP information for a given network type.
1500 *
1501 * @param networkType the network type of interest.
1502 * @return a {@link LinkProperties} object describing the IP info
1503 * for the given networkType, or {@code null} if there is
1504 * no current default network.
1505 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001506 * {@hide}
Paul Jensena8e6dc62015-03-18 12:23:02 -04001507 * @deprecated This method does not support multiple connected networks
1508 * of the same type. Use {@link #getAllNetworks},
1509 * {@link #getNetworkInfo(android.net.Network)}, and
1510 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001511 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001512 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001513 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001514 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001515 public LinkProperties getLinkProperties(int networkType) {
1516 try {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001517 return mService.getLinkPropertiesForType(networkType);
1518 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001519 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001520 }
1521 }
1522
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001523 /**
1524 * Get the {@link LinkProperties} for the given {@link Network}. This
1525 * will return {@code null} if the network is unknown.
1526 *
1527 * @param network The {@link Network} object identifying the network in question.
1528 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001529 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001530 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001531 @Nullable
1532 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001533 try {
1534 return mService.getLinkProperties(network);
1535 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001536 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001537 }
1538 }
1539
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001540 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001541 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001542 * will return {@code null} if the network is unknown.
1543 *
Roshan Pius7992afd2020-12-22 15:10:42 -08001544 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1545 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1546 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1547 * this location sensitive information (subject to app's location permissions) will be
1548 * noted by system. To include any location sensitive data in {@link TransportInfo},
1549 * use a {@link NetworkCallback} with
1550 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1551 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001552 * @param network The {@link Network} object identifying the network in question.
Roshan Pius7992afd2020-12-22 15:10:42 -08001553 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001554 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001555 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001556 @Nullable
1557 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001558 try {
Roshan Piusc97d8062020-12-17 14:53:09 -08001559 return mService.getNetworkCapabilities(
1560 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001561 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001562 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001563 }
1564 }
1565
Robert Greenwalt26744a52013-02-15 10:56:35 -08001566 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001567 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001568 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1569 * portal is present.
1570 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1571 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1572 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001573 * The system network validation may be using different strategies to detect captive portals,
1574 * so this method does not necessarily return a URL used by the system. It only returns a URL
1575 * that may be relevant for other components trying to detect captive portals.
paulhuec0a9632019-08-12 16:25:11 +08001576 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001577 * @hide
paulhuec0a9632019-08-12 16:25:11 +08001578 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1579 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001580 */
paulhuec0a9632019-08-12 16:25:11 +08001581 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001582 @SystemApi
paulhuec0a9632019-08-12 16:25:11 +08001583 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001584 public String getCaptivePortalServerUrl() {
1585 try {
1586 return mService.getCaptivePortalServerUrl();
1587 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001588 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001589 }
1590 }
1591
1592 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001593 * Tells the underlying networking system that the caller wants to
1594 * begin using the named feature. The interpretation of {@code feature}
1595 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001596 *
1597 * <p>This method requires the caller to hold either the
1598 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1599 * or the ability to modify system settings as determined by
1600 * {@link android.provider.Settings.System#canWrite}.</p>
1601 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001602 * @param networkType specifies which network the request pertains to
1603 * @param feature the name of the feature to be used
1604 * @return an integer value representing the outcome of the request.
1605 * The interpretation of this value is specific to each networking
1606 * implementation+feature combination, except that the value {@code -1}
1607 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001608 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001609 * @deprecated Deprecated in favor of the cleaner
1610 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001611 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001612 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001613 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001614 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001615 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001616 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001617 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001618 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1619 if (netCap == null) {
1620 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1621 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001622 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001623 }
1624
1625 NetworkRequest request = null;
1626 synchronized (sLegacyRequests) {
1627 LegacyRequest l = sLegacyRequests.get(netCap);
1628 if (l != null) {
1629 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1630 renewRequestLocked(l);
1631 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001632 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001633 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001634 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001635 }
1636 }
1637
1638 request = requestNetworkForFeatureLocked(netCap);
1639 }
1640 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001641 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001642 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001643 } else {
1644 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001645 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001646 }
1647 }
1648
1649 /**
1650 * Tells the underlying networking system that the caller is finished
1651 * using the named feature. The interpretation of {@code feature}
1652 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001653 *
1654 * <p>This method requires the caller to hold either the
1655 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1656 * or the ability to modify system settings as determined by
1657 * {@link android.provider.Settings.System#canWrite}.</p>
1658 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001659 * @param networkType specifies which network the request pertains to
1660 * @param feature the name of the feature that is no longer needed
1661 * @return an integer value representing the outcome of the request.
1662 * The interpretation of this value is specific to each networking
1663 * implementation+feature combination, except that the value {@code -1}
1664 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001665 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001666 * @deprecated Deprecated in favor of the cleaner
1667 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001668 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001669 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001670 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001671 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001672 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001673 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001674 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001675 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1676 if (netCap == null) {
1677 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1678 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001679 return -1;
1680 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001681
Paul Jensen034dea32014-12-17 10:39:34 -05001682 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001683 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001684 }
1685 return 1;
1686 }
1687
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001688 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001689 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1690 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001691 switch (feature) {
1692 case "enableCBS":
1693 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1694 case "enableDUN":
1695 case "enableDUNAlways":
1696 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1697 case "enableFOTA":
1698 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1699 case "enableHIPRI":
1700 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1701 case "enableIMS":
1702 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1703 case "enableMMS":
1704 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1705 case "enableSUPL":
1706 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1707 default:
1708 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001709 }
Erik Kline50068e52017-01-26 18:08:28 +09001710 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1711 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001712 }
1713 return null;
1714 }
1715
Robert Greenwalt5a367872014-06-02 15:32:02 -07001716 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001717 if (netCap == null) return TYPE_NONE;
1718 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1719 return TYPE_MOBILE_CBS;
1720 }
1721 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1722 return TYPE_MOBILE_IMS;
1723 }
1724 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1725 return TYPE_MOBILE_FOTA;
1726 }
1727 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1728 return TYPE_MOBILE_DUN;
1729 }
1730 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1731 return TYPE_MOBILE_SUPL;
1732 }
1733 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1734 return TYPE_MOBILE_MMS;
1735 }
1736 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1737 return TYPE_MOBILE_HIPRI;
1738 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001739 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1740 return TYPE_WIFI_P2P;
1741 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001742 return TYPE_NONE;
1743 }
1744
1745 private static class LegacyRequest {
1746 NetworkCapabilities networkCapabilities;
1747 NetworkRequest networkRequest;
1748 int expireSequenceNumber;
1749 Network currentNetwork;
1750 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001751
1752 private void clearDnsBinding() {
1753 if (currentNetwork != null) {
1754 currentNetwork = null;
1755 setProcessDefaultNetworkForHostResolution(null);
1756 }
1757 }
1758
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001759 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001760 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001761 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001762 currentNetwork = network;
1763 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001764 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001765 }
1766 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001767 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001768 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001769 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1770 }
1771 };
1772 }
1773
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001774 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001775 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1776 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001777
1778 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1779 synchronized (sLegacyRequests) {
1780 LegacyRequest l = sLegacyRequests.get(netCap);
1781 if (l != null) return l.networkRequest;
1782 }
1783 return null;
1784 }
1785
1786 private void renewRequestLocked(LegacyRequest l) {
1787 l.expireSequenceNumber++;
1788 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1789 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1790 }
1791
1792 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1793 int ourSeqNum = -1;
1794 synchronized (sLegacyRequests) {
1795 LegacyRequest l = sLegacyRequests.get(netCap);
1796 if (l == null) return;
1797 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001798 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001799 }
1800 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1801 }
1802
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001803 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001804 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1805 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001806 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001807 try {
1808 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001809 } catch (RemoteException e) {
1810 throw e.rethrowFromSystemServer();
1811 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001812 LegacyRequest l = new LegacyRequest();
1813 l.networkCapabilities = netCap;
1814 l.delay = delay;
1815 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001816 l.networkRequest = sendRequestForNetwork(
1817 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001818 if (l.networkRequest == null) return null;
1819 sLegacyRequests.put(netCap, l);
1820 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1821 return l.networkRequest;
1822 }
1823
1824 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1825 if (delay >= 0) {
1826 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001827 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001828 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1829 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001830 }
1831 }
1832
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001833 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001834 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1835 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001836 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001837 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001838 }
Paul Jensen034dea32014-12-17 10:39:34 -05001839 if (l == null) return false;
1840 unregisterNetworkCallback(l.networkCallback);
1841 l.clearDnsBinding();
1842 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001843 }
1844
Erik Kline50068e52017-01-26 18:08:28 +09001845 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1846 static {
1847 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1848 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1849 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1850 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1851 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1852 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1853 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1854 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1855 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1856 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1857 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1858 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1859 }
1860
1861 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1862 static {
1863 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1864 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1865 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1866 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1867 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1868 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1869 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1870 }
1871
1872 /**
1873 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1874 * instance suitable for registering a request or callback. Throws an
1875 * IllegalArgumentException if no mapping from the legacy type to
1876 * NetworkCapabilities is known.
1877 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001878 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1879 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001880 * @hide
1881 */
1882 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1883 final NetworkCapabilities nc = new NetworkCapabilities();
1884
1885 // Map from type to transports.
1886 final int NOT_FOUND = -1;
1887 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001888 if (transport == NOT_FOUND) {
1889 throw new IllegalArgumentException("unknown legacy type: " + type);
1890 }
Erik Kline50068e52017-01-26 18:08:28 +09001891 nc.addTransportType(transport);
1892
1893 // Map from type to capabilities.
1894 nc.addCapability(sLegacyTypeToCapability.get(
1895 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1896 nc.maybeMarkCapabilitiesRestricted();
1897 return nc;
1898 }
1899
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001900 /** @hide */
1901 public static class PacketKeepaliveCallback {
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001902 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayevfc03a992019-11-15 19:12:49 +00001903 public PacketKeepaliveCallback() {
1904 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001905 /** The requested keepalive was successfully started. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001906 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001907 public void onStarted() {}
1908 /** The keepalive was successfully stopped. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001909 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001910 public void onStopped() {}
1911 /** An error occurred. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001912 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001913 public void onError(int error) {}
1914 }
1915
1916 /**
1917 * Allows applications to request that the system periodically send specific packets on their
1918 * behalf, using hardware offload to save battery power.
1919 *
1920 * To request that the system send keepalives, call one of the methods that return a
1921 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1922 * passing in a non-null callback. If the callback is successfully started, the callback's
1923 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1924 * specifying one of the {@code ERROR_*} constants in this class.
1925 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001926 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1927 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1928 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001929 *
junyulaia86defc2018-12-27 17:25:29 +08001930 * @deprecated Use {@link SocketKeepalive} instead.
1931 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001932 * @hide
1933 */
1934 public class PacketKeepalive {
1935
1936 private static final String TAG = "PacketKeepalive";
1937
1938 /** @hide */
1939 public static final int SUCCESS = 0;
1940
1941 /** @hide */
1942 public static final int NO_KEEPALIVE = -1;
1943
1944 /** @hide */
1945 public static final int BINDER_DIED = -10;
1946
1947 /** The specified {@code Network} is not connected. */
1948 public static final int ERROR_INVALID_NETWORK = -20;
1949 /** The specified IP addresses are invalid. For example, the specified source IP address is
1950 * not configured on the specified {@code Network}. */
1951 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1952 /** The requested port is invalid. */
1953 public static final int ERROR_INVALID_PORT = -22;
1954 /** The packet length is invalid (e.g., too long). */
1955 public static final int ERROR_INVALID_LENGTH = -23;
1956 /** The packet transmission interval is invalid (e.g., too short). */
1957 public static final int ERROR_INVALID_INTERVAL = -24;
1958
1959 /** The hardware does not support this request. */
1960 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001961 /** The hardware returned an error. */
1962 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001963
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001964 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001965 public static final int NATT_PORT = 4500;
1966
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001967 /** The minimum interval in seconds between keepalive packet transmissions */
1968 public static final int MIN_INTERVAL = 10;
1969
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001970 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001971 private final ISocketKeepaliveCallback mCallback;
1972 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001973
1974 private volatile Integer mSlot;
1975
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001976 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001977 public void stop() {
1978 try {
junyulai9f872232019-01-16 20:23:34 +08001979 mExecutor.execute(() -> {
1980 try {
1981 if (mSlot != null) {
1982 mService.stopKeepalive(mNetwork, mSlot);
1983 }
1984 } catch (RemoteException e) {
1985 Log.e(TAG, "Error stopping packet keepalive: ", e);
1986 throw e.rethrowFromSystemServer();
1987 }
1988 });
1989 } catch (RejectedExecutionException e) {
1990 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001991 }
1992 }
1993
1994 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001995 Objects.requireNonNull(network, "network cannot be null");
1996 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001997 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08001998 mExecutor = Executors.newSingleThreadExecutor();
1999 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002000 @Override
junyulai9f872232019-01-16 20:23:34 +08002001 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08002002 final long token = Binder.clearCallingIdentity();
2003 try {
2004 mExecutor.execute(() -> {
2005 mSlot = slot;
2006 callback.onStarted();
2007 });
2008 } finally {
2009 Binder.restoreCallingIdentity(token);
2010 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002011 }
junyulai9f872232019-01-16 20:23:34 +08002012
2013 @Override
2014 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08002015 final long token = Binder.clearCallingIdentity();
2016 try {
2017 mExecutor.execute(() -> {
2018 mSlot = null;
2019 callback.onStopped();
2020 });
2021 } finally {
2022 Binder.restoreCallingIdentity(token);
2023 }
junyulai9f872232019-01-16 20:23:34 +08002024 mExecutor.shutdown();
2025 }
2026
2027 @Override
2028 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08002029 final long token = Binder.clearCallingIdentity();
2030 try {
2031 mExecutor.execute(() -> {
2032 mSlot = null;
2033 callback.onError(error);
2034 });
2035 } finally {
2036 Binder.restoreCallingIdentity(token);
2037 }
junyulai9f872232019-01-16 20:23:34 +08002038 mExecutor.shutdown();
2039 }
2040
2041 @Override
2042 public void onDataReceived() {
2043 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2044 // this callback when data is received.
2045 }
2046 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002047 }
2048 }
2049
2050 /**
2051 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2052 *
junyulaia86defc2018-12-27 17:25:29 +08002053 * @deprecated Use {@link #createSocketKeepalive} instead.
2054 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002055 * @hide
2056 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002057 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002058 public PacketKeepalive startNattKeepalive(
2059 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2060 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2061 final PacketKeepalive k = new PacketKeepalive(network, callback);
2062 try {
junyulai9f872232019-01-16 20:23:34 +08002063 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002064 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2065 } catch (RemoteException e) {
2066 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08002067 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002068 }
2069 return k;
2070 }
2071
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002072 // Construct an invalid fd.
2073 private ParcelFileDescriptor createInvalidFd() {
2074 final int invalidFd = -1;
2075 return ParcelFileDescriptor.adoptFd(invalidFd);
2076 }
2077
The Android Open Source Project28527d22009-03-03 19:31:44 -08002078 /**
junyulaia86defc2018-12-27 17:25:29 +08002079 * Request that keepalives be started on a IPsec NAT-T socket.
2080 *
2081 * @param network The {@link Network} the socket is on.
2082 * @param socket The socket that needs to be kept alive.
2083 * @param source The source address of the {@link UdpEncapsulationSocket}.
2084 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2085 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2086 * must run callback sequentially, otherwise the order of callbacks cannot be
2087 * guaranteed.
2088 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2089 * changes. Must be extended by applications that use this API.
2090 *
junyulaic7ea1242019-01-08 20:04:33 +08002091 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2092 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08002093 **/
junyulai61143782019-03-04 22:45:36 +08002094 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08002095 @NonNull UdpEncapsulationSocket socket,
2096 @NonNull InetAddress source,
2097 @NonNull InetAddress destination,
2098 @NonNull @CallbackExecutor Executor executor,
2099 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002100 ParcelFileDescriptor dup;
2101 try {
junyulaic4fb2482019-03-27 11:00:37 +08002102 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2103 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08002104 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2105 } catch (IOException ignored) {
2106 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2107 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002108 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002109 }
2110 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2111 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08002112 }
2113
2114 /**
2115 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2116 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2117 *
2118 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08002119 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2120 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2121 * from that port.
junyulai48a59382019-01-15 11:32:44 +08002122 * @param source The source address of the {@link UdpEncapsulationSocket}.
2123 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2124 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2125 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2126 * must run callback sequentially, otherwise the order of callbacks cannot be
2127 * guaranteed.
2128 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2129 * changes. Must be extended by applications that use this API.
2130 *
junyulaic7ea1242019-01-08 20:04:33 +08002131 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2132 * given socket.
junyulai48a59382019-01-15 11:32:44 +08002133 * @hide
2134 */
2135 @SystemApi
2136 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002137 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2138 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08002139 @NonNull InetAddress source,
2140 @NonNull InetAddress destination,
2141 @NonNull @CallbackExecutor Executor executor,
2142 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002143 ParcelFileDescriptor dup;
2144 try {
junyulaic4fb2482019-03-27 11:00:37 +08002145 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08002146 dup = pfd.dup();
2147 } catch (IOException ignored) {
2148 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2149 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002150 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002151 }
2152 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VAN642d6ab2021-03-11 10:56:49 +00002153 -1 /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08002154 }
2155
2156 /**
junyulaic7ea1242019-01-08 20:04:33 +08002157 * Request that keepalives be started on a TCP socket.
2158 * The socket must be established.
2159 *
2160 * @param network The {@link Network} the socket is on.
2161 * @param socket The socket that needs to be kept alive.
2162 * @param executor The executor on which callback will be invoked. This implementation assumes
2163 * the provided {@link Executor} runs the callbacks in sequence with no
2164 * concurrency. Failing this, no guarantee of correctness can be made. It is
2165 * the responsibility of the caller to ensure the executor provides this
2166 * guarantee. A simple way of creating such an executor is with the standard
2167 * tool {@code Executors.newSingleThreadExecutor}.
2168 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2169 * changes. Must be extended by applications that use this API.
2170 *
2171 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2172 * given socket.
2173 * @hide
2174 */
2175 @SystemApi
2176 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002177 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002178 @NonNull Socket socket,
2179 @NonNull Executor executor,
2180 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002181 ParcelFileDescriptor dup;
2182 try {
2183 dup = ParcelFileDescriptor.fromSocket(socket);
2184 } catch (UncheckedIOException ignored) {
2185 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2186 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002187 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002188 }
2189 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002190 }
2191
2192 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002193 * Ensure that a network route exists to deliver traffic to the specified
2194 * host via the specified network interface. An attempt to add a route that
2195 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002196 *
2197 * <p>This method requires the caller to hold either the
2198 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2199 * or the ability to modify system settings as determined by
2200 * {@link android.provider.Settings.System#canWrite}.</p>
2201 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002202 * @param networkType the type of the network over which traffic to the specified
2203 * host is to be routed
2204 * @param hostAddress the IP address of the host to which the route is desired
2205 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002206 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002207 * @deprecated Deprecated in favor of the
2208 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2209 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002210 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002211 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002212 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002213 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002214 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002215 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002216 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002217 }
2218
2219 /**
2220 * Ensure that a network route exists to deliver traffic to the specified
2221 * host via the specified network interface. An attempt to add a route that
2222 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002223 *
2224 * <p>This method requires the caller to hold either the
2225 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2226 * or the ability to modify system settings as determined by
2227 * {@link android.provider.Settings.System#canWrite}.</p>
2228 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002229 * @param networkType the type of the network over which traffic to the specified
2230 * host is to be routed
2231 * @param hostAddress the IP address of the host to which the route is desired
2232 * @return {@code true} on success, {@code false} on failure
2233 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002234 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002235 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002236 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002237 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002238 @UnsupportedAppUsage
lucaslin5140e482021-03-22 11:51:27 +08002239 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002240 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002241 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242 try {
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002243 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2244 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002245 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002246 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002247 }
2248 }
2249
2250 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002251 * @return the context's attribution tag
2252 */
2253 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2254 private @Nullable String getAttributionTag() {
2255 return mContext.getAttributionTag();
2256 }
2257
2258 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002259 * Returns the value of the setting for background data usage. If false,
2260 * applications should not use the network if the application is not in the
2261 * foreground. Developers should respect this setting, and check the value
2262 * of this before performing any background data operations.
2263 * <p>
2264 * All applications that have background services that use the network
2265 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002266 * <p>
Scott Main50589142011-10-06 18:32:43 -07002267 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002268 * background data depends on several combined factors, and this method will
2269 * always return {@code true}. Instead, when background data is unavailable,
2270 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002271 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002272 * @return Whether background data usage is allowed.
2273 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002274 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002275 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002276 // assume that background data is allowed; final authority is
2277 // NetworkInfo which may be blocked.
2278 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002279 }
2280
2281 /**
2282 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002283 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002284 * @param allowBackgroundData Whether an application should use data while
2285 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002286 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002287 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2288 * @see #getBackgroundDataSetting()
2289 * @hide
2290 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002291 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002292 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002293 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002294 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002295 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002296
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002297 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002298 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002299 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002300 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002301 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002302 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002303 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002304 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2305 if (tm != null) {
2306 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2307 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2308 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2309 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2310 + " retVal=" + retVal);
2311 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002312 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002313 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002314 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002315 }
2316
The Android Open Source Project28527d22009-03-03 19:31:44 -08002317 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002318 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002319 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002320 */
2321 public interface OnNetworkActiveListener {
2322 /**
2323 * Called on the main thread of the process to report that the current data network
2324 * has become active, and it is now a good time to perform any pending network
2325 * operations. Note that this listener only tells you when the network becomes
2326 * active; if at any other time you want to know whether it is active (and thus okay
2327 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002328 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002329 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002330 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002331 }
2332
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002333 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002334 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002335
2336 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002337 * Start listening to reports when the system's default data network is active, meaning it is
2338 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2339 * to determine the current state of the system's default network after registering the
2340 * listener.
2341 * <p>
2342 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002343 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002344 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002345 *
2346 * @param l The listener to be told when the network is active.
2347 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002348 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002349 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2350 @Override
2351 public void onNetworkActive() throws RemoteException {
2352 l.onNetworkActive();
2353 }
2354 };
2355
2356 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002357 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002358 mNetworkActivityListeners.put(l, rl);
2359 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002360 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002361 }
2362 }
2363
2364 /**
2365 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002366 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002367 *
2368 * @param l Previously registered listener.
2369 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002370 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002371 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002372 if (rl == null) {
2373 throw new IllegalArgumentException("Listener was not registered.");
2374 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002375 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002376 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002377 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002378 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002379 }
2380 }
2381
2382 /**
2383 * Return whether the data network is currently active. An active network means that
2384 * it is currently in a high power state for performing data transmission. On some
2385 * types of networks, it may be expensive to move and stay in such a state, so it is
2386 * more power efficient to batch network traffic together when the radio is already in
2387 * this state. This method tells you whether right now is currently a good time to
2388 * initiate network traffic, as the network is already active.
2389 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002390 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002391 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002392 return mService.isDefaultNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002393 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002394 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002395 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002396 }
2397
2398 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002399 * {@hide}
2400 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002401 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002402 mContext = Objects.requireNonNull(context, "missing context");
2403 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002404 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002405 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002406 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002407
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002408 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002409 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002410 public static ConnectivityManager from(Context context) {
2411 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2412 }
2413
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002414 /** @hide */
2415 public NetworkRequest getDefaultRequest() {
2416 try {
2417 // This is not racy as the default request is final in ConnectivityService.
2418 return mService.getDefaultRequest();
2419 } catch (RemoteException e) {
2420 throw e.rethrowFromSystemServer();
2421 }
2422 }
2423
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002424 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002425 * Check if the package is a allowed to write settings. This also accounts that such an access
2426 * happened.
2427 *
2428 * @return {@code true} iff the package is allowed to write settings.
2429 */
2430 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2431 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2432 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2433 boolean throwException) {
2434 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2435 callingAttributionTag, throwException);
2436 }
2437
2438 /**
Paul Jensen12131352014-12-10 15:12:18 -05002439 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2440 * situations where a Context pointer is unavailable.
2441 * @hide
2442 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002443 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002444 static ConnectivityManager getInstanceOrNull() {
2445 return sInstance;
2446 }
2447
2448 /**
2449 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2450 * situations where a Context pointer is unavailable.
2451 * @hide
2452 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002453 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002454 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002455 private static ConnectivityManager getInstance() {
2456 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002457 throw new IllegalStateException("No ConnectivityManager yet constructed");
2458 }
Paul Jensen895c3942015-03-10 10:54:12 -04002459 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002460 }
2461
2462 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002463 * Get the set of tetherable, available interfaces. This list is limited by
2464 * device configuration and current interface existence.
2465 *
2466 * @return an array of 0 or more Strings of tetherable interface names.
2467 *
markchien75721e42020-01-21 13:11:06 +08002468 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002469 * {@hide}
2470 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002471 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002472 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002473 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002474 public String[] getTetherableIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002475 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002476 }
2477
2478 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002479 * Get the set of tethered interfaces.
2480 *
2481 * @return an array of 0 or more String of currently tethered interface names.
2482 *
markchien75721e42020-01-21 13:11:06 +08002483 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002484 * {@hide}
2485 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002486 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002487 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002488 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002489 public String[] getTetheredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002490 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002491 }
2492
2493 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002494 * Get the set of interface names which attempted to tether but
2495 * failed. Re-attempting to tether may cause them to reset to the Tethered
2496 * state. Alternatively, causing the interface to be destroyed and recreated
2497 * may cause them to reset to the available state.
2498 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2499 * information on the cause of the errors.
2500 *
2501 * @return an array of 0 or more String indicating the interface names
2502 * which failed to tether.
2503 *
markchien75721e42020-01-21 13:11:06 +08002504 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002505 * {@hide}
2506 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002507 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002508 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002509 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002510 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002511 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002512 }
2513
2514 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002515 * Get the set of tethered dhcp ranges.
2516 *
markchien9e046242020-02-06 19:23:26 +08002517 * @deprecated This method is not supported.
2518 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002519 * {@hide}
2520 */
paulhuec0a9632019-08-12 16:25:11 +08002521 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien75721e42020-01-21 13:11:06 +08002522 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002523 public String[] getTetheredDhcpRanges() {
markchien9e046242020-02-06 19:23:26 +08002524 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002525 }
2526
2527 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002528 * Attempt to tether the named interface. This will setup a dhcp server
2529 * on the interface, forward and NAT IP packets and forward DNS requests
2530 * to the best active upstream network interface. Note that if no upstream
2531 * IP network interface is available, dhcp will still run and traffic will be
2532 * allowed between the tethered devices and this device, though upstream net
2533 * access will of course fail until an upstream network interface becomes
2534 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002535 *
2536 * <p>This method requires the caller to hold either the
2537 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2538 * or the ability to modify system settings as determined by
2539 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002540 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002541 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2542 * and WifiStateMachine which need direct access. All other clients should use
2543 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2544 * logic.</p>
2545 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002546 * @param iface the interface name to tether.
2547 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002548 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002549 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002550 * {@hide}
2551 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002552 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien10ddd022020-01-20 19:31:56 +08002553 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002554 public int tether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002555 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002556 }
2557
2558 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002559 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002560 *
2561 * <p>This method requires the caller to hold either the
2562 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2563 * or the ability to modify system settings as determined by
2564 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002565 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002566 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2567 * and WifiStateMachine which need direct access. All other clients should use
2568 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2569 * logic.</p>
2570 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002571 * @param iface the interface name to untether.
2572 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2573 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002574 * {@hide}
2575 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002576 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002577 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002578 public int untether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002579 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002580 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002581
2582 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002583 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002584 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002585 * due to device configuration.
2586 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002587 * <p>If this app does not have permission to use this API, it will always
2588 * return false rather than throw an exception.</p>
2589 *
2590 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2591 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2592 *
2593 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2594 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2595 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002596 * @return a boolean - {@code true} indicating Tethering is supported.
2597 *
markchien75721e42020-01-21 13:11:06 +08002598 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002599 * {@hide}
2600 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002601 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002602 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2603 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002604 public boolean isTetheringSupported() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002605 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002606 }
2607
2608 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002609 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien10ddd022020-01-20 19:31:56 +08002610 *
2611 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002612 * @hide
2613 */
2614 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002615 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002616 public static abstract class OnStartTetheringCallback {
2617 /**
2618 * Called when tethering has been successfully started.
2619 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002620 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002621
2622 /**
2623 * Called when starting tethering failed.
2624 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002625 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002626 }
2627
2628 /**
2629 * Convenient overload for
2630 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2631 * handler to run on the current thread's {@link Looper}.
markchien10ddd022020-01-20 19:31:56 +08002632 *
2633 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002634 * @hide
2635 */
2636 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002637 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002638 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002639 public void startTethering(int type, boolean showProvisioningUi,
2640 final OnStartTetheringCallback callback) {
2641 startTethering(type, showProvisioningUi, callback, null);
2642 }
2643
2644 /**
2645 * Runs tether provisioning for the given type if needed and then starts tethering if
2646 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2647 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2648 * schedules tether provisioning re-checks if appropriate.
2649 *
2650 * @param type The type of tethering to start. Must be one of
2651 * {@link ConnectivityManager.TETHERING_WIFI},
2652 * {@link ConnectivityManager.TETHERING_USB}, or
2653 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2654 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2655 * is one. This should be true the first time this function is called and also any time
2656 * the user can see this UI. It gives users information from their carrier about the
2657 * check failing and how they can sign up for tethering if possible.
2658 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2659 * of the result of trying to tether.
2660 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien10ddd022020-01-20 19:31:56 +08002661 *
2662 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002663 * @hide
2664 */
2665 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002666 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002667 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002668 public void startTethering(int type, boolean showProvisioningUi,
2669 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002670 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002671
markchien10ddd022020-01-20 19:31:56 +08002672 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002673 @Override
markchien10ddd022020-01-20 19:31:56 +08002674 public void execute(Runnable command) {
2675 if (handler == null) {
2676 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002677 } else {
markchien10ddd022020-01-20 19:31:56 +08002678 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002679 }
2680 }
2681 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002682
markchien10ddd022020-01-20 19:31:56 +08002683 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2684 @Override
2685 public void onTetheringStarted() {
2686 callback.onTetheringStarted();
2687 }
2688
2689 @Override
markchien68b67842020-03-19 13:37:43 +08002690 public void onTetheringFailed(final int error) {
markchien10ddd022020-01-20 19:31:56 +08002691 callback.onTetheringFailed();
2692 }
2693 };
2694
2695 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien68b67842020-03-19 13:37:43 +08002696 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien10ddd022020-01-20 19:31:56 +08002697
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002698 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002699 }
2700
2701 /**
2702 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2703 * applicable.
2704 *
2705 * @param type The type of tethering to stop. Must be one of
2706 * {@link ConnectivityManager.TETHERING_WIFI},
2707 * {@link ConnectivityManager.TETHERING_USB}, or
2708 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien75721e42020-01-21 13:11:06 +08002709 *
2710 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002711 * @hide
2712 */
2713 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002714 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002715 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002716 public void stopTethering(int type) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002717 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002718 }
2719
2720 /**
markchiena005c992019-02-27 14:56:11 +08002721 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2722 * upstream status.
2723 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002724 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien75721e42020-01-21 13:11:06 +08002725 * @hide
markchiena005c992019-02-27 14:56:11 +08002726 */
2727 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002728 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002729 public abstract static class OnTetheringEventCallback {
2730
2731 /**
2732 * Called when tethering upstream changed. This can be called multiple times and can be
2733 * called any time.
2734 *
2735 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2736 * have any upstream.
2737 */
2738 public void onUpstreamChanged(@Nullable Network network) {}
2739 }
2740
markchien75721e42020-01-21 13:11:06 +08002741 @GuardedBy("mTetheringEventCallbacks")
2742 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2743 mTetheringEventCallbacks = new ArrayMap<>();
2744
markchiena005c992019-02-27 14:56:11 +08002745 /**
2746 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002747 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002748 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2749 * with a null argument. The same callback object cannot be registered twice.
2750 *
2751 * @param executor the executor on which callback will be invoked.
2752 * @param callback the callback to be called when tethering has change events.
markchien75721e42020-01-21 13:11:06 +08002753 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002754 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002755 * @hide
2756 */
2757 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002758 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002759 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2760 public void registerTetheringEventCallback(
2761 @NonNull @CallbackExecutor Executor executor,
2762 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002763 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchiena005c992019-02-27 14:56:11 +08002764
markchien75721e42020-01-21 13:11:06 +08002765 final TetheringEventCallback tetherCallback =
2766 new TetheringEventCallback() {
2767 @Override
2768 public void onUpstreamChanged(@Nullable Network network) {
2769 callback.onUpstreamChanged(network);
2770 }
2771 };
2772
2773 synchronized (mTetheringEventCallbacks) {
2774 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002775 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002776 }
markchiena005c992019-02-27 14:56:11 +08002777 }
2778
2779 /**
2780 * Remove tethering event callback previously registered with
2781 * {@link #registerTetheringEventCallback}.
2782 *
2783 * @param callback previously registered callback.
markchien75721e42020-01-21 13:11:06 +08002784 *
2785 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002786 * @hide
2787 */
2788 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002789 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002790 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2791 public void unregisterTetheringEventCallback(
2792 @NonNull final OnTetheringEventCallback callback) {
markchien75721e42020-01-21 13:11:06 +08002793 Objects.requireNonNull(callback, "The callback must be non-null");
2794 synchronized (mTetheringEventCallbacks) {
2795 final TetheringEventCallback tetherCallback =
2796 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002797 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002798 }
markchiena005c992019-02-27 14:56:11 +08002799 }
2800
2801
2802 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002803 * Get the list of regular expressions that define any tetherable
2804 * USB network interfaces. If USB tethering is not supported by the
2805 * device, this list should be empty.
2806 *
2807 * @return an array of 0 or more regular expression Strings defining
2808 * what interfaces are considered tetherable usb interfaces.
2809 *
markchien75721e42020-01-21 13:11:06 +08002810 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002811 * {@hide}
2812 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002813 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002814 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002815 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002816 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002817 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002818 }
2819
2820 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002821 * Get the list of regular expressions that define any tetherable
2822 * Wifi network interfaces. If Wifi tethering is not supported by the
2823 * device, this list should be empty.
2824 *
2825 * @return an array of 0 or more regular expression Strings defining
2826 * what interfaces are considered tetherable wifi interfaces.
2827 *
markchien75721e42020-01-21 13:11:06 +08002828 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002829 * {@hide}
2830 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002831 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002832 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002833 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002834 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002835 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002836 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002837
Danica Chang96567052010-08-11 14:54:43 -07002838 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002839 * Get the list of regular expressions that define any tetherable
2840 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2841 * device, this list should be empty.
2842 *
2843 * @return an array of 0 or more regular expression Strings defining
2844 * what interfaces are considered tetherable bluetooth interfaces.
2845 *
markchien75721e42020-01-21 13:11:06 +08002846 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2847 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002848 * {@hide}
2849 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002850 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002851 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002852 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002853 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002854 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002855 }
2856
Mike Lockwooded4a1742011-07-19 13:04:47 -07002857 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002858 * Attempt to both alter the mode of USB and Tethering of USB. A
2859 * utility method to deal with some of the complexity of USB - will
2860 * attempt to switch to Rndis and subsequently tether the resulting
2861 * interface on {@code true} or turn off tethering and switch off
2862 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002863 *
2864 * <p>This method requires the caller to hold either the
2865 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2866 * or the ability to modify system settings as determined by
2867 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002868 *
2869 * @param enable a boolean - {@code true} to enable tethering
2870 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002871 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002872 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002873 * {@hide}
2874 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002875 @UnsupportedAppUsage
markchien10ddd022020-01-20 19:31:56 +08002876 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002877 public int setUsbTethering(boolean enable) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002878 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002879 }
2880
markchien75721e42020-01-21 13:11:06 +08002881 /**
2882 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2883 * {@hide}
2884 */
markchien5bd499c2019-01-16 17:44:13 +08002885 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002886 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002887 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien75721e42020-01-21 13:11:06 +08002888 /**
2889 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2890 * {@hide}
2891 */
2892 @Deprecated
2893 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2894 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2895 /**
2896 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2897 * {@hide}
2898 */
2899 @Deprecated
2900 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2901 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2902 /**
2903 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2904 * {@hide}
2905 */
2906 @Deprecated
2907 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2908 /**
2909 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2910 * {@hide}
2911 */
2912 @Deprecated
2913 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2914 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2915 /**
markchien68b67842020-03-19 13:37:43 +08002916 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002917 * {@hide}
2918 */
2919 @Deprecated
markchien68b67842020-03-19 13:37:43 +08002920 public static final int TETHER_ERROR_MASTER_ERROR =
2921 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien75721e42020-01-21 13:11:06 +08002922 /**
2923 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2924 * {@hide}
2925 */
2926 @Deprecated
2927 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2928 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2929 /**
2930 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2931 * {@hide}
2932 */
2933 @Deprecated
2934 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2935 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2936 /**
markchien68b67842020-03-19 13:37:43 +08002937 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002938 * {@hide}
2939 */
2940 @Deprecated
2941 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002942 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002943 /**
markchien68b67842020-03-19 13:37:43 +08002944 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002945 * {@hide}
2946 */
2947 @Deprecated
2948 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002949 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002950 /**
2951 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2952 * {@hide}
2953 */
2954 @Deprecated
2955 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2956 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2957 /**
markchien68b67842020-03-19 13:37:43 +08002958 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien75721e42020-01-21 13:11:06 +08002959 * {@hide}
2960 */
markchien5bd499c2019-01-16 17:44:13 +08002961 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002962 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002963 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien75721e42020-01-21 13:11:06 +08002964 /**
2965 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2966 * {@hide}
2967 */
2968 @Deprecated
2969 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2970 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2971 /**
2972 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2973 * {@hide}
2974 */
markchien5bd499c2019-01-16 17:44:13 +08002975 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002976 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002977 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002978
2979 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002980 * Get a more detailed error code after a Tethering or Untethering
2981 * request asynchronously failed.
2982 *
2983 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002984 * @return error The error code of the last error tethering or untethering the named
2985 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002986 *
markchien75721e42020-01-21 13:11:06 +08002987 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002988 * {@hide}
2989 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002990 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002991 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien75721e42020-01-21 13:11:06 +08002992 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002993 public int getLastTetherError(String iface) {
markchien68b67842020-03-19 13:37:43 +08002994 int error = mTetheringManager.getLastTetherError(iface);
2995 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2996 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2997 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2998 // instead.
2999 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3000 }
3001 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003002 }
3003
markchiendd41c822019-03-06 16:25:00 +08003004 /** @hide */
3005 @Retention(RetentionPolicy.SOURCE)
3006 @IntDef(value = {
3007 TETHER_ERROR_NO_ERROR,
3008 TETHER_ERROR_PROVISION_FAILED,
3009 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3010 })
3011 public @interface EntitlementResultCode {
3012 }
3013
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003014 /**
markchiendd41c822019-03-06 16:25:00 +08003015 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08003016 * entitlement succeeded.
markchien75721e42020-01-21 13:11:06 +08003017 *
3018 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08003019 * @hide
3020 */
3021 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003022 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08003023 public interface OnTetheringEntitlementResultListener {
3024 /**
3025 * Called to notify entitlement result.
3026 *
3027 * @param resultCode an int value of entitlement result. It may be one of
3028 * {@link #TETHER_ERROR_NO_ERROR},
3029 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3030 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3031 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07003032 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08003033 }
3034
3035 /**
markchien5bd499c2019-01-16 17:44:13 +08003036 * Get the last value of the entitlement check on this downstream. If the cached value is
3037 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3038 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3039 * guaranteed that the UI-based entitlement check will complete in any specific time period
3040 * and may in fact never complete. Any successful entitlement check the platform performs for
3041 * any reason will update the cached value.
3042 *
3043 * @param type the downstream type of tethering. Must be one of
3044 * {@link #TETHERING_WIFI},
3045 * {@link #TETHERING_USB}, or
3046 * {@link #TETHERING_BLUETOOTH}.
3047 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08003048 * @param executor the executor on which callback will be invoked.
3049 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3050 * notify the caller of the result of entitlement check. The listener may be called zero
3051 * or one time.
markchien75721e42020-01-21 13:11:06 +08003052 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08003053 * {@hide}
3054 */
3055 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003056 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08003057 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08003058 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3059 @NonNull @CallbackExecutor Executor executor,
3060 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003061 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchiendd41c822019-03-06 16:25:00 +08003062 ResultReceiver wrappedListener = new ResultReceiver(null) {
3063 @Override
3064 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslin9cc04192021-03-04 09:38:21 +08003065 final long token = Binder.clearCallingIdentity();
3066 try {
3067 executor.execute(() -> {
3068 listener.onTetheringEntitlementResult(resultCode);
3069 });
3070 } finally {
3071 Binder.restoreCallingIdentity(token);
3072 }
markchiendd41c822019-03-06 16:25:00 +08003073 }
3074 };
3075
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00003076 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienb0bb7862019-12-16 20:15:20 +08003077 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08003078 }
3079
3080 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003081 * Report network connectivity status. This is currently used only
3082 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003083 * <p>This method requires the caller to hold the permission
3084 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003085 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003086 * @param networkType The type of network you want to report on
3087 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09003088 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003089 * {@hide}
3090 */
3091 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003092 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003093 try {
3094 mService.reportInetCondition(networkType, percentage);
3095 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003096 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003097 }
3098 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003099
3100 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003101 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07003102 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003103 * the framework to re-evaluate network connectivity and/or switch to another
3104 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003105 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003106 * @param network The {@link Network} the application was attempting to use
3107 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04003108 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3109 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003110 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003111 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09003112 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003113 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003114 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04003115 // One of these will be ignored because it matches system's current state.
3116 // The other will trigger the necessary reevaluation.
3117 mService.reportNetworkConnectivity(network, true);
3118 mService.reportNetworkConnectivity(network, false);
3119 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003120 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003121 }
3122 }
3123
3124 /**
3125 * Report to the framework whether a network has working connectivity.
3126 * This provides a hint to the system that a particular network is providing
3127 * working connectivity or not. In response the framework may re-evaluate
3128 * the network's connectivity and might take further action thereafter.
3129 *
3130 * @param network The {@link Network} the application was attempting to use
3131 * or {@code null} to indicate the current default network.
3132 * @param hasConnectivity {@code true} if the application was able to successfully access the
3133 * Internet using {@code network} or {@code false} if not.
3134 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003135 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003136 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003137 try {
3138 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003139 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003140 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003141 }
3142 }
3143
3144 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003145 * Set a network-independent global http proxy. This is not normally what you want
3146 * for typical HTTP proxies - they are general network dependent. However if you're
3147 * doing something unusual like general internal filtering this may be useful. On
3148 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003149 *
3150 * @param p A {@link ProxyInfo} object defining the new global
3151 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003152 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003153 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003154 @SystemApi(client = MODULE_LIBRARIES)
paulhuec0a9632019-08-12 16:25:11 +08003155 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003156 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003157 try {
3158 mService.setGlobalProxy(p);
3159 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003160 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003161 }
3162 }
3163
3164 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003165 * Retrieve any network-independent global HTTP proxy.
3166 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003167 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003168 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003169 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003170 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003171 @SystemApi(client = MODULE_LIBRARIES)
3172 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04003173 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003174 try {
3175 return mService.getGlobalProxy();
3176 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003177 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003178 }
3179 }
3180
3181 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003182 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3183 * network-specific HTTP proxy. If {@code network} is null, the
3184 * network-specific proxy returned is the proxy of the default active
3185 * network.
3186 *
3187 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3188 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3189 * or when {@code network} is {@code null},
3190 * the {@code ProxyInfo} for the default active network. Returns
3191 * {@code null} when no proxy applies or the caller doesn't have
3192 * permission to use {@code network}.
3193 * @hide
3194 */
3195 public ProxyInfo getProxyForNetwork(Network network) {
3196 try {
3197 return mService.getProxyForNetwork(network);
3198 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003199 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003200 }
3201 }
3202
3203 /**
Paul Jensen12131352014-12-10 15:12:18 -05003204 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3205 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003206 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003207 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003208 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003209 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003210 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003211 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003212 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003213 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003214 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003215 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003216
3217 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003218 * Returns true if the hardware supports the given network type
3219 * else it returns false. This doesn't indicate we have coverage
3220 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003221 * hardware supports it. For example a GSM phone without a SIM
3222 * should still return {@code true} for mobile data, but a wifi only
3223 * tablet would return {@code false}.
3224 *
3225 * @param networkType The network type we'd like to check
3226 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003227 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003228 * @hide
3229 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003230 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003231 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003232 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003233 public boolean isNetworkSupported(int networkType) {
3234 try {
3235 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003236 } catch (RemoteException e) {
3237 throw e.rethrowFromSystemServer();
3238 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003239 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003240
3241 /**
3242 * Returns if the currently active data network is metered. A network is
3243 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003244 * that connection due to monetary costs, data limitations or
3245 * battery/performance issues. You should check this before doing large
3246 * data transfers, and warn the user or delay the operation until another
3247 * network is available.
3248 *
3249 * @return {@code true} if large transfers should be avoided, otherwise
3250 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003251 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003252 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003253 public boolean isActiveNetworkMetered() {
3254 try {
3255 return mService.isActiveNetworkMetered();
3256 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003257 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003258 }
3259 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003260
Robert Greenwalt26744a52013-02-15 10:56:35 -08003261 /**
Sarah Chincab74db2020-11-25 12:15:14 -08003262 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003263 *
Sarah Chincab74db2020-11-25 12:15:14 -08003264 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003265 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003266 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003267 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003268 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003269 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003270 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003271 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003272 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003273 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003274 }
3275 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003276
3277 /**
3278 * Set the value for enabling/disabling airplane mode
3279 *
3280 * @param enable whether to enable airplane mode or not
3281 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003282 * @hide
3283 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003284 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003285 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003286 android.Manifest.permission.NETWORK_SETTINGS,
3287 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3288 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003289 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003290 public void setAirplaneMode(boolean enable) {
3291 try {
3292 mService.setAirplaneMode(enable);
3293 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003294 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003295 }
3296 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003297
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003298 /**
3299 * Registers the specified {@link NetworkProvider}.
3300 * Each listener must only be registered once. The listener can be unregistered with
3301 * {@link #unregisterNetworkProvider}.
3302 *
3303 * @param provider the provider to register
3304 * @return the ID of the provider. This ID must be used by the provider when registering
3305 * {@link android.net.NetworkAgent}s.
3306 * @hide
3307 */
3308 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003309 @RequiresPermission(anyOf = {
3310 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3311 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003312 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3313 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003314 throw new IllegalStateException("NetworkProviders can only be registered once");
3315 }
3316
3317 try {
3318 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3319 provider.getName());
3320 provider.setProviderId(providerId);
3321 } catch (RemoteException e) {
3322 throw e.rethrowFromSystemServer();
3323 }
3324 return provider.getProviderId();
3325 }
3326
3327 /**
3328 * Unregisters the specified NetworkProvider.
3329 *
3330 * @param provider the provider to unregister
3331 * @hide
3332 */
3333 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003334 @RequiresPermission(anyOf = {
3335 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3336 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003337 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3338 try {
3339 mService.unregisterNetworkProvider(provider.getMessenger());
3340 } catch (RemoteException e) {
3341 throw e.rethrowFromSystemServer();
3342 }
3343 provider.setProviderId(NetworkProvider.ID_NONE);
3344 }
3345
Chalard Jean1ef1d902021-01-05 08:40:09 +09003346 /**
3347 * Register or update a network offer with ConnectivityService.
3348 *
3349 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jeand7268cd2021-03-24 17:43:10 +09003350 * them to networking requests made by apps or the system. A callback identifies an offer
3351 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3352 * score and the capabilities of the network it might be able to bring up ; these act as
3353 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jean1ef1d902021-01-05 08:40:09 +09003354 * provider.
3355 *
3356 * The provider is under no obligation to be able to bring up the network it offers at any
3357 * given time. Instead, this mechanism is meant to limit requests received by providers
3358 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3359 * the quality of the network satisfying a given request to their own offer.
3360 *
3361 * An offer can be updated by calling this again with the same callback object. This is
3362 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3363 * provider with the changes caused by the changes in the offer.
3364 *
3365 * @param provider The provider making this offer.
3366 * @param score The prospective score of the network.
3367 * @param caps The prospective capabilities of the network.
3368 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003369 * @hide exposed via the NetworkProvider class.
Chalard Jean1ef1d902021-01-05 08:40:09 +09003370 */
3371 @RequiresPermission(anyOf = {
3372 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3373 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanb004da52021-03-22 22:44:02 +09003374 public void offerNetwork(@NonNull final int providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09003375 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3376 @NonNull final INetworkOfferCallback callback) {
3377 try {
Chalard Jeanb004da52021-03-22 22:44:02 +09003378 mService.offerNetwork(providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09003379 Objects.requireNonNull(score, "null score"),
3380 Objects.requireNonNull(caps, "null caps"),
3381 Objects.requireNonNull(callback, "null callback"));
3382 } catch (RemoteException e) {
3383 throw e.rethrowFromSystemServer();
3384 }
3385 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003386
Chalard Jean1ef1d902021-01-05 08:40:09 +09003387 /**
3388 * Withdraw a network offer made with {@link #offerNetwork}.
3389 *
3390 * @param callback The callback passed at registration time. This must be the same object
3391 * that was passed to {@link #offerNetwork}
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003392 * @hide exposed via the NetworkProvider class.
Chalard Jean1ef1d902021-01-05 08:40:09 +09003393 */
3394 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3395 try {
3396 mService.unofferNetwork(Objects.requireNonNull(callback));
3397 } catch (RemoteException e) {
3398 throw e.rethrowFromSystemServer();
3399 }
3400 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003401 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003402 @RequiresPermission(anyOf = {
3403 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3404 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003405 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3406 try {
3407 mService.declareNetworkRequestUnfulfillable(request);
3408 } catch (RemoteException e) {
3409 throw e.rethrowFromSystemServer();
3410 }
3411 }
3412
Paul Jensenc2569432015-02-13 14:18:39 -05003413 /**
3414 * @hide
3415 * Register a NetworkAgent with ConnectivityService.
Chalard Jean1aea87a2019-12-13 19:47:12 +09003416 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003417 */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003418 @RequiresPermission(anyOf = {
3419 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3420 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003421 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeandd753522020-12-21 18:36:52 +09003422 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3423 int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003424 try {
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003425 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003426 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003427 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003428 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003429 }
3430
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003431 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003432 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3433 * changes. Should be extended by applications wanting notifications.
3434 *
3435 * A {@code NetworkCallback} is registered by calling
3436 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3437 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003438 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003439 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3440 * A {@code NetworkCallback} should be registered at most once at any time.
3441 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003442 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003443 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003444 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003445 * No flags associated with this callback.
3446 * @hide
3447 */
3448 public static final int FLAG_NONE = 0;
3449 /**
3450 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3451 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3452 * <p>
3453 * These include:
3454 * <li> Some transport info instances (retrieved via
3455 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3456 * contain location sensitive information.
3457 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3458 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3459 * </p>
3460 * <p>
3461 * Note:
3462 * <li> Retrieving this location sensitive information (subject to app's location
3463 * permissions) will be noted by system. </li>
3464 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3465 * not include location sensitive info.
3466 * </p>
3467 */
3468 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3469
3470 /** @hide */
3471 @Retention(RetentionPolicy.SOURCE)
3472 @IntDef(flag = true, prefix = "FLAG_", value = {
3473 FLAG_NONE,
3474 FLAG_INCLUDE_LOCATION_INFO
3475 })
3476 public @interface Flag { }
3477
3478 /**
3479 * All the valid flags for error checking.
3480 */
3481 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3482
3483 public NetworkCallback() {
3484 this(FLAG_NONE);
3485 }
3486
3487 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003488 if ((flags & VALID_FLAGS) != flags) {
3489 throw new IllegalArgumentException("Invalid flags");
3490 }
Roshan Pius7992afd2020-12-22 15:10:42 -08003491 mFlags = flags;
3492 }
3493
3494 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003495 * Called when the framework connects to a new network to evaluate whether it satisfies this
3496 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3497 * callback. There is no guarantee that this new network will satisfy any requests, or that
3498 * the network will stay connected for longer than the time necessary to evaluate it.
3499 * <p>
3500 * Most applications <b>should not</b> act on this callback, and should instead use
3501 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3502 * the framework in properly evaluating the network &mdash; for example, an application that
3503 * can automatically log in to a captive portal without user intervention.
3504 *
3505 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003506 *
3507 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003508 */
paulhua9a6e2a2019-03-22 16:35:06 +08003509 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003510
3511 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003512 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003513 * This callback may be called more than once if the {@link Network} that is
3514 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003515 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003516 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003517 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3518 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003519 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003520 * @hide
3521 */
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003522 public final void onAvailable(@NonNull Network network,
paulhua9a6e2a2019-03-22 16:35:06 +08003523 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003524 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003525 // Internally only this method is called when a new network is available, and
3526 // it calls the callback in the same way and order that older versions used
3527 // to call so as not to change the behavior.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003528 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3529 onBlockedStatusChanged(network, blocked);
3530 }
3531
3532 /**
3533 * Legacy variant of onAvailable that takes a boolean blocked reason.
3534 *
3535 * This method has never been public API, but it's not final, so there may be apps that
3536 * implemented it and rely on it being called. Do our best not to break them.
3537 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3538 * this method is called. There does not seem to be a way to avoid this.
3539 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3540 *
3541 * @hide
3542 */
3543 public void onAvailable(@NonNull Network network,
3544 @NonNull NetworkCapabilities networkCapabilities,
3545 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003546 onAvailable(network);
3547 if (!networkCapabilities.hasCapability(
3548 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3549 onNetworkSuspended(network);
3550 }
3551 onCapabilitiesChanged(network, networkCapabilities);
3552 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003553 // No call to onBlockedStatusChanged here. That is done by the caller.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003554 }
3555
3556 /**
3557 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003558 *
3559 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3560 * be available at the same time, and onAvailable will be called for each of these as they
3561 * appear.
3562 *
3563 * <p>For callbacks registered with {@link #requestNetwork} and
3564 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3565 * is the new best network for this request and is now tracked by this callback ; this
3566 * callback will no longer receive method calls about other networks that may have been
3567 * passed to this method previously. The previously-best network may have disconnected, or
3568 * it may still be around and the newly-best network may simply be better.
3569 *
3570 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3571 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3572 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3573 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3574 *
3575 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3576 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3577 * this callback as this is prone to race conditions (there is no guarantee the objects
3578 * returned by these methods will be current). Instead, wait for a call to
3579 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3580 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3581 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003582 *
3583 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003584 */
paulhua9a6e2a2019-03-22 16:35:06 +08003585 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003586
3587 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003588 * Called when the network is about to be lost, typically because there are no outstanding
3589 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3590 * with the new replacement network for graceful handover. This method is not guaranteed
3591 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3592 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003593 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003594 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3595 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3596 * this callback as this is prone to race conditions ; calling these methods while in a
3597 * callback may return an outdated or even a null object.
3598 *
3599 * @param network The {@link Network} that is about to be lost.
3600 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3601 * connected for graceful handover; note that the network may still
3602 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003603 */
paulhua9a6e2a2019-03-22 16:35:06 +08003604 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003605
3606 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003607 * Called when a network disconnects or otherwise no longer satisfies this request or
3608 * callback.
3609 *
3610 * <p>If the callback was registered with requestNetwork() or
3611 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3612 * returned by onAvailable() when that network is lost and no other network satisfies
3613 * the criteria of the request.
3614 *
3615 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3616 * each network which no longer satisfies the criteria of the callback.
3617 *
3618 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3619 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3620 * this callback as this is prone to race conditions ; calling these methods while in a
3621 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003622 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003623 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003624 */
paulhua9a6e2a2019-03-22 16:35:06 +08003625 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003626
3627 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003628 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003629 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3630 * requested network request cannot be fulfilled (whether or not a timeout was
3631 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003632 * {@link NetworkRequest} will have already been removed and released, as if
3633 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003634 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003635 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003636
3637 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003638 * Called when the network corresponding to this request changes capabilities but still
3639 * satisfies the requested criteria.
3640 *
3641 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3642 * to be called immediately after {@link #onAvailable}.
3643 *
3644 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3645 * ConnectivityManager methods in this callback as this is prone to race conditions :
3646 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003647 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003648 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius7992afd2020-12-22 15:10:42 -08003649 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003650 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003651 */
paulhua9a6e2a2019-03-22 16:35:06 +08003652 public void onCapabilitiesChanged(@NonNull Network network,
3653 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003654
3655 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003656 * Called when the network corresponding to this request changes {@link LinkProperties}.
3657 *
3658 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3659 * to be called immediately after {@link #onAvailable}.
3660 *
3661 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3662 * ConnectivityManager methods in this callback as this is prone to race conditions :
3663 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003664 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003665 * @param network The {@link Network} whose link properties have changed.
3666 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003667 */
paulhua9a6e2a2019-03-22 16:35:06 +08003668 public void onLinkPropertiesChanged(@NonNull Network network,
3669 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003670
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003671 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003672 * Called when the network the framework connected to for this request suspends data
3673 * transmission temporarily.
3674 *
3675 * <p>This generally means that while the TCP connections are still live temporarily
3676 * network data fails to transfer. To give a specific example, this is used on cellular
3677 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3678 * means read operations on sockets on this network will block once the buffers are
3679 * drained, and write operations will block once the buffers are full.
3680 *
3681 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3682 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3683 * this callback as this is prone to race conditions (there is no guarantee the objects
3684 * returned by these methods will be current).
3685 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003686 * @hide
3687 */
paulhua9a6e2a2019-03-22 16:35:06 +08003688 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003689
3690 /**
3691 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003692 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3693 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003694
3695 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3696 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3697 * this callback as this is prone to race conditions : calling these methods while in a
3698 * callback may return an outdated or even a null object.
3699 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003700 * @hide
3701 */
paulhua9a6e2a2019-03-22 16:35:06 +08003702 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003703
junyulai5ab727b2018-08-07 19:50:45 +08003704 /**
3705 * Called when access to the specified network is blocked or unblocked.
3706 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003707 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3708 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3709 * this callback as this is prone to race conditions : calling these methods while in a
3710 * callback may return an outdated or even a null object.
3711 *
junyulai5ab727b2018-08-07 19:50:45 +08003712 * @param network The {@link Network} whose blocked status has changed.
3713 * @param blocked The blocked status of this {@link Network}.
3714 */
junyulai61143782019-03-04 22:45:36 +08003715 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003716
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003717 /**
3718 * Called when access to the specified network is blocked or unblocked.
3719 *
3720 * If a NetworkCallback object implements this method,
3721 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3722 *
3723 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3724 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3725 * this callback as this is prone to race conditions : calling these methods while in a
3726 * callback may return an outdated or even a null object.
3727 *
3728 * @param network The {@link Network} whose blocked status has changed.
3729 * @param blocked The blocked status of this {@link Network}.
3730 * @hide
3731 */
3732 @SystemApi(client = MODULE_LIBRARIES)
3733 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3734 onBlockedStatusChanged(network, blocked != 0);
3735 }
3736
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003737 private NetworkRequest networkRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -08003738 private final int mFlags;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003739 }
3740
Hugo Benichi145e3792017-05-11 13:16:17 +09003741 /**
3742 * Constant error codes used by ConnectivityService to communicate about failures and errors
3743 * across a Binder boundary.
3744 * @hide
3745 */
3746 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003747 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003748 }
3749
3750 /** @hide */
3751 public static class TooManyRequestsException extends RuntimeException {}
3752
3753 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3754 switch (e.errorCode) {
3755 case Errors.TOO_MANY_REQUESTS:
3756 return new TooManyRequestsException();
3757 default:
3758 Log.w(TAG, "Unknown service error code " + e.errorCode);
3759 return new RuntimeException(e);
3760 }
3761 }
3762
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003763 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003764 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003765 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003766 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003767 /** @hide arg1 = TTL */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003768 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003769 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003770 public static final int CALLBACK_LOST = 4;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003771 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003772 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003773 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003774 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003775 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003776 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003777 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003778 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003779 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003780 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003781 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003782 public static final int CALLBACK_RESUMED = 10;
junyulai5ab727b2018-08-07 19:50:45 +08003783 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003784 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003785
Erik Kline66721822015-11-25 12:49:38 +09003786 /** @hide */
3787 public static String getCallbackName(int whichCallback) {
3788 switch (whichCallback) {
3789 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3790 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3791 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3792 case CALLBACK_LOST: return "CALLBACK_LOST";
3793 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3794 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3795 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003796 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3797 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3798 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003799 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003800 default:
3801 return Integer.toString(whichCallback);
3802 }
3803 }
3804
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003805 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003806 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003807 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003808
Hugo Benichife3325f2016-07-06 22:53:17 +09003809 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003810 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003811 }
3812
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003813 CallbackHandler(Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003814 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003815 }
3816
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003817 @Override
3818 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003819 if (message.what == EXPIRE_LEGACY_REQUEST) {
3820 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3821 return;
3822 }
3823
3824 final NetworkRequest request = getObject(message, NetworkRequest.class);
3825 final Network network = getObject(message, Network.class);
3826 final NetworkCallback callback;
3827 synchronized (sCallbacks) {
3828 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003829 if (callback == null) {
3830 Log.w(TAG,
3831 "callback not found for " + getCallbackName(message.what) + " message");
3832 return;
3833 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003834 if (message.what == CALLBACK_UNAVAIL) {
3835 sCallbacks.remove(request);
3836 callback.networkRequest = ALREADY_UNREGISTERED;
3837 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003838 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003839 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003840 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003841 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003842
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003843 switch (message.what) {
3844 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003845 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003846 break;
3847 }
3848 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003849 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3850 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003851 callback.onAvailable(network, cap, lp, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003852 break;
3853 }
3854 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003855 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003856 break;
3857 }
3858 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003859 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003860 break;
3861 }
3862 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003863 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003864 break;
3865 }
3866 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003867 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3868 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003869 break;
3870 }
3871 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003872 LinkProperties lp = getObject(message, LinkProperties.class);
3873 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003874 break;
3875 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003876 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003877 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003878 break;
3879 }
3880 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003881 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003882 break;
3883 }
junyulai5ab727b2018-08-07 19:50:45 +08003884 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003885 callback.onBlockedStatusChanged(network, message.arg1);
junyulai5ab727b2018-08-07 19:50:45 +08003886 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003887 }
3888 }
3889
Hugo Benichife3325f2016-07-06 22:53:17 +09003890 private <T> T getObject(Message msg, Class<T> c) {
3891 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003892 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003893 }
3894
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003895 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003896 synchronized (sCallbacks) {
3897 if (sCallbackHandler == null) {
3898 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003899 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003900 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003901 }
3902 }
3903
Hugo Benichiec180d52017-02-03 14:18:44 +09003904 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3905 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003906
Lorenzo Colittib199b962021-03-12 22:48:07 +09003907 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3908 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3909 CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003910 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003911 checkCallbackNotNull(callback);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003912 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3913 throw new IllegalArgumentException("null NetworkCapabilities");
3914 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003915 final NetworkRequest request;
Roshan Piusd26ae412020-01-16 12:17:17 -08003916 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003917 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003918 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003919 if (callback.networkRequest != null
3920 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003921 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3922 // and requests (http://b/20701525).
3923 Log.e(TAG, "NetworkCallback was already registered");
3924 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003925 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003926 Binder binder = new Binder();
Roshan Pius7992afd2020-12-22 15:10:42 -08003927 final int callbackFlags = callback.mFlags;
junyulaid1a78162021-01-11 16:53:38 +08003928 if (reqType == LISTEN) {
Roshan Piusd26ae412020-01-16 12:17:17 -08003929 request = mService.listenForNetwork(
Roshan Pius7992afd2020-12-22 15:10:42 -08003930 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08003931 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003932 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003933 request = mService.requestNetwork(
Lorenzo Colittib199b962021-03-12 22:48:07 +09003934 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3935 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003936 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003937 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003938 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003939 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003940 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003941 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003942 } catch (RemoteException e) {
3943 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003944 } catch (ServiceSpecificException e) {
3945 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003946 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003947 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003948 }
3949
Lorenzo Colittib199b962021-03-12 22:48:07 +09003950 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3951 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3952 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3953 legacyType, handler);
3954 }
3955
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003956 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003957 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003958 *
markchien0fe11402020-03-18 21:16:15 +08003959 * This API is only for use in internal system code that requests networks with legacy type and
3960 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchien769c5752020-01-14 12:54:40 +08003961 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003962 *
markchien769c5752020-01-14 12:54:40 +08003963 * @param request {@link NetworkRequest} describing this request.
markchien769c5752020-01-14 12:54:40 +08003964 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3965 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3966 * be a positive value (i.e. >0).
3967 * @param legacyType to specify the network type(#TYPE_*).
3968 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien0fe11402020-03-18 21:16:15 +08003969 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3970 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003971 *
3972 * @hide
3973 */
markchien769c5752020-01-14 12:54:40 +08003974 @SystemApi
markchien0fe11402020-03-18 21:16:15 +08003975 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003976 public void requestNetwork(@NonNull NetworkRequest request,
markchien0fe11402020-03-18 21:16:15 +08003977 int timeoutMs, int legacyType, @NonNull Handler handler,
3978 @NonNull NetworkCallback networkCallback) {
3979 if (legacyType == TYPE_NONE) {
3980 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3981 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003982 CallbackHandler cbHandler = new CallbackHandler(handler);
3983 NetworkCapabilities nc = request.networkCapabilities;
3984 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003985 }
3986
3987 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003988 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003989 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003990 * <p>This method will attempt to find the best network that matches the passed
3991 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3992 * criteria. The platform will evaluate which network is the best at its own discretion.
3993 * Throughput, latency, cost per byte, policy, user preference and other considerations
3994 * may be factored in the decision of what is considered the best network.
3995 *
3996 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3997 * matching this request, while always attempting to match the request to a better network if
3998 * possible. If a better match is found, the platform will switch this request to the now-best
3999 * network and inform the app of the newly best network by invoking
4000 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4001 * will not try to maintain any other network than the best one currently matching the request:
4002 * a network not matching any network request may be disconnected at any time.
4003 *
4004 * <p>For example, an application could use this method to obtain a connected cellular network
4005 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4006 * radio to consume additional power. Or, an application could inform the system that it wants
4007 * a network supporting sending MMSes and have the system let it know about the currently best
4008 * MMS-supporting network through the provided {@link NetworkCallback}.
4009 *
4010 * <p>The status of the request can be followed by listening to the various callbacks described
4011 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4012 * used to direct traffic to the network (although accessing some networks may be subject to
4013 * holding specific permissions). Callers will learn about the specific characteristics of the
4014 * network through
4015 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4016 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4017 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4018 * matching the request at any given time; therefore when a better network matching the request
4019 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4020 * with the new network after which no further updates are given about the previously-best
4021 * network, unless it becomes the best again at some later time. All callbacks are invoked
4022 * in order on the same thread, which by default is a thread created by the framework running
4023 * in the app.
4024 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4025 * callbacks are invoked.
4026 *
4027 * <p>This{@link NetworkRequest} will live until released via
4028 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4029 * which point the system may let go of the network at any time.
4030 *
4031 * <p>A version of this method which takes a timeout is
4032 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4033 * wait for a limited amount of time for the network to become unavailable.
4034 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004035 * <p>It is presently unsupported to request a network with mutable
4036 * {@link NetworkCapabilities} such as
4037 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4038 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4039 * as these {@code NetworkCapabilities} represent states that a particular
4040 * network may never attain, and whether a network will attain these states
4041 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09004042 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004043 *
4044 * <p>This method requires the caller to hold either the
4045 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4046 * or the ability to modify system settings as determined by
4047 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004048 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004049 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4050 * number of outstanding requests to 100 per app (identified by their UID), shared with
4051 * all variants of this method, of {@link #registerNetworkCallback} as well as
4052 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4053 * Requesting a network with this method will count toward this limit. If this limit is
4054 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4055 * make sure to unregister the callbacks with
4056 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4057 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004058 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004059 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4060 * the callback must not be shared - it uniquely specifies this request.
4061 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004062 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4063 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004064 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004065 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004066 public void requestNetwork(@NonNull NetworkRequest request,
4067 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004068 requestNetwork(request, networkCallback, getDefaultHandler());
4069 }
4070
4071 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004072 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004073 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004074 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4075 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004076 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004077 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004078 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4079 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004080 *
4081 * @param request {@link NetworkRequest} describing this request.
4082 * @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 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004085 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004086 public void requestNetwork(@NonNull NetworkRequest request,
4087 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004088 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004089 NetworkCapabilities nc = request.networkCapabilities;
4090 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004091 }
4092
4093 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004094 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohen67e58a02017-03-01 12:47:28 -08004095 * by a timeout.
4096 *
4097 * This function behaves identically to the non-timed-out version
4098 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4099 * is not found within the given time (in milliseconds) the
4100 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4101 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4102 * not have to be released if timed-out (it is automatically released). Unregistering a
4103 * request that timed out is not an error.
4104 *
4105 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4106 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4107 * for that purpose. Calling this method will attempt to bring up the requested network.
4108 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004109 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004110 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4111 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08004112 *
4113 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004114 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4115 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004116 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4117 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4118 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08004119 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004120 public void requestNetwork(@NonNull NetworkRequest request,
4121 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004122 checkTimeout(timeoutMs);
markchien0fe11402020-03-18 21:16:15 +08004123 NetworkCapabilities nc = request.networkCapabilities;
4124 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4125 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004126 }
4127
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004128 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004129 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004130 * by a timeout.
4131 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004132 * This method behaves identically to
4133 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4134 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08004135 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004136 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004137 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4138 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004139 *
4140 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004141 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4142 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004143 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004144 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4145 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004146 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004147 public void requestNetwork(@NonNull NetworkRequest request,
4148 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004149 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004150 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004151 NetworkCapabilities nc = request.networkCapabilities;
4152 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004153 }
4154
4155 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004156 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004157 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004158 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08004159 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04004160 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4161 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004162 */
Erik Klinefb087f12014-11-19 12:12:24 +09004163 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004164
4165 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004166 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004167 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004168 * {@link android.content.Intent#getParcelableExtra(String)}.
4169 */
Erik Klinefb087f12014-11-19 12:12:24 +09004170 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004171
4172
4173 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004174 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004175 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08004176 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004177 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004178 * the request may outlive the calling application and get called back when a suitable
4179 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004180 * <p>
4181 * The operation is an Intent broadcast that goes to a broadcast receiver that
4182 * you registered with {@link Context#registerReceiver} or through the
4183 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4184 * <p>
4185 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09004186 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4187 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004188 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004189 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004190 * Intent to reserve the network or it will be released shortly after the Intent
4191 * is processed.
4192 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04004193 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004194 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004195 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004196 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08004197 * The request may be released normally by calling
4198 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004199 * <p>It is presently unsupported to request a network with either
4200 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4201 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4202 * as these {@code NetworkCapabilities} represent states that a particular
4203 * network may never attain, and whether a network will attain these states
4204 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09004205 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004206 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004207 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4208 * number of outstanding requests to 100 per app (identified by their UID), shared with
4209 * all variants of this method, of {@link #registerNetworkCallback} as well as
4210 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4211 * Requesting a network with this method will count toward this limit. If this limit is
4212 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4213 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4214 * or {@link #releaseNetworkRequest(PendingIntent)}.
4215 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004216 * <p>This method requires the caller to hold either the
4217 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4218 * or the ability to modify system settings as determined by
4219 * {@link android.provider.Settings.System#canWrite}.</p>
4220 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004221 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004222 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004223 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08004224 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004225 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4226 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004227 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004228 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004229 public void requestNetwork(@NonNull NetworkRequest request,
4230 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004231 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004232 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004233 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004234 mService.pendingRequestForNetwork(
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07004235 request.networkCapabilities, operation, mContext.getOpPackageName(),
4236 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004237 } catch (RemoteException e) {
4238 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004239 } catch (ServiceSpecificException e) {
4240 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004241 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004242 }
4243
4244 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004245 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4246 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004247 * This method has the same behavior as
4248 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004249 * releasing network resources and disconnecting.
4250 *
4251 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4252 * PendingIntent passed to
4253 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4254 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4255 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004256 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004257 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004258 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004259 try {
4260 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004261 } catch (RemoteException e) {
4262 throw e.rethrowFromSystemServer();
4263 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004264 }
4265
Hugo Benichiff4bf602017-05-09 15:19:01 +09004266 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004267 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004268 }
4269
4270 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004271 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004272 }
4273
4274 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004275 if (timeoutMs <= 0) {
4276 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4277 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004278 }
4279
4280 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004281 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004282 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004283 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4284 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004285 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004286 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4287 * number of outstanding requests to 100 per app (identified by their UID), shared with
4288 * all variants of this method, of {@link #requestNetwork} as well as
4289 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4290 * Requesting a network with this method will count toward this limit. If this limit is
4291 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4292 * make sure to unregister the callbacks with
4293 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4294 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004295 * @param request {@link NetworkRequest} describing this request.
4296 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4297 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004298 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004299 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004300 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004301 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004302 public void registerNetworkCallback(@NonNull NetworkRequest request,
4303 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004304 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4305 }
4306
4307 /**
4308 * Registers to receive notifications about all networks which satisfy the given
4309 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004310 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4311 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004312 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004313 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4314 * number of outstanding requests to 100 per app (identified by their UID), shared with
4315 * all variants of this method, of {@link #requestNetwork} as well as
4316 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4317 * Requesting a network with this method will count toward this limit. If this limit is
4318 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4319 * make sure to unregister the callbacks with
4320 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4321 *
4322 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004323 * @param request {@link NetworkRequest} describing this request.
4324 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4325 * networks change state.
4326 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004327 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004328 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004329 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004330 public void registerNetworkCallback(@NonNull NetworkRequest request,
4331 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004332 CallbackHandler cbHandler = new CallbackHandler(handler);
4333 NetworkCapabilities nc = request.networkCapabilities;
4334 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004335 }
4336
4337 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004338 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4339 * {@link NetworkRequest}.
4340 *
4341 * This function behaves identically to the version that takes a NetworkCallback, but instead
4342 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4343 * the request may outlive the calling application and get called back when a suitable
4344 * network is found.
4345 * <p>
4346 * The operation is an Intent broadcast that goes to a broadcast receiver that
4347 * you registered with {@link Context#registerReceiver} or through the
4348 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4349 * <p>
4350 * The operation Intent is delivered with two extras, a {@link Network} typed
4351 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4352 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4353 * the original requests parameters.
4354 * <p>
4355 * If there is already a request for this Intent registered (with the equality of
4356 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4357 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4358 * <p>
4359 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004360 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004361 *
4362 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4363 * number of outstanding requests to 100 per app (identified by their UID), shared with
4364 * all variants of this method, of {@link #requestNetwork} as well as
4365 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4366 * Requesting a network with this method will count toward this limit. If this limit is
4367 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4368 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4369 * or {@link #releaseNetworkRequest(PendingIntent)}.
4370 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004371 * @param request {@link NetworkRequest} describing this request.
4372 * @param operation Action to perform when the network is available (corresponds
4373 * to the {@link NetworkCallback#onAvailable} call. Typically
4374 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004375 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004376 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004377 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004378 public void registerNetworkCallback(@NonNull NetworkRequest request,
4379 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004380 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004381 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004382 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004383 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004384 request.networkCapabilities, operation, mContext.getOpPackageName(),
4385 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004386 } catch (RemoteException e) {
4387 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004388 } catch (ServiceSpecificException e) {
4389 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004390 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004391 }
4392
4393 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004394 * Registers to receive notifications about changes in the application's default network. This
4395 * may be a physical network or a virtual network, such as a VPN that applies to the
4396 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004397 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004398 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004399 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4400 * number of outstanding requests to 100 per app (identified by their UID), shared with
4401 * all variants of this method, of {@link #requestNetwork} as well as
4402 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4403 * Requesting a network with this method will count toward this limit. If this limit is
4404 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4405 * make sure to unregister the callbacks with
4406 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4407 *
Erik Klinee0aed632016-03-16 15:31:39 +09004408 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004409 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004410 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004411 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004412 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004413 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004414 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004415 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4416 }
4417
4418 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004419 * Registers to receive notifications about changes in the application's default network. This
4420 * may be a physical network or a virtual network, such as a VPN that applies to the
4421 * application. The callbacks will continue to be called until either the application exits or
4422 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4423 *
4424 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4425 * number of outstanding requests to 100 per app (identified by their UID), shared with
4426 * all variants of this method, of {@link #requestNetwork} as well as
4427 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4428 * Requesting a network with this method will count toward this limit. If this limit is
4429 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4430 * make sure to unregister the callbacks with
4431 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4432 *
4433 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4434 * application's default network changes.
4435 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4436 * @throws RuntimeException if the app already has too many callbacks registered.
4437 */
4438 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4439 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4440 @NonNull Handler handler) {
Lorenzo Colittib199b962021-03-12 22:48:07 +09004441 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4442 }
4443
4444 /**
4445 * Registers to receive notifications about changes in the default network for the specified
4446 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4447 * UID. The callbacks will continue to be called until either the application exits or
4448 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4449 *
4450 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4451 * number of outstanding requests to 100 per app (identified by their UID), shared with
4452 * all variants of this method, of {@link #requestNetwork} as well as
4453 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4454 * Requesting a network with this method will count toward this limit. If this limit is
4455 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4456 * make sure to unregister the callbacks with
4457 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4458 *
4459 * @param uid the UID for which to track default network changes.
4460 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4461 * UID's default network changes.
4462 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4463 * @throws RuntimeException if the app already has too many callbacks registered.
4464 * @hide
4465 */
Lorenzo Colitti3949d6e2021-03-22 18:23:21 +09004466 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittib199b962021-03-12 22:48:07 +09004467 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4468 @RequiresPermission(anyOf = {
4469 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4470 android.Manifest.permission.NETWORK_SETTINGS})
4471 public void registerDefaultNetworkCallbackAsUid(int uid,
4472 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004473 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colittib199b962021-03-12 22:48:07 +09004474 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004475 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4476 }
4477
4478 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004479 * Registers to receive notifications about changes in the system default network. The callbacks
4480 * will continue to be called until either the application exits or
4481 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004482 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004483 * This method should not be used to determine networking state seen by applications, because in
4484 * many cases, most or even all application traffic may not use the default network directly,
4485 * and traffic from different applications may go on different networks by default. As an
4486 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4487 * and not onto the system default network. Applications or system components desiring to do
4488 * determine network state as seen by applications should use other methods such as
4489 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4490 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004491 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4492 * number of outstanding requests to 100 per app (identified by their UID), shared with
4493 * all variants of this method, of {@link #requestNetwork} as well as
4494 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4495 * Requesting a network with this method will count toward this limit. If this limit is
4496 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4497 * make sure to unregister the callbacks with
4498 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4499 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004500 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4501 * system default network changes.
4502 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004503 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004504 *
4505 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004506 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004507 @SystemApi(client = MODULE_LIBRARIES)
4508 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4509 @RequiresPermission(anyOf = {
4510 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4511 android.Manifest.permission.NETWORK_SETTINGS})
4512 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004513 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004514 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004515 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004516 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004517 }
4518
4519 /**
junyulaibd622262021-03-15 11:48:48 +08004520 * Registers to receive notifications about the best matching network which satisfy the given
4521 * {@link NetworkRequest}. The callbacks will continue to be called until
4522 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4523 * called.
4524 *
4525 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4526 * number of outstanding requests to 100 per app (identified by their UID), shared with
4527 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4528 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4529 * Requesting a network with this method will count toward this limit. If this limit is
4530 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4531 * make sure to unregister the callbacks with
4532 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4533 *
4534 *
4535 * @param request {@link NetworkRequest} describing this request.
4536 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4537 * networks change state.
4538 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4539 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai6b0a6a22021-03-05 15:51:17 +08004540 */
junyulai6b0a6a22021-03-05 15:51:17 +08004541 @SuppressLint("ExecutorRegistration")
4542 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4543 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4544 final NetworkCapabilities nc = request.networkCapabilities;
4545 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai8cae3c72021-03-12 20:05:08 +08004546 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai6b0a6a22021-03-05 15:51:17 +08004547 }
4548
4549 /**
fenglu73169332015-04-21 17:12:05 -07004550 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4551 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4552 * network connection for updated bandwidth information. The caller will be notified via
4553 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004554 * method assumes that the caller has previously called
4555 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4556 * changes.
fenglu76564332015-03-20 11:29:56 -07004557 *
fenglu41808e82015-04-27 14:28:04 -07004558 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004559 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004560 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004561 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004562 try {
fenglu73169332015-04-21 17:12:05 -07004563 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004564 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004565 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004566 }
4567 }
4568
4569 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004570 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004571 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4572 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4573 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004574 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4575 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004576 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004577 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4578 * triggering it as soon as this call returns.
4579 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004580 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004581 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004582 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004583 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004584 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004585 final List<NetworkRequest> reqs = new ArrayList<>();
4586 // Find all requests associated to this callback and stop callback triggers immediately.
4587 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4588 synchronized (sCallbacks) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004589 if (networkCallback.networkRequest == null) {
4590 throw new IllegalArgumentException("NetworkCallback was not registered");
4591 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07004592 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4593 Log.d(TAG, "NetworkCallback was already unregistered");
4594 return;
4595 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004596 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4597 if (e.getValue() == networkCallback) {
4598 reqs.add(e.getKey());
4599 }
4600 }
4601 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4602 for (NetworkRequest r : reqs) {
4603 try {
4604 mService.releaseNetworkRequest(r);
4605 } catch (RemoteException e) {
4606 throw e.rethrowFromSystemServer();
4607 }
4608 // Only remove mapping if rpc was successful.
4609 sCallbacks.remove(r);
4610 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004611 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004612 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004613 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004614
4615 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004616 * Unregisters a callback previously registered via
4617 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4618 *
4619 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4620 * PendingIntent passed to
4621 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4622 * Cannot be null.
4623 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004624 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004625 releaseNetworkRequest(operation);
4626 }
4627
4628 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004629 * Informs the system whether it should switch to {@code network} regardless of whether it is
4630 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4631 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4632 * the system default network regardless of any other network that's currently connected. If
4633 * {@code always} is true, then the choice is remembered, so that the next time the user
4634 * connects to this network, the system will switch to it.
4635 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004636 * @param network The network to accept.
4637 * @param accept Whether to accept the network even if unvalidated.
4638 * @param always Whether to remember this choice in the future.
4639 *
4640 * @hide
4641 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004642 @SystemApi(client = MODULE_LIBRARIES)
4643 @RequiresPermission(anyOf = {
4644 android.Manifest.permission.NETWORK_SETTINGS,
4645 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4646 android.Manifest.permission.NETWORK_STACK,
4647 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4648 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004649 try {
4650 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004651 } catch (RemoteException e) {
4652 throw e.rethrowFromSystemServer();
4653 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004654 }
4655
4656 /**
lucaslin25a50472019-03-12 13:08:03 +08004657 * Informs the system whether it should consider the network as validated even if it only has
4658 * partial connectivity. If {@code accept} is true, then the network will be considered as
4659 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4660 * is remembered, so that the next time the user connects to this network, the system will
4661 * switch to it.
4662 *
4663 * @param network The network to accept.
4664 * @param accept Whether to consider the network as validated even if it has partial
4665 * connectivity.
4666 * @param always Whether to remember this choice in the future.
4667 *
4668 * @hide
4669 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004670 @SystemApi(client = MODULE_LIBRARIES)
4671 @RequiresPermission(anyOf = {
4672 android.Manifest.permission.NETWORK_SETTINGS,
4673 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4674 android.Manifest.permission.NETWORK_STACK,
4675 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4676 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4677 boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004678 try {
4679 mService.setAcceptPartialConnectivity(network, accept, always);
4680 } catch (RemoteException e) {
4681 throw e.rethrowFromSystemServer();
4682 }
4683 }
4684
4685 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004686 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4687 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4688 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4689 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4690 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004691 * @param network The network to accept.
4692 *
4693 * @hide
4694 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004695 @SystemApi(client = MODULE_LIBRARIES)
4696 @RequiresPermission(anyOf = {
4697 android.Manifest.permission.NETWORK_SETTINGS,
4698 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4699 android.Manifest.permission.NETWORK_STACK,
4700 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4701 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004702 try {
4703 mService.setAvoidUnvalidated(network);
4704 } catch (RemoteException e) {
4705 throw e.rethrowFromSystemServer();
4706 }
4707 }
4708
4709 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004710 * Requests that the system open the captive portal app on the specified network.
4711 *
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004712 * <p>This is to be used on networks where a captive portal was detected, as per
4713 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4714 *
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004715 * @param network The network to log into.
4716 *
4717 * @hide
4718 */
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004719 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4720 @RequiresPermission(anyOf = {
4721 android.Manifest.permission.NETWORK_SETTINGS,
4722 android.Manifest.permission.NETWORK_STACK,
4723 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4724 })
4725 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004726 try {
4727 mService.startCaptivePortalApp(network);
4728 } catch (RemoteException e) {
4729 throw e.rethrowFromSystemServer();
4730 }
4731 }
4732
4733 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004734 * Requests that the system open the captive portal app with the specified extras.
4735 *
4736 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4737 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004738 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004739 * @param appExtras Extras to include in the app start intent.
4740 * @hide
4741 */
4742 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004743 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004744 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004745 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004746 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004747 } catch (RemoteException e) {
4748 throw e.rethrowFromSystemServer();
4749 }
4750 }
4751
4752 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004753 * Determine whether the device is configured to avoid bad wifi.
4754 * @hide
4755 */
4756 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004757 @RequiresPermission(anyOf = {
4758 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4759 android.Manifest.permission.NETWORK_STACK})
4760 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004761 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004762 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004763 } catch (RemoteException e) {
4764 throw e.rethrowFromSystemServer();
4765 }
4766 }
4767
4768 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004769 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4770 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004771 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4772 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004773 *
4774 * An example of such an operation might be a time-sensitive foreground activity, such as a
4775 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4776 */
4777 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4778
4779 /**
4780 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4781 * a backup channel for traffic that is primarily going over another network.
4782 *
4783 * An example might be maintaining backup connections to peers or servers for the purpose of
4784 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4785 * on backup paths should be negligible compared to the traffic on the main path.
4786 */
4787 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4788
4789 /**
4790 * It is acceptable to use metered data to improve network latency and performance.
4791 */
4792 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4793
4794 /**
4795 * Return value to use for unmetered networks. On such networks we currently set all the flags
4796 * to true.
4797 * @hide
4798 */
4799 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4800 MULTIPATH_PREFERENCE_HANDOVER |
4801 MULTIPATH_PREFERENCE_RELIABILITY |
4802 MULTIPATH_PREFERENCE_PERFORMANCE;
4803
4804 /** @hide */
4805 @Retention(RetentionPolicy.SOURCE)
4806 @IntDef(flag = true, value = {
4807 MULTIPATH_PREFERENCE_HANDOVER,
4808 MULTIPATH_PREFERENCE_RELIABILITY,
4809 MULTIPATH_PREFERENCE_PERFORMANCE,
4810 })
4811 public @interface MultipathPreference {
4812 }
4813
4814 /**
4815 * Provides a hint to the calling application on whether it is desirable to use the
4816 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4817 * for multipath data transfer on this network when it is not the system default network.
4818 * Applications desiring to use multipath network protocols should call this method before
4819 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004820 *
4821 * @param network The network on which the application desires to use multipath data.
4822 * If {@code null}, this method will return the a preference that will generally
4823 * apply to metered networks.
4824 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4825 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004826 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004827 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004828 try {
4829 return mService.getMultipathPreference(network);
4830 } catch (RemoteException e) {
4831 throw e.rethrowFromSystemServer();
4832 }
4833 }
4834
4835 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004836 * Resets all connectivity manager settings back to factory defaults.
4837 * @hide
4838 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004839 @SystemApi(client = MODULE_LIBRARIES)
4840 @RequiresPermission(anyOf = {
4841 android.Manifest.permission.NETWORK_SETTINGS,
4842 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scottd3bb5082015-03-30 13:17:11 -07004843 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004844 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004845 mService.factoryReset();
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00004846 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004847 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004848 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004849 }
4850 }
4851
4852 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004853 * Binds the current process to {@code network}. All Sockets created in the future
4854 * (and not explicitly bound via a bound SocketFactory from
4855 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4856 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4857 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4858 * work and all host name resolutions will fail. This is by design so an application doesn't
4859 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4860 * To clear binding pass {@code null} for {@code network}. Using individually bound
4861 * Sockets created by Network.getSocketFactory().createSocket() and
4862 * performing network-specific host name resolutions via
4863 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004864 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004865 *
4866 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4867 * the current binding.
4868 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4869 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004870 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004871 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004872 // instantiated.
4873 return setProcessDefaultNetwork(network);
4874 }
4875
4876 /**
4877 * Binds the current process to {@code network}. All Sockets created in the future
4878 * (and not explicitly bound via a bound SocketFactory from
4879 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4880 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4881 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4882 * work and all host name resolutions will fail. This is by design so an application doesn't
4883 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4884 * To clear binding pass {@code null} for {@code network}. Using individually bound
4885 * Sockets created by Network.getSocketFactory().createSocket() and
4886 * performing network-specific host name resolutions via
4887 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4888 * {@code setProcessDefaultNetwork}.
4889 *
4890 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4891 * the current binding.
4892 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4893 * @deprecated This function can throw {@link IllegalStateException}. Use
4894 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4895 * is a direct replacement.
4896 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004897 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004898 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004899 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004900 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4901
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004902 if (netId != NETID_UNSET) {
4903 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004904 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004905
4906 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4907 return false;
4908 }
4909
4910 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004911 // Set HTTP proxy system properties to match network.
4912 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004913 try {
Remi NGUYEN VANa1860ff2021-02-03 10:18:20 +09004914 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004915 } catch (SecurityException e) {
4916 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4917 Log.e(TAG, "Can't set proxy properties", e);
4918 }
Paul Jensen99c36662014-08-27 12:38:45 -04004919 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN33e3abb2021-03-18 23:27:19 +09004920 InetAddressCompat.clearDnsCache();
Paul Jensen99c36662014-08-27 12:38:45 -04004921 // Must flush socket pool as idle sockets will be bound to previous network and may
4922 // cause subsequent fetches to be performed on old network.
4923 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004924 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004925
4926 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004927 }
4928
4929 /**
4930 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004931 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004932 *
4933 * @return {@code Network} to which this process is bound, or {@code null}.
4934 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004935 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004936 public Network getBoundNetworkForProcess() {
4937 // Forcing callers to call thru non-static function ensures ConnectivityManager
4938 // instantiated.
4939 return getProcessDefaultNetwork();
4940 }
4941
4942 /**
4943 * Returns the {@link Network} currently bound to this process via
4944 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4945 *
4946 * @return {@code Network} to which this process is bound, or {@code null}.
4947 * @deprecated Using this function can lead to other functions throwing
4948 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4949 * {@code getBoundNetworkForProcess} is a direct replacement.
4950 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004951 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004952 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004953 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004954 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004955 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004956 return new Network(netId);
4957 }
4958
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004959 private void unsupportedStartingFrom(int version) {
4960 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004961 // The getApplicationInfo() call we make below is not supported in system context. Let
4962 // the call through here, and rely on the fact that ConnectivityService will refuse to
4963 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004964 return;
4965 }
4966
4967 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4968 throw new UnsupportedOperationException(
4969 "This method is not supported in target SDK version " + version + " and above");
4970 }
4971 }
4972
4973 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4974 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004975 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004976 // remove these exemptions. Note that this check is not secure, and apps can still access these
4977 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4978 // so is unsupported and may break in the future. http://b/22728205
4979 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07004980 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004981 }
4982
Paul Jensene98c6e02014-05-29 10:12:39 -04004983 /**
4984 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04004985 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04004986 *
4987 * @param network The {@link Network} to bind host resolutions from the current process to, or
4988 * {@code null} to clear the current binding.
4989 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4990 * @hide
4991 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4992 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004993 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00004994 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04004995 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04004996 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09004997 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04004998 }
Felipe Lemed16384b2016-01-22 09:44:57 -08004999
5000 /**
5001 * Device is not restricting metered network activity while application is running on
5002 * background.
5003 */
5004 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5005
5006 /**
5007 * Device is restricting metered network activity while application is running on background,
5008 * but application is allowed to bypass it.
5009 * <p>
5010 * In this state, application should take action to mitigate metered network access.
5011 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5012 */
5013 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5014
5015 /**
5016 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08005017 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08005018 * In this state, application should not try to use the network while running on background,
5019 * because it would be denied.
5020 */
5021 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5022
Felipe Leme6a5b7692016-01-27 14:46:39 -08005023 /**
5024 * A change in the background metered network activity restriction has occurred.
5025 * <p>
5026 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5027 * applies to them.
5028 * <p>
5029 * This is only sent to registered receivers, not manifest receivers.
5030 */
5031 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5032 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5033 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5034
Felipe Leme1b42ef92016-01-25 11:48:04 -08005035 /** @hide */
5036 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08005037 @IntDef(flag = false, value = {
5038 RESTRICT_BACKGROUND_STATUS_DISABLED,
5039 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5040 RESTRICT_BACKGROUND_STATUS_ENABLED,
5041 })
Felipe Lemed16384b2016-01-22 09:44:57 -08005042 public @interface RestrictBackgroundStatus {
5043 }
5044
Felipe Lemed16384b2016-01-22 09:44:57 -08005045 /**
5046 * Determines if the calling application is subject to metered network restrictions while
5047 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07005048 *
5049 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5050 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5051 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08005052 */
5053 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5054 try {
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09005055 return mService.getRestrictBackgroundStatusByCaller();
Felipe Lemed16384b2016-01-22 09:44:57 -08005056 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07005057 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08005058 }
5059 }
Ricky Waid53cf002018-01-23 04:09:45 +00005060
5061 /**
5062 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00005063 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5064 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00005065 *
5066 * @return Hash of network watchlist config file. Null if config does not exist.
5067 */
Chalard Jean42a9c292019-01-07 19:26:34 +09005068 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00005069 public byte[] getNetworkWatchlistConfigHash() {
5070 try {
5071 return mService.getNetworkWatchlistConfigHash();
5072 } catch (RemoteException e) {
5073 Log.e(TAG, "Unable to get watchlist config hash");
5074 throw e.rethrowFromSystemServer();
5075 }
5076 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005077
5078 /**
5079 * Returns the {@code uid} of the owner of a network connection.
5080 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08005081 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5082 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005083 * @param local The local {@link InetSocketAddress} of a connection.
5084 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005085 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08005086 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5087 * android.os.Process#INVALID_UID} if the connection is not found.
5088 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5089 * user.
5090 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005091 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08005092 public int getConnectionOwnerUid(
5093 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005094 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5095 try {
5096 return mService.getConnectionOwnerUid(connectionInfo);
5097 } catch (RemoteException e) {
5098 throw e.rethrowFromSystemServer();
5099 }
5100 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09005101
5102 private void printStackTrace() {
5103 if (DEBUG) {
5104 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5105 final StringBuffer sb = new StringBuffer();
5106 for (int i = 3; i < callStack.length; i++) {
5107 final String stackTrace = callStack[i].toString();
5108 if (stackTrace == null || stackTrace.contains("android.os")) {
5109 break;
5110 }
5111 sb.append(" [").append(stackTrace).append("]");
5112 }
5113 Log.d(TAG, "StackLog:" + sb.toString());
5114 }
5115 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005116
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09005117 /** @hide */
5118 public TestNetworkManager startOrGetTestNetworkManager() {
5119 final IBinder tnBinder;
5120 try {
5121 tnBinder = mService.startOrGetTestNetworkService();
5122 } catch (RemoteException e) {
5123 throw e.rethrowFromSystemServer();
5124 }
5125
5126 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5127 }
5128
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09005129 /** @hide */
5130 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5131 return new ConnectivityDiagnosticsManager(mContext, mService);
5132 }
5133
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005134 /**
5135 * Simulates a Data Stall for the specified Network.
5136 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09005137 * <p>This method should only be used for tests.
5138 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005139 * <p>The caller must be the owner of the specified Network.
5140 *
5141 * @param detectionMethod The detection method used to identify the Data Stall.
5142 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
5143 * @param network The Network for which a Data Stall is being simluated.
5144 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5145 * @throws SecurityException if the caller is not the owner of the given network.
5146 * @hide
5147 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09005148 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005149 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5150 android.Manifest.permission.NETWORK_STACK})
5151 public void simulateDataStall(int detectionMethod, long timestampMillis,
5152 @NonNull Network network, @NonNull PersistableBundle extras) {
5153 try {
5154 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5155 } catch (RemoteException e) {
5156 e.rethrowFromSystemServer();
5157 }
5158 }
James Mattisdcea9fb2020-10-28 21:48:54 -07005159
Daniel Bright60f02ed2020-06-15 16:10:01 -07005160 @NonNull
5161 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5162
5163 /**
5164 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5165 * receive available QoS events related to the {@link Network} and local ip + port
5166 * specified within socketInfo.
5167 * <p/>
5168 * The same {@link QosCallback} must be unregistered before being registered a second time,
5169 * otherwise {@link QosCallbackRegistrationException} is thrown.
5170 * <p/>
5171 * This API does not, in itself, require any permission if called with a network that is not
5172 * restricted. However, the underlying implementation currently only supports the IMS network,
5173 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5174 * useful, because they'd never be called back on networks that they would have access to.
5175 *
5176 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5177 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5178 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5179 * @throws RuntimeException if the app already has too many callbacks registered.
5180 *
5181 * Exceptions after the time of registration is passed through
5182 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5183 *
5184 * @param socketInfo the socket information used to match QoS events
Daniel Bright60f02ed2020-06-15 16:10:01 -07005185 * @param executor The executor on which the callback will be invoked. The provided
5186 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Brightb953a3e2021-03-10 11:51:50 -08005187 * callbacks cannot be guaranteed.onQosCallbackRegistered
5188 * @param callback receives qos events that satisfy socketInfo
Daniel Bright60f02ed2020-06-15 16:10:01 -07005189 *
5190 * @hide
5191 */
5192 @SystemApi
5193 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Brightb953a3e2021-03-10 11:51:50 -08005194 @CallbackExecutor @NonNull final Executor executor,
5195 @NonNull final QosCallback callback) {
Daniel Bright60f02ed2020-06-15 16:10:01 -07005196 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005197 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Brightb953a3e2021-03-10 11:51:50 -08005198 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005199
5200 try {
5201 synchronized (mQosCallbackConnections) {
5202 if (getQosCallbackConnection(callback) == null) {
5203 final QosCallbackConnection connection =
5204 new QosCallbackConnection(this, callback, executor);
5205 mQosCallbackConnections.add(connection);
5206 mService.registerQosSocketCallback(socketInfo, connection);
5207 } else {
5208 Log.e(TAG, "registerQosCallback: Callback already registered");
5209 throw new QosCallbackRegistrationException();
5210 }
5211 }
5212 } catch (final RemoteException e) {
5213 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5214
5215 // The same unregister method method is called for consistency even though nothing
5216 // will be sent to the ConnectivityService since the callback was never successfully
5217 // registered.
5218 unregisterQosCallback(callback);
5219 e.rethrowFromSystemServer();
5220 } catch (final ServiceSpecificException e) {
5221 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5222 unregisterQosCallback(callback);
5223 throw convertServiceException(e);
5224 }
5225 }
5226
5227 /**
5228 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5229 * events once unregistered and can be registered a second time.
5230 * <p/>
5231 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5232 *
5233 * @param callback the callback being unregistered
5234 *
5235 * @hide
5236 */
5237 @SystemApi
5238 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5239 Objects.requireNonNull(callback, "The callback must be non-null");
5240 try {
5241 synchronized (mQosCallbackConnections) {
5242 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5243 if (connection != null) {
5244 connection.stopReceivingMessages();
5245 mService.unregisterQosCallback(connection);
5246 mQosCallbackConnections.remove(connection);
5247 } else {
5248 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5249 }
5250 }
5251 } catch (final RemoteException e) {
5252 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5253 e.rethrowFromSystemServer();
5254 }
5255 }
5256
5257 /**
5258 * Gets the connection related to the callback.
5259 *
5260 * @param callback the callback to look up
5261 * @return the related connection
5262 */
5263 @Nullable
5264 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5265 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5266 // Checking by reference here is intentional
5267 if (connection.getCallback() == callback) {
5268 return connection;
5269 }
5270 }
5271 return null;
5272 }
Junyu Lai23568a42021-01-19 11:10:56 +00005273
5274 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08005275 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Lai23568a42021-01-19 11:10:56 +00005276 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5277 * be used to request that the system provide a network without causing the network to be
5278 * in the foreground.
5279 *
5280 * <p>This method will attempt to find the best network that matches the passed
5281 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5282 * criteria. The platform will evaluate which network is the best at its own discretion.
5283 * Throughput, latency, cost per byte, policy, user preference and other considerations
5284 * may be factored in the decision of what is considered the best network.
5285 *
5286 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5287 * matching this request, while always attempting to match the request to a better network if
5288 * possible. If a better match is found, the platform will switch this request to the now-best
5289 * network and inform the app of the newly best network by invoking
5290 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5291 * will not try to maintain any other network than the best one currently matching the request:
5292 * a network not matching any network request may be disconnected at any time.
5293 *
5294 * <p>For example, an application could use this method to obtain a connected cellular network
5295 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5296 * radio to consume additional power. Or, an application could inform the system that it wants
5297 * a network supporting sending MMSes and have the system let it know about the currently best
5298 * MMS-supporting network through the provided {@link NetworkCallback}.
5299 *
5300 * <p>The status of the request can be followed by listening to the various callbacks described
5301 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5302 * used to direct traffic to the network (although accessing some networks may be subject to
5303 * holding specific permissions). Callers will learn about the specific characteristics of the
5304 * network through
5305 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5306 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5307 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5308 * matching the request at any given time; therefore when a better network matching the request
5309 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5310 * with the new network after which no further updates are given about the previously-best
5311 * network, unless it becomes the best again at some later time. All callbacks are invoked
5312 * in order on the same thread, which by default is a thread created by the framework running
5313 * in the app.
5314 *
5315 * <p>This{@link NetworkRequest} will live until released via
5316 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5317 * which point the system may let go of the network at any time.
5318 *
5319 * <p>It is presently unsupported to request a network with mutable
5320 * {@link NetworkCapabilities} such as
5321 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5322 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5323 * as these {@code NetworkCapabilities} represent states that a particular
5324 * network may never attain, and whether a network will attain these states
5325 * is unknown prior to bringing up the network so the framework does not
5326 * know how to go about satisfying a request with these capabilities.
5327 *
5328 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5329 * number of outstanding requests to 100 per app (identified by their UID), shared with
5330 * all variants of this method, of {@link #registerNetworkCallback} as well as
5331 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5332 * Requesting a network with this method will count toward this limit. If this limit is
5333 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5334 * make sure to unregister the callbacks with
5335 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5336 *
5337 * @param request {@link NetworkRequest} describing this request.
5338 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5339 * If null, the callback is invoked on the default internal Handler.
5340 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5341 * the callback must not be shared - it uniquely specifies this request.
5342 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5343 * @throws SecurityException if missing the appropriate permissions.
5344 * @throws RuntimeException if the app already has too many callbacks registered.
5345 *
5346 * @hide
5347 */
5348 @SystemApi(client = MODULE_LIBRARIES)
5349 @SuppressLint("ExecutorRegistration")
5350 @RequiresPermission(anyOf = {
5351 android.Manifest.permission.NETWORK_SETTINGS,
5352 android.Manifest.permission.NETWORK_STACK,
5353 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5354 })
5355 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaif4bc12f2021-03-09 20:49:48 +08005356 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Lai23568a42021-01-19 11:10:56 +00005357 final NetworkCapabilities nc = request.networkCapabilities;
5358 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaif4bc12f2021-03-09 20:49:48 +08005359 TYPE_NONE, new CallbackHandler(handler));
Junyu Lai23568a42021-01-19 11:10:56 +00005360 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005361
5362 /**
James Mattis6e6fabf2021-01-10 14:24:24 -08005363 * Used by automotive devices to set the network preferences used to direct traffic at an
5364 * application level as per the given OemNetworkPreferences. An example use-case would be an
5365 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5366 * vehicle via a particular network.
5367 *
5368 * Calling this will overwrite the existing preference.
5369 *
5370 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5371 * @param executor the executor on which listener will be invoked.
5372 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5373 * communicate completion of setOemNetworkPreference(). This will only be
5374 * called once upon successful completion of setOemNetworkPreference().
5375 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5376 * @throws SecurityException if missing the appropriate permissions.
5377 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005378 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005379 */
James Mattis7a253542021-01-26 16:23:52 -08005380 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005381 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005382 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005383 @Nullable @CallbackExecutor final Executor executor,
Chalard Jeancc9ad152021-03-03 16:37:13 +09005384 @Nullable final Runnable listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08005385 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5386 if (null != listener) {
5387 Objects.requireNonNull(executor, "Executor must be non-null");
5388 }
Chalard Jeancc9ad152021-03-03 16:37:13 +09005389 final IOnCompleteListener listenerInternal = listener == null ? null :
5390 new IOnCompleteListener.Stub() {
James Mattis6e6fabf2021-01-10 14:24:24 -08005391 @Override
5392 public void onComplete() {
Chalard Jeancc9ad152021-03-03 16:37:13 +09005393 executor.execute(listener::run);
James Mattis6e6fabf2021-01-10 14:24:24 -08005394 }
5395 };
5396
5397 try {
5398 mService.setOemNetworkPreference(preference, listenerInternal);
5399 } catch (RemoteException e) {
5400 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5401 throw e.rethrowFromSystemServer();
5402 }
5403 }
lucaslin1a6095c2021-03-12 00:46:33 +08005404
Chalard Jean03433052021-02-25 17:23:40 +09005405 /**
5406 * Request that a user profile is put by default on a network matching a given preference.
5407 *
5408 * See the documentation for the individual preferences for a description of the supported
5409 * behaviors.
5410 *
5411 * @param profile the profile concerned.
5412 * @param preference the preference for this profile.
5413 * @param executor an executor to execute the listener on. Optional if listener is null.
5414 * @param listener an optional listener to listen for completion of the operation.
5415 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5416 * @throws SecurityException if missing the appropriate permissions.
5417 * @hide
5418 */
Chalard Jeancc9ad152021-03-03 16:37:13 +09005419 // This function is for establishing per-profile default networking and can only be called by
5420 // the device policy manager, running as the system server. It would make no sense to call it
5421 // on a context for a user because it does not establish a setting on behalf of a user, rather
5422 // it establishes a setting for a user on behalf of the DPM.
5423 @SuppressLint({"UserHandle"})
5424 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09005425 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5426 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5427 @ProfileNetworkPreference final int preference,
5428 @Nullable @CallbackExecutor final Executor executor,
5429 @Nullable final Runnable listener) {
5430 if (null != listener) {
5431 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5432 }
5433 final IOnCompleteListener proxy;
5434 if (null == listener) {
5435 proxy = null;
5436 } else {
5437 proxy = new IOnCompleteListener.Stub() {
5438 @Override
5439 public void onComplete() {
5440 executor.execute(listener::run);
5441 }
5442 };
5443 }
5444 try {
5445 mService.setProfileNetworkPreference(profile, preference, proxy);
5446 } catch (RemoteException e) {
5447 throw e.rethrowFromSystemServer();
5448 }
5449 }
5450
lucaslin1a6095c2021-03-12 00:46:33 +08005451 // The first network ID of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005452 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin1a6095c2021-03-12 00:46:33 +08005453 // The network ID range of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005454 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin1a6095c2021-03-12 00:46:33 +08005455
5456 /**
5457 * Get the network ID range reserved for IPSec tunnel interfaces.
5458 *
5459 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5460 * @hide
5461 */
5462 @SystemApi(client = MODULE_LIBRARIES)
5463 @NonNull
5464 public static Range<Integer> getIpSecNetIdRange() {
5465 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5466 }
lucaslin50205af2021-03-12 16:11:27 +08005467
5468 /**
5469 * Get private DNS mode from settings.
5470 *
lucaslin73c98602021-03-17 14:53:35 +08005471 * @param context The Context to query the private DNS mode from settings.
lucaslin50205af2021-03-12 16:11:27 +08005472 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5473 *
5474 * @hide
5475 */
5476 @SystemApi(client = MODULE_LIBRARIES)
5477 @NonNull
5478 @PrivateDnsMode
lucaslinacd3ded2021-03-16 17:11:14 +08005479 public static String getPrivateDnsMode(@NonNull Context context) {
5480 final ContentResolver cr = context.getContentResolver();
lucaslin50205af2021-03-12 16:11:27 +08005481 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5482 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5483 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5484 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5485 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5486 return mode;
5487 }
paulhu28321462021-03-25 12:36:56 +08005488
5489 /**
5490 * Set private DNS mode to settings.
5491 *
5492 * @param context The {@link Context} to set the private DNS mode.
5493 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5494 *
5495 * @hide
5496 */
5497 @SystemApi(client = MODULE_LIBRARIES)
5498 public static void setPrivateDnsMode(@NonNull Context context,
5499 @NonNull @PrivateDnsMode String mode) {
5500 if (!(mode == PRIVATE_DNS_MODE_OFF
5501 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5502 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5503 throw new IllegalArgumentException("Invalid private dns mode");
5504 }
5505 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5506 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005507}