blob: 350b47fc6df7224cbaf1dc456d87e50c9769a078 [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,
Lorenzo Colittia37eaff2021-03-25 23:17:36 +0900927 BLOCKED_REASON_LOCKDOWN_VPN,
Sudheer Shanka457dfd52021-03-23 08:12:28 +0000928 BLOCKED_METERED_REASON_DATA_SAVER,
929 BLOCKED_METERED_REASON_USER_RESTRICTED,
930 BLOCKED_METERED_REASON_ADMIN_DISABLED,
931 })
932 public @interface BlockedReason {}
933
Lorenzo Colitti60104f52021-03-18 00:54:57 +0900934 /**
935 * Set of blocked reasons that are only applicable on metered networks.
936 *
937 * @hide
938 */
939 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
940 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
941
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900942 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700943 private final IConnectivityManager mService;
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +0900944
Paul Jensen12131352014-12-10 15:12:18 -0500945 /**
946 * A kludge to facilitate static access where a Context pointer isn't available, like in the
947 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
948 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
949 * methods that take a Context argument.
950 */
951 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800952
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +0900953 private final Context mContext;
954
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +0000955 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800956
Robert Greenwalt26744a52013-02-15 10:56:35 -0800957 /**
958 * Tests if a given integer represents a valid network type.
959 * @param networkType the type to be tested
960 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen1c9f2e42015-05-06 10:42:25 -0400961 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
962 * validate a network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800963 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700964 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700965 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900966 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800967 }
968
Robert Greenwalt26744a52013-02-15 10:56:35 -0800969 /**
970 * Returns a non-localized string representing a given network type.
971 * ONLY used for debugging output.
972 * @param type the type needing naming
973 * @return a String for the given type, or a string version of the type ("87")
974 * if no name is known.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900975 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800976 * {@hide}
977 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900978 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +0000979 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700980 public static String getNetworkTypeName(int type) {
981 switch (type) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900982 case TYPE_NONE:
983 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700984 case TYPE_MOBILE:
985 return "MOBILE";
986 case TYPE_WIFI:
987 return "WIFI";
988 case TYPE_MOBILE_MMS:
989 return "MOBILE_MMS";
990 case TYPE_MOBILE_SUPL:
991 return "MOBILE_SUPL";
992 case TYPE_MOBILE_DUN:
993 return "MOBILE_DUN";
994 case TYPE_MOBILE_HIPRI:
995 return "MOBILE_HIPRI";
996 case TYPE_WIMAX:
997 return "WIMAX";
998 case TYPE_BLUETOOTH:
999 return "BLUETOOTH";
1000 case TYPE_DUMMY:
1001 return "DUMMY";
1002 case TYPE_ETHERNET:
1003 return "ETHERNET";
1004 case TYPE_MOBILE_FOTA:
1005 return "MOBILE_FOTA";
1006 case TYPE_MOBILE_IMS:
1007 return "MOBILE_IMS";
1008 case TYPE_MOBILE_CBS:
1009 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -07001010 case TYPE_WIFI_P2P:
1011 return "WIFI_P2P";
Wink Saville70dbdcc2013-07-29 15:00:57 -07001012 case TYPE_MOBILE_IA:
1013 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -07001014 case TYPE_MOBILE_EMERGENCY:
1015 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -05001016 case TYPE_PROXY:
1017 return "PROXY";
Erik Klineb1ff7002014-11-19 17:23:41 +09001018 case TYPE_VPN:
1019 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -07001020 default:
1021 return Integer.toString(type);
1022 }
1023 }
1024
Robert Greenwalt26744a52013-02-15 10:56:35 -08001025 /**
Aaron Huangdfba5d12020-06-27 07:18:23 +08001026 * @hide
Aaron Huangdfba5d12020-06-27 07:18:23 +08001027 */
lucaslin8c121bf2021-03-17 14:16:01 +08001028 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huangdfba5d12020-06-27 07:18:23 +08001029 public void systemReady() {
1030 try {
1031 mService.systemReady();
1032 } catch (RemoteException e) {
1033 throw e.rethrowFromSystemServer();
1034 }
1035 }
1036
1037 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001038 * Checks if a given type uses the cellular data connection.
1039 * This should be replaced in the future by a network property.
1040 * @param networkType the type to check
1041 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09001042 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001043 * {@hide}
1044 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09001045 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001046 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001047 public static boolean isNetworkTypeMobile(int networkType) {
1048 switch (networkType) {
1049 case TYPE_MOBILE:
1050 case TYPE_MOBILE_MMS:
1051 case TYPE_MOBILE_SUPL:
1052 case TYPE_MOBILE_DUN:
1053 case TYPE_MOBILE_HIPRI:
1054 case TYPE_MOBILE_FOTA:
1055 case TYPE_MOBILE_IMS:
1056 case TYPE_MOBILE_CBS:
Wink Saville70dbdcc2013-07-29 15:00:57 -07001057 case TYPE_MOBILE_IA:
Ram201d45f2014-06-26 11:03:44 -07001058 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -07001059 return true;
1060 default:
1061 return false;
1062 }
1063 }
1064
Robert Greenwalt26744a52013-02-15 10:56:35 -08001065 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001066 * Checks if the given network type is backed by a Wi-Fi radio.
1067 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001068 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001069 * @hide
1070 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09001071 @Deprecated
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -07001072 public static boolean isNetworkTypeWifi(int networkType) {
1073 switch (networkType) {
1074 case TYPE_WIFI:
1075 case TYPE_WIFI_P2P:
1076 return true;
1077 default:
1078 return false;
1079 }
1080 }
1081
1082 /**
Chalard Jean03433052021-02-25 17:23:40 +09001083 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1084 * Specify that the traffic for this user should by follow the default rules.
1085 * @hide
1086 */
Chalard Jean560d4032021-03-17 14:33:24 +09001087 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09001088 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1089
1090 /**
1091 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1092 * Specify that the traffic for this user should by default go on a network with
1093 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1094 * if no such network is available.
1095 * @hide
1096 */
Chalard Jean560d4032021-03-17 14:33:24 +09001097 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09001098 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1099
1100 /** @hide */
1101 @Retention(RetentionPolicy.SOURCE)
1102 @IntDef(value = {
1103 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1104 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1105 })
1106 public @interface ProfileNetworkPreference {
1107 }
1108
1109 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001110 * Specifies the preferred network type. When the device has more
1111 * than one type available the preferred network type will be used.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001112 *
1113 * @param preference the network type to prefer over all others. It is
1114 * unspecified what happens to the old preferred network in the
1115 * overall ordering.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001116 * @deprecated Functionality has been removed as it no longer makes sense,
1117 * with many more than two networks - we'd need an array to express
1118 * preference. Instead we use dynamic network properties of
1119 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001120 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001121 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001122 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001123 }
1124
Robert Greenwalt26744a52013-02-15 10:56:35 -08001125 /**
1126 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001127 *
1128 * @return an integer representing the preferred network type
1129 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001130 * @deprecated Functionality has been removed as it no longer makes sense,
1131 * with many more than two networks - we'd need an array to express
1132 * preference. Instead we use dynamic network properties of
1133 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001134 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001135 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001136 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001137 public int getNetworkPreference() {
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001138 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001139 }
1140
Scott Mainf58b7d82011-10-06 19:02:28 -07001141 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001142 * Returns details about the currently active default data network. When
1143 * connected, this network is the default route for outgoing connections.
1144 * You should always check {@link NetworkInfo#isConnected()} before initiating
1145 * network traffic. This may return {@code null} when there is no default
1146 * network.
Chalard Jean7c85ba42018-03-29 17:45:24 +09001147 * Note that if the default network is a VPN, this method will return the
1148 * NetworkInfo for one of its underlying networks instead, or null if the
1149 * VPN agent did not specify any. Apps interested in learning about VPNs
1150 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001151 *
1152 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001153 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001154 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001155 */
junyulai5c2f6262018-12-13 12:47:51 +08001156 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001157 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001158 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001159 public NetworkInfo getActiveNetworkInfo() {
1160 try {
1161 return mService.getActiveNetworkInfo();
1162 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001163 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001164 }
1165 }
1166
Robert Greenwalt26744a52013-02-15 10:56:35 -08001167 /**
Paul Jensenc2569432015-02-13 14:18:39 -05001168 * Returns a {@link Network} object corresponding to the currently active
1169 * default data network. In the event that the current active default data
1170 * network disconnects, the returned {@code Network} object will no longer
1171 * be usable. This will return {@code null} when there is no default
1172 * network.
1173 *
1174 * @return a {@link Network} object for the current default network or
1175 * {@code null} if no default network is currently active
Paul Jensenc2569432015-02-13 14:18:39 -05001176 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001177 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001178 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001179 public Network getActiveNetwork() {
1180 try {
1181 return mService.getActiveNetwork();
1182 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001183 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001184 }
1185 }
1186
1187 /**
Robin Leeda4d2e22016-03-24 12:07:00 +00001188 * Returns a {@link Network} object corresponding to the currently active
1189 * default data network for a specific UID. In the event that the default data
1190 * network disconnects, the returned {@code Network} object will no longer
1191 * be usable. This will return {@code null} when there is no default
1192 * network for the UID.
Robin Leeda4d2e22016-03-24 12:07:00 +00001193 *
1194 * @return a {@link Network} object for the current default network for the
1195 * given UID or {@code null} if no default network is currently active
lifrb22da4e2021-03-11 20:11:09 +08001196 * TODO: b/183465229 Cleanup getActiveNetworkForUid once b/165835257 is fixed
Robin Leeda4d2e22016-03-24 12:07:00 +00001197 */
paulhuec0a9632019-08-12 16:25:11 +08001198 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001199 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001200 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001201 return getActiveNetworkForUid(uid, false);
1202 }
1203
1204 /** {@hide} */
1205 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001206 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001207 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001208 } catch (RemoteException e) {
1209 throw e.rethrowFromSystemServer();
1210 }
1211 }
1212
1213 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001214 * Adds or removes a requirement for given UID ranges to use the VPN.
1215 *
1216 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1217 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1218 * otherwise have permission to bypass the VPN (e.g., because they have the
1219 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1220 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1221 * set to {@code false}, a previously-added restriction is removed.
1222 * <p>
1223 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1224 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1225 * remove a previously-added range, the exact range must be removed as is.
1226 * <p>
1227 * The changes are applied asynchronously and may not have been applied by the time the method
1228 * returns. Apps will be notified about any changes that apply to them via
1229 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1230 * effect.
1231 * <p>
1232 * This method should be called only by the VPN code.
1233 *
1234 * @param ranges the UID ranges to restrict
1235 * @param requireVpn whether the specified UID ranges must use a VPN
1236 *
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001237 * @hide
1238 */
1239 @RequiresPermission(anyOf = {
1240 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001241 android.Manifest.permission.NETWORK_STACK,
1242 android.Manifest.permission.NETWORK_SETTINGS})
1243 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001244 public void setRequireVpnForUids(boolean requireVpn,
1245 @NonNull Collection<Range<Integer>> ranges) {
1246 Objects.requireNonNull(ranges);
1247 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1248 // This method is not necessarily expected to be used outside the system server, so
1249 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1250 // stack process, or by tests.
1251 UidRange[] rangesArray = new UidRange[ranges.size()];
1252 int index = 0;
1253 for (Range<Integer> range : ranges) {
1254 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1255 }
1256 try {
1257 mService.setRequireVpnForUids(requireVpn, rangesArray);
1258 } catch (RemoteException e) {
1259 throw e.rethrowFromSystemServer();
1260 }
1261 }
1262
1263 /**
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001264 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1265 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1266 * but is still supported for backwards compatibility.
1267 * <p>
1268 * This type of VPN is assumed always to use the system default network, and must always declare
1269 * exactly one underlying network, which is the network that was the default when the VPN
1270 * connected.
1271 * <p>
1272 * Calling this method with {@code true} enables legacy behaviour, specifically:
1273 * <ul>
1274 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1275 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1276 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1277 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1278 * underlying the VPN.</li>
1279 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1280 * similarly replaced by the VPN network state.</li>
1281 * <li>Information on current network interfaces passed to NetworkStatsService will not
1282 * include any VPN interfaces.</li>
1283 * </ul>
1284 *
1285 * @param enabled whether legacy lockdown VPN is enabled or disabled
1286 *
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001287 * @hide
1288 */
1289 @RequiresPermission(anyOf = {
1290 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001291 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001292 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin5140e482021-03-22 11:51:27 +08001293 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001294 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1295 try {
1296 mService.setLegacyLockdownVpnEnabled(enabled);
1297 } catch (RemoteException e) {
1298 throw e.rethrowFromSystemServer();
1299 }
1300 }
1301
1302 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001303 * Returns details about the currently active default data network
1304 * for a given uid. This is for internal use only to avoid spying
1305 * other apps.
1306 *
1307 * @return a {@link NetworkInfo} object for the current default network
1308 * for the given uid or {@code null} if no default network is
1309 * available for the specified uid.
1310 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001311 * {@hide}
1312 */
paulhuec0a9632019-08-12 16:25:11 +08001313 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001314 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001315 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001316 return getActiveNetworkInfoForUid(uid, false);
1317 }
1318
1319 /** {@hide} */
1320 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001321 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001322 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001323 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001324 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001325 }
1326 }
1327
Robert Greenwalt26744a52013-02-15 10:56:35 -08001328 /**
1329 * Returns connection status information about a particular
1330 * network type.
1331 *
1332 * @param networkType integer specifying which networkType in
1333 * which you're interested.
1334 * @return a {@link NetworkInfo} object for the requested
1335 * network type or {@code null} if the type is not
Chalard Jean7c85ba42018-03-29 17:45:24 +09001336 * supported by the device. If {@code networkType} is
1337 * TYPE_VPN and a VPN is active for the calling app,
1338 * then this method will try to return one of the
1339 * underlying networks for the VPN or null if the
1340 * VPN agent didn't specify any.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001341 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001342 * @deprecated This method does not support multiple connected networks
1343 * of the same type. Use {@link #getAllNetworks} and
1344 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001345 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001346 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001347 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001348 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001349 public NetworkInfo getNetworkInfo(int networkType) {
1350 try {
1351 return mService.getNetworkInfo(networkType);
1352 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001353 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001354 }
1355 }
1356
Robert Greenwalt26744a52013-02-15 10:56:35 -08001357 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001358 * Returns connection status information about a particular
1359 * Network.
1360 *
1361 * @param network {@link Network} specifying which network
1362 * in which you're interested.
1363 * @return a {@link NetworkInfo} object for the requested
1364 * network or {@code null} if the {@code Network}
1365 * is not valid.
junyulai5c2f6262018-12-13 12:47:51 +08001366 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001367 */
junyulai5c2f6262018-12-13 12:47:51 +08001368 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001369 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001370 @Nullable
1371 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001372 return getNetworkInfoForUid(network, Process.myUid(), false);
1373 }
1374
1375 /** {@hide} */
1376 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001377 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001378 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001379 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001380 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001381 }
1382 }
1383
1384 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001385 * Returns connection status information about all network
1386 * types supported by the device.
1387 *
1388 * @return an array of {@link NetworkInfo} objects. Check each
1389 * {@link NetworkInfo#getType} for which type each applies.
1390 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001391 * @deprecated This method does not support multiple connected networks
1392 * of the same type. Use {@link #getAllNetworks} and
1393 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001394 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001395 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001396 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001397 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001398 public NetworkInfo[] getAllNetworkInfo() {
1399 try {
1400 return mService.getAllNetworkInfo();
1401 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001402 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001403 }
1404 }
1405
Robert Greenwalt26744a52013-02-15 10:56:35 -08001406 /**
junyulai57840802021-03-03 12:09:05 +08001407 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1408 * connected.
1409 * @hide
1410 */
1411 @SystemApi(client = MODULE_LIBRARIES)
1412 @RequiresPermission(anyOf = {
1413 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1414 android.Manifest.permission.NETWORK_STACK,
1415 android.Manifest.permission.NETWORK_SETTINGS})
1416 @NonNull
1417 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1418 try {
1419 return mService.getAllNetworkStateSnapshot();
1420 } catch (RemoteException e) {
1421 throw e.rethrowFromSystemServer();
1422 }
1423 }
1424
1425 /**
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001426 * Returns the {@link Network} object currently serving a given type, or
1427 * null if the given type is not connected.
1428 *
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001429 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04001430 * @deprecated This method does not support multiple connected networks
1431 * of the same type. Use {@link #getAllNetworks} and
1432 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001433 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001434 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001435 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001436 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001437 public Network getNetworkForType(int networkType) {
1438 try {
1439 return mService.getNetworkForType(networkType);
1440 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001441 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001442 }
1443 }
1444
1445 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001446 * Returns an array of all {@link Network} currently tracked by the
1447 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001448 *
1449 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001450 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001451 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001452 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001453 public Network[] getAllNetworks() {
1454 try {
1455 return mService.getAllNetworks();
1456 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001457 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001458 }
1459 }
1460
1461 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001462 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001463 * the Networks that applications run by the given user will use by default.
1464 * @hide
1465 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001466 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001467 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1468 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001469 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001470 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001471 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001472 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001473 }
1474 }
1475
1476 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001477 * Returns the IP information for the current default network.
1478 *
1479 * @return a {@link LinkProperties} object describing the IP info
1480 * for the current default network, or {@code null} if there
1481 * is no current default network.
1482 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001483 * {@hide}
Chalard Jeancc47b522019-01-11 16:47:53 +09001484 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1485 * value of {@link #getActiveNetwork()} instead. In particular,
1486 * this method will return non-null LinkProperties even if the
1487 * app is blocked by policy from using this network.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001488 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001489 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-01-11 16:47:53 +09001490 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001491 public LinkProperties getActiveLinkProperties() {
1492 try {
1493 return mService.getActiveLinkProperties();
1494 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001495 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001496 }
1497 }
1498
Robert Greenwalt26744a52013-02-15 10:56:35 -08001499 /**
1500 * Returns the IP information for a given network type.
1501 *
1502 * @param networkType the network type of interest.
1503 * @return a {@link LinkProperties} object describing the IP info
1504 * for the given networkType, or {@code null} if there is
1505 * no current default network.
1506 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001507 * {@hide}
Paul Jensena8e6dc62015-03-18 12:23:02 -04001508 * @deprecated This method does not support multiple connected networks
1509 * of the same type. Use {@link #getAllNetworks},
1510 * {@link #getNetworkInfo(android.net.Network)}, and
1511 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001512 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001513 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001514 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001515 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001516 public LinkProperties getLinkProperties(int networkType) {
1517 try {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001518 return mService.getLinkPropertiesForType(networkType);
1519 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001520 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001521 }
1522 }
1523
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001524 /**
1525 * Get the {@link LinkProperties} for the given {@link Network}. This
1526 * will return {@code null} if the network is unknown.
1527 *
1528 * @param network The {@link Network} object identifying the network in question.
1529 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001530 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001531 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001532 @Nullable
1533 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001534 try {
1535 return mService.getLinkProperties(network);
1536 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001537 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001538 }
1539 }
1540
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001541 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001542 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001543 * will return {@code null} if the network is unknown.
1544 *
Roshan Pius7992afd2020-12-22 15:10:42 -08001545 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1546 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1547 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1548 * this location sensitive information (subject to app's location permissions) will be
1549 * noted by system. To include any location sensitive data in {@link TransportInfo},
1550 * use a {@link NetworkCallback} with
1551 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1552 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001553 * @param network The {@link Network} object identifying the network in question.
Roshan Pius7992afd2020-12-22 15:10:42 -08001554 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001555 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001556 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001557 @Nullable
1558 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001559 try {
Roshan Piusc97d8062020-12-17 14:53:09 -08001560 return mService.getNetworkCapabilities(
1561 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001562 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001563 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001564 }
1565 }
1566
Robert Greenwalt26744a52013-02-15 10:56:35 -08001567 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001568 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001569 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1570 * portal is present.
1571 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1572 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1573 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001574 * The system network validation may be using different strategies to detect captive portals,
1575 * so this method does not necessarily return a URL used by the system. It only returns a URL
1576 * that may be relevant for other components trying to detect captive portals.
paulhuec0a9632019-08-12 16:25:11 +08001577 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001578 * @hide
paulhuec0a9632019-08-12 16:25:11 +08001579 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1580 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001581 */
paulhuec0a9632019-08-12 16:25:11 +08001582 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001583 @SystemApi
paulhuec0a9632019-08-12 16:25:11 +08001584 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001585 public String getCaptivePortalServerUrl() {
1586 try {
1587 return mService.getCaptivePortalServerUrl();
1588 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001589 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001590 }
1591 }
1592
1593 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001594 * Tells the underlying networking system that the caller wants to
1595 * begin using the named feature. The interpretation of {@code feature}
1596 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001597 *
1598 * <p>This method requires the caller to hold either the
1599 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1600 * or the ability to modify system settings as determined by
1601 * {@link android.provider.Settings.System#canWrite}.</p>
1602 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001603 * @param networkType specifies which network the request pertains to
1604 * @param feature the name of the feature to be used
1605 * @return an integer value representing the outcome of the request.
1606 * The interpretation of this value is specific to each networking
1607 * implementation+feature combination, except that the value {@code -1}
1608 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001609 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001610 * @deprecated Deprecated in favor of the cleaner
1611 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001612 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001613 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001614 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001615 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001616 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001617 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001618 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001619 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1620 if (netCap == null) {
1621 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1622 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001623 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001624 }
1625
1626 NetworkRequest request = null;
1627 synchronized (sLegacyRequests) {
1628 LegacyRequest l = sLegacyRequests.get(netCap);
1629 if (l != null) {
1630 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1631 renewRequestLocked(l);
1632 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001633 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001634 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001635 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001636 }
1637 }
1638
1639 request = requestNetworkForFeatureLocked(netCap);
1640 }
1641 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001642 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001643 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001644 } else {
1645 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001646 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001647 }
1648 }
1649
1650 /**
1651 * Tells the underlying networking system that the caller is finished
1652 * using the named feature. The interpretation of {@code feature}
1653 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001654 *
1655 * <p>This method requires the caller to hold either the
1656 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1657 * or the ability to modify system settings as determined by
1658 * {@link android.provider.Settings.System#canWrite}.</p>
1659 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001660 * @param networkType specifies which network the request pertains to
1661 * @param feature the name of the feature that is no longer needed
1662 * @return an integer value representing the outcome of the request.
1663 * The interpretation of this value is specific to each networking
1664 * implementation+feature combination, except that the value {@code -1}
1665 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001666 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001667 * @deprecated Deprecated in favor of the cleaner
1668 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001669 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001670 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001671 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001672 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001673 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001674 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001675 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001676 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1677 if (netCap == null) {
1678 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1679 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001680 return -1;
1681 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001682
Paul Jensen034dea32014-12-17 10:39:34 -05001683 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001684 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001685 }
1686 return 1;
1687 }
1688
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001689 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001690 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1691 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001692 switch (feature) {
1693 case "enableCBS":
1694 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1695 case "enableDUN":
1696 case "enableDUNAlways":
1697 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1698 case "enableFOTA":
1699 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1700 case "enableHIPRI":
1701 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1702 case "enableIMS":
1703 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1704 case "enableMMS":
1705 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1706 case "enableSUPL":
1707 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1708 default:
1709 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001710 }
Erik Kline50068e52017-01-26 18:08:28 +09001711 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1712 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001713 }
1714 return null;
1715 }
1716
Robert Greenwalt5a367872014-06-02 15:32:02 -07001717 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001718 if (netCap == null) return TYPE_NONE;
1719 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1720 return TYPE_MOBILE_CBS;
1721 }
1722 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1723 return TYPE_MOBILE_IMS;
1724 }
1725 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1726 return TYPE_MOBILE_FOTA;
1727 }
1728 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1729 return TYPE_MOBILE_DUN;
1730 }
1731 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1732 return TYPE_MOBILE_SUPL;
1733 }
1734 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1735 return TYPE_MOBILE_MMS;
1736 }
1737 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1738 return TYPE_MOBILE_HIPRI;
1739 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001740 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1741 return TYPE_WIFI_P2P;
1742 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001743 return TYPE_NONE;
1744 }
1745
1746 private static class LegacyRequest {
1747 NetworkCapabilities networkCapabilities;
1748 NetworkRequest networkRequest;
1749 int expireSequenceNumber;
1750 Network currentNetwork;
1751 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001752
1753 private void clearDnsBinding() {
1754 if (currentNetwork != null) {
1755 currentNetwork = null;
1756 setProcessDefaultNetworkForHostResolution(null);
1757 }
1758 }
1759
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001760 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001761 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001762 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001763 currentNetwork = network;
1764 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001765 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001766 }
1767 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001768 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001769 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001770 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1771 }
1772 };
1773 }
1774
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001775 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001776 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1777 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001778
1779 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1780 synchronized (sLegacyRequests) {
1781 LegacyRequest l = sLegacyRequests.get(netCap);
1782 if (l != null) return l.networkRequest;
1783 }
1784 return null;
1785 }
1786
1787 private void renewRequestLocked(LegacyRequest l) {
1788 l.expireSequenceNumber++;
1789 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1790 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1791 }
1792
1793 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1794 int ourSeqNum = -1;
1795 synchronized (sLegacyRequests) {
1796 LegacyRequest l = sLegacyRequests.get(netCap);
1797 if (l == null) return;
1798 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001799 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001800 }
1801 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1802 }
1803
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001804 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001805 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1806 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001807 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001808 try {
1809 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001810 } catch (RemoteException e) {
1811 throw e.rethrowFromSystemServer();
1812 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001813 LegacyRequest l = new LegacyRequest();
1814 l.networkCapabilities = netCap;
1815 l.delay = delay;
1816 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001817 l.networkRequest = sendRequestForNetwork(
1818 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001819 if (l.networkRequest == null) return null;
1820 sLegacyRequests.put(netCap, l);
1821 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1822 return l.networkRequest;
1823 }
1824
1825 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1826 if (delay >= 0) {
1827 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001828 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001829 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1830 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001831 }
1832 }
1833
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001834 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001835 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1836 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001837 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001838 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001839 }
Paul Jensen034dea32014-12-17 10:39:34 -05001840 if (l == null) return false;
1841 unregisterNetworkCallback(l.networkCallback);
1842 l.clearDnsBinding();
1843 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001844 }
1845
Erik Kline50068e52017-01-26 18:08:28 +09001846 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1847 static {
1848 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1849 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1850 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1851 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1852 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1853 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1854 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1855 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1856 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1857 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1858 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1859 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1860 }
1861
1862 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1863 static {
1864 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1865 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1866 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1867 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1868 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1869 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1870 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1871 }
1872
1873 /**
1874 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1875 * instance suitable for registering a request or callback. Throws an
1876 * IllegalArgumentException if no mapping from the legacy type to
1877 * NetworkCapabilities is known.
1878 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001879 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1880 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001881 * @hide
1882 */
1883 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1884 final NetworkCapabilities nc = new NetworkCapabilities();
1885
1886 // Map from type to transports.
1887 final int NOT_FOUND = -1;
1888 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001889 if (transport == NOT_FOUND) {
1890 throw new IllegalArgumentException("unknown legacy type: " + type);
1891 }
Erik Kline50068e52017-01-26 18:08:28 +09001892 nc.addTransportType(transport);
1893
1894 // Map from type to capabilities.
1895 nc.addCapability(sLegacyTypeToCapability.get(
1896 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1897 nc.maybeMarkCapabilitiesRestricted();
1898 return nc;
1899 }
1900
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001901 /** @hide */
1902 public static class PacketKeepaliveCallback {
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001903 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayevfc03a992019-11-15 19:12:49 +00001904 public PacketKeepaliveCallback() {
1905 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001906 /** The requested keepalive was successfully started. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001907 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001908 public void onStarted() {}
1909 /** The keepalive was successfully stopped. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001910 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001911 public void onStopped() {}
1912 /** An error occurred. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001913 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001914 public void onError(int error) {}
1915 }
1916
1917 /**
1918 * Allows applications to request that the system periodically send specific packets on their
1919 * behalf, using hardware offload to save battery power.
1920 *
1921 * To request that the system send keepalives, call one of the methods that return a
1922 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1923 * passing in a non-null callback. If the callback is successfully started, the callback's
1924 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1925 * specifying one of the {@code ERROR_*} constants in this class.
1926 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001927 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1928 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1929 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001930 *
junyulaia86defc2018-12-27 17:25:29 +08001931 * @deprecated Use {@link SocketKeepalive} instead.
1932 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001933 * @hide
1934 */
1935 public class PacketKeepalive {
1936
1937 private static final String TAG = "PacketKeepalive";
1938
1939 /** @hide */
1940 public static final int SUCCESS = 0;
1941
1942 /** @hide */
1943 public static final int NO_KEEPALIVE = -1;
1944
1945 /** @hide */
1946 public static final int BINDER_DIED = -10;
1947
1948 /** The specified {@code Network} is not connected. */
1949 public static final int ERROR_INVALID_NETWORK = -20;
1950 /** The specified IP addresses are invalid. For example, the specified source IP address is
1951 * not configured on the specified {@code Network}. */
1952 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1953 /** The requested port is invalid. */
1954 public static final int ERROR_INVALID_PORT = -22;
1955 /** The packet length is invalid (e.g., too long). */
1956 public static final int ERROR_INVALID_LENGTH = -23;
1957 /** The packet transmission interval is invalid (e.g., too short). */
1958 public static final int ERROR_INVALID_INTERVAL = -24;
1959
1960 /** The hardware does not support this request. */
1961 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001962 /** The hardware returned an error. */
1963 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001964
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001965 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001966 public static final int NATT_PORT = 4500;
1967
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001968 /** The minimum interval in seconds between keepalive packet transmissions */
1969 public static final int MIN_INTERVAL = 10;
1970
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001971 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001972 private final ISocketKeepaliveCallback mCallback;
1973 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001974
1975 private volatile Integer mSlot;
1976
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001977 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001978 public void stop() {
1979 try {
junyulai9f872232019-01-16 20:23:34 +08001980 mExecutor.execute(() -> {
1981 try {
1982 if (mSlot != null) {
1983 mService.stopKeepalive(mNetwork, mSlot);
1984 }
1985 } catch (RemoteException e) {
1986 Log.e(TAG, "Error stopping packet keepalive: ", e);
1987 throw e.rethrowFromSystemServer();
1988 }
1989 });
1990 } catch (RejectedExecutionException e) {
1991 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001992 }
1993 }
1994
1995 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001996 Objects.requireNonNull(network, "network cannot be null");
1997 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001998 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08001999 mExecutor = Executors.newSingleThreadExecutor();
2000 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002001 @Override
junyulai9f872232019-01-16 20:23:34 +08002002 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08002003 final long token = Binder.clearCallingIdentity();
2004 try {
2005 mExecutor.execute(() -> {
2006 mSlot = slot;
2007 callback.onStarted();
2008 });
2009 } finally {
2010 Binder.restoreCallingIdentity(token);
2011 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002012 }
junyulai9f872232019-01-16 20:23:34 +08002013
2014 @Override
2015 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08002016 final long token = Binder.clearCallingIdentity();
2017 try {
2018 mExecutor.execute(() -> {
2019 mSlot = null;
2020 callback.onStopped();
2021 });
2022 } finally {
2023 Binder.restoreCallingIdentity(token);
2024 }
junyulai9f872232019-01-16 20:23:34 +08002025 mExecutor.shutdown();
2026 }
2027
2028 @Override
2029 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08002030 final long token = Binder.clearCallingIdentity();
2031 try {
2032 mExecutor.execute(() -> {
2033 mSlot = null;
2034 callback.onError(error);
2035 });
2036 } finally {
2037 Binder.restoreCallingIdentity(token);
2038 }
junyulai9f872232019-01-16 20:23:34 +08002039 mExecutor.shutdown();
2040 }
2041
2042 @Override
2043 public void onDataReceived() {
2044 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2045 // this callback when data is received.
2046 }
2047 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002048 }
2049 }
2050
2051 /**
2052 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2053 *
junyulaia86defc2018-12-27 17:25:29 +08002054 * @deprecated Use {@link #createSocketKeepalive} instead.
2055 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002056 * @hide
2057 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002058 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002059 public PacketKeepalive startNattKeepalive(
2060 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2061 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2062 final PacketKeepalive k = new PacketKeepalive(network, callback);
2063 try {
junyulai9f872232019-01-16 20:23:34 +08002064 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002065 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2066 } catch (RemoteException e) {
2067 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08002068 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002069 }
2070 return k;
2071 }
2072
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002073 // Construct an invalid fd.
2074 private ParcelFileDescriptor createInvalidFd() {
2075 final int invalidFd = -1;
2076 return ParcelFileDescriptor.adoptFd(invalidFd);
2077 }
2078
The Android Open Source Project28527d22009-03-03 19:31:44 -08002079 /**
junyulaia86defc2018-12-27 17:25:29 +08002080 * Request that keepalives be started on a IPsec NAT-T socket.
2081 *
2082 * @param network The {@link Network} the socket is on.
2083 * @param socket The socket that needs to be kept alive.
2084 * @param source The source address of the {@link UdpEncapsulationSocket}.
2085 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2086 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2087 * must run callback sequentially, otherwise the order of callbacks cannot be
2088 * guaranteed.
2089 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2090 * changes. Must be extended by applications that use this API.
2091 *
junyulaic7ea1242019-01-08 20:04:33 +08002092 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2093 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08002094 **/
junyulai61143782019-03-04 22:45:36 +08002095 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08002096 @NonNull UdpEncapsulationSocket socket,
2097 @NonNull InetAddress source,
2098 @NonNull InetAddress destination,
2099 @NonNull @CallbackExecutor Executor executor,
2100 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002101 ParcelFileDescriptor dup;
2102 try {
junyulaic4fb2482019-03-27 11:00:37 +08002103 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2104 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08002105 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2106 } catch (IOException ignored) {
2107 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2108 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002109 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002110 }
2111 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2112 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08002113 }
2114
2115 /**
2116 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2117 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2118 *
2119 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08002120 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2121 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2122 * from that port.
junyulai48a59382019-01-15 11:32:44 +08002123 * @param source The source address of the {@link UdpEncapsulationSocket}.
2124 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2125 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2126 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2127 * must run callback sequentially, otherwise the order of callbacks cannot be
2128 * guaranteed.
2129 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2130 * changes. Must be extended by applications that use this API.
2131 *
junyulaic7ea1242019-01-08 20:04:33 +08002132 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2133 * given socket.
junyulai48a59382019-01-15 11:32:44 +08002134 * @hide
2135 */
2136 @SystemApi
2137 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002138 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2139 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08002140 @NonNull InetAddress source,
2141 @NonNull InetAddress destination,
2142 @NonNull @CallbackExecutor Executor executor,
2143 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002144 ParcelFileDescriptor dup;
2145 try {
junyulaic4fb2482019-03-27 11:00:37 +08002146 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08002147 dup = pfd.dup();
2148 } catch (IOException ignored) {
2149 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2150 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002151 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002152 }
2153 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VAN642d6ab2021-03-11 10:56:49 +00002154 -1 /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08002155 }
2156
2157 /**
junyulaic7ea1242019-01-08 20:04:33 +08002158 * Request that keepalives be started on a TCP socket.
2159 * The socket must be established.
2160 *
2161 * @param network The {@link Network} the socket is on.
2162 * @param socket The socket that needs to be kept alive.
2163 * @param executor The executor on which callback will be invoked. This implementation assumes
2164 * the provided {@link Executor} runs the callbacks in sequence with no
2165 * concurrency. Failing this, no guarantee of correctness can be made. It is
2166 * the responsibility of the caller to ensure the executor provides this
2167 * guarantee. A simple way of creating such an executor is with the standard
2168 * tool {@code Executors.newSingleThreadExecutor}.
2169 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2170 * changes. Must be extended by applications that use this API.
2171 *
2172 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2173 * given socket.
2174 * @hide
2175 */
2176 @SystemApi
2177 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002178 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002179 @NonNull Socket socket,
2180 @NonNull Executor executor,
2181 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002182 ParcelFileDescriptor dup;
2183 try {
2184 dup = ParcelFileDescriptor.fromSocket(socket);
2185 } catch (UncheckedIOException ignored) {
2186 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2187 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002188 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002189 }
2190 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002191 }
2192
2193 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002194 * Ensure that a network route exists to deliver traffic to the specified
2195 * host via the specified network interface. An attempt to add a route that
2196 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002197 *
2198 * <p>This method requires the caller to hold either the
2199 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2200 * or the ability to modify system settings as determined by
2201 * {@link android.provider.Settings.System#canWrite}.</p>
2202 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002203 * @param networkType the type of the network over which traffic to the specified
2204 * host is to be routed
2205 * @param hostAddress the IP address of the host to which the route is desired
2206 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002207 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002208 * @deprecated Deprecated in favor of the
2209 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2210 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002211 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002212 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002213 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002214 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002215 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002216 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002217 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002218 }
2219
2220 /**
2221 * Ensure that a network route exists to deliver traffic to the specified
2222 * host via the specified network interface. An attempt to add a route that
2223 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002224 *
2225 * <p>This method requires the caller to hold either the
2226 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2227 * or the ability to modify system settings as determined by
2228 * {@link android.provider.Settings.System#canWrite}.</p>
2229 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002230 * @param networkType the type of the network over which traffic to the specified
2231 * host is to be routed
2232 * @param hostAddress the IP address of the host to which the route is desired
2233 * @return {@code true} on success, {@code false} on failure
2234 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002235 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002236 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002237 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002238 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002239 @UnsupportedAppUsage
lucaslin5140e482021-03-22 11:51:27 +08002240 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002241 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002242 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002243 try {
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002244 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2245 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002246 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002247 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002248 }
2249 }
2250
2251 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002252 * @return the context's attribution tag
2253 */
2254 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2255 private @Nullable String getAttributionTag() {
2256 return mContext.getAttributionTag();
2257 }
2258
2259 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002260 * Returns the value of the setting for background data usage. If false,
2261 * applications should not use the network if the application is not in the
2262 * foreground. Developers should respect this setting, and check the value
2263 * of this before performing any background data operations.
2264 * <p>
2265 * All applications that have background services that use the network
2266 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002267 * <p>
Scott Main50589142011-10-06 18:32:43 -07002268 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002269 * background data depends on several combined factors, and this method will
2270 * always return {@code true}. Instead, when background data is unavailable,
2271 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002272 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002273 * @return Whether background data usage is allowed.
2274 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002275 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002276 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002277 // assume that background data is allowed; final authority is
2278 // NetworkInfo which may be blocked.
2279 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002280 }
2281
2282 /**
2283 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002284 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002285 * @param allowBackgroundData Whether an application should use data while
2286 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002287 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002288 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2289 * @see #getBackgroundDataSetting()
2290 * @hide
2291 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002292 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002293 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002294 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002295 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002296 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002297
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002298 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002299 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002300 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002301 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002302 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002303 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002304 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002305 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2306 if (tm != null) {
2307 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2308 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2309 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2310 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2311 + " retVal=" + retVal);
2312 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002313 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002314 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002315 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002316 }
2317
The Android Open Source Project28527d22009-03-03 19:31:44 -08002318 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002319 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002320 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002321 */
2322 public interface OnNetworkActiveListener {
2323 /**
2324 * Called on the main thread of the process to report that the current data network
2325 * has become active, and it is now a good time to perform any pending network
2326 * operations. Note that this listener only tells you when the network becomes
2327 * active; if at any other time you want to know whether it is active (and thus okay
2328 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002329 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002330 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002331 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002332 }
2333
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002334 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002335 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002336
2337 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002338 * Start listening to reports when the system's default data network is active, meaning it is
2339 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2340 * to determine the current state of the system's default network after registering the
2341 * listener.
2342 * <p>
2343 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002344 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002345 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002346 *
2347 * @param l The listener to be told when the network is active.
2348 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002349 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002350 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2351 @Override
2352 public void onNetworkActive() throws RemoteException {
2353 l.onNetworkActive();
2354 }
2355 };
2356
2357 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002358 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002359 mNetworkActivityListeners.put(l, rl);
2360 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002361 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002362 }
2363 }
2364
2365 /**
2366 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002367 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002368 *
2369 * @param l Previously registered listener.
2370 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002371 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002372 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002373 if (rl == null) {
2374 throw new IllegalArgumentException("Listener was not registered.");
2375 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002376 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002377 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002378 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002379 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002380 }
2381 }
2382
2383 /**
2384 * Return whether the data network is currently active. An active network means that
2385 * it is currently in a high power state for performing data transmission. On some
2386 * types of networks, it may be expensive to move and stay in such a state, so it is
2387 * more power efficient to batch network traffic together when the radio is already in
2388 * this state. This method tells you whether right now is currently a good time to
2389 * initiate network traffic, as the network is already active.
2390 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002391 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002392 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002393 return mService.isDefaultNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002394 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002395 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002396 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002397 }
2398
2399 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002400 * {@hide}
2401 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002402 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002403 mContext = Objects.requireNonNull(context, "missing context");
2404 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002405 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002406 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002407 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002408
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002409 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002410 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002411 public static ConnectivityManager from(Context context) {
2412 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2413 }
2414
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002415 /** @hide */
2416 public NetworkRequest getDefaultRequest() {
2417 try {
2418 // This is not racy as the default request is final in ConnectivityService.
2419 return mService.getDefaultRequest();
2420 } catch (RemoteException e) {
2421 throw e.rethrowFromSystemServer();
2422 }
2423 }
2424
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002425 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002426 * Check if the package is a allowed to write settings. This also accounts that such an access
2427 * happened.
2428 *
2429 * @return {@code true} iff the package is allowed to write settings.
2430 */
2431 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2432 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2433 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2434 boolean throwException) {
2435 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2436 callingAttributionTag, throwException);
2437 }
2438
2439 /**
Paul Jensen12131352014-12-10 15:12:18 -05002440 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2441 * situations where a Context pointer is unavailable.
2442 * @hide
2443 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002444 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002445 static ConnectivityManager getInstanceOrNull() {
2446 return sInstance;
2447 }
2448
2449 /**
2450 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2451 * situations where a Context pointer is unavailable.
2452 * @hide
2453 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002454 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002455 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002456 private static ConnectivityManager getInstance() {
2457 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002458 throw new IllegalStateException("No ConnectivityManager yet constructed");
2459 }
Paul Jensen895c3942015-03-10 10:54:12 -04002460 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002461 }
2462
2463 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002464 * Get the set of tetherable, available interfaces. This list is limited by
2465 * device configuration and current interface existence.
2466 *
2467 * @return an array of 0 or more Strings of tetherable interface names.
2468 *
markchien75721e42020-01-21 13:11:06 +08002469 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002470 * {@hide}
2471 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002472 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002473 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002474 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002475 public String[] getTetherableIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002476 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002477 }
2478
2479 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002480 * Get the set of tethered interfaces.
2481 *
2482 * @return an array of 0 or more String of currently tethered interface names.
2483 *
markchien75721e42020-01-21 13:11:06 +08002484 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002485 * {@hide}
2486 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002487 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002488 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002489 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002490 public String[] getTetheredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002491 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002492 }
2493
2494 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002495 * Get the set of interface names which attempted to tether but
2496 * failed. Re-attempting to tether may cause them to reset to the Tethered
2497 * state. Alternatively, causing the interface to be destroyed and recreated
2498 * may cause them to reset to the available state.
2499 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2500 * information on the cause of the errors.
2501 *
2502 * @return an array of 0 or more String indicating the interface names
2503 * which failed to tether.
2504 *
markchien75721e42020-01-21 13:11:06 +08002505 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002506 * {@hide}
2507 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002508 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002509 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002510 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002511 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002512 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002513 }
2514
2515 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002516 * Get the set of tethered dhcp ranges.
2517 *
markchien9e046242020-02-06 19:23:26 +08002518 * @deprecated This method is not supported.
2519 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002520 * {@hide}
2521 */
paulhuec0a9632019-08-12 16:25:11 +08002522 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien75721e42020-01-21 13:11:06 +08002523 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002524 public String[] getTetheredDhcpRanges() {
markchien9e046242020-02-06 19:23:26 +08002525 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002526 }
2527
2528 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002529 * Attempt to tether the named interface. This will setup a dhcp server
2530 * on the interface, forward and NAT IP packets and forward DNS requests
2531 * to the best active upstream network interface. Note that if no upstream
2532 * IP network interface is available, dhcp will still run and traffic will be
2533 * allowed between the tethered devices and this device, though upstream net
2534 * access will of course fail until an upstream network interface becomes
2535 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002536 *
2537 * <p>This method requires the caller to hold either the
2538 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2539 * or the ability to modify system settings as determined by
2540 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002541 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002542 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2543 * and WifiStateMachine which need direct access. All other clients should use
2544 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2545 * logic.</p>
2546 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002547 * @param iface the interface name to tether.
2548 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002549 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002550 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002551 * {@hide}
2552 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002553 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien10ddd022020-01-20 19:31:56 +08002554 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002555 public int tether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002556 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002557 }
2558
2559 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002560 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002561 *
2562 * <p>This method requires the caller to hold either the
2563 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2564 * or the ability to modify system settings as determined by
2565 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002566 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002567 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2568 * and WifiStateMachine which need direct access. All other clients should use
2569 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2570 * logic.</p>
2571 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002572 * @param iface the interface name to untether.
2573 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2574 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002575 * {@hide}
2576 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002577 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002578 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002579 public int untether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002580 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002581 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002582
2583 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002584 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002585 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002586 * due to device configuration.
2587 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002588 * <p>If this app does not have permission to use this API, it will always
2589 * return false rather than throw an exception.</p>
2590 *
2591 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2592 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2593 *
2594 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2595 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2596 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002597 * @return a boolean - {@code true} indicating Tethering is supported.
2598 *
markchien75721e42020-01-21 13:11:06 +08002599 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002600 * {@hide}
2601 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002602 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002603 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2604 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002605 public boolean isTetheringSupported() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002606 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002607 }
2608
2609 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002610 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien10ddd022020-01-20 19:31:56 +08002611 *
2612 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002613 * @hide
2614 */
2615 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002616 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002617 public static abstract class OnStartTetheringCallback {
2618 /**
2619 * Called when tethering has been successfully started.
2620 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002621 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002622
2623 /**
2624 * Called when starting tethering failed.
2625 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002626 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002627 }
2628
2629 /**
2630 * Convenient overload for
2631 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2632 * handler to run on the current thread's {@link Looper}.
markchien10ddd022020-01-20 19:31:56 +08002633 *
2634 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002635 * @hide
2636 */
2637 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002638 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002639 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002640 public void startTethering(int type, boolean showProvisioningUi,
2641 final OnStartTetheringCallback callback) {
2642 startTethering(type, showProvisioningUi, callback, null);
2643 }
2644
2645 /**
2646 * Runs tether provisioning for the given type if needed and then starts tethering if
2647 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2648 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2649 * schedules tether provisioning re-checks if appropriate.
2650 *
2651 * @param type The type of tethering to start. Must be one of
2652 * {@link ConnectivityManager.TETHERING_WIFI},
2653 * {@link ConnectivityManager.TETHERING_USB}, or
2654 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2655 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2656 * is one. This should be true the first time this function is called and also any time
2657 * the user can see this UI. It gives users information from their carrier about the
2658 * check failing and how they can sign up for tethering if possible.
2659 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2660 * of the result of trying to tether.
2661 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien10ddd022020-01-20 19:31:56 +08002662 *
2663 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002664 * @hide
2665 */
2666 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002667 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002668 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002669 public void startTethering(int type, boolean showProvisioningUi,
2670 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002671 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002672
markchien10ddd022020-01-20 19:31:56 +08002673 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002674 @Override
markchien10ddd022020-01-20 19:31:56 +08002675 public void execute(Runnable command) {
2676 if (handler == null) {
2677 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002678 } else {
markchien10ddd022020-01-20 19:31:56 +08002679 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002680 }
2681 }
2682 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002683
markchien10ddd022020-01-20 19:31:56 +08002684 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2685 @Override
2686 public void onTetheringStarted() {
2687 callback.onTetheringStarted();
2688 }
2689
2690 @Override
markchien68b67842020-03-19 13:37:43 +08002691 public void onTetheringFailed(final int error) {
markchien10ddd022020-01-20 19:31:56 +08002692 callback.onTetheringFailed();
2693 }
2694 };
2695
2696 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien68b67842020-03-19 13:37:43 +08002697 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien10ddd022020-01-20 19:31:56 +08002698
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002699 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002700 }
2701
2702 /**
2703 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2704 * applicable.
2705 *
2706 * @param type The type of tethering to stop. Must be one of
2707 * {@link ConnectivityManager.TETHERING_WIFI},
2708 * {@link ConnectivityManager.TETHERING_USB}, or
2709 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien75721e42020-01-21 13:11:06 +08002710 *
2711 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002712 * @hide
2713 */
2714 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002715 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002716 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002717 public void stopTethering(int type) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002718 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002719 }
2720
2721 /**
markchiena005c992019-02-27 14:56:11 +08002722 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2723 * upstream status.
2724 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002725 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien75721e42020-01-21 13:11:06 +08002726 * @hide
markchiena005c992019-02-27 14:56:11 +08002727 */
2728 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002729 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002730 public abstract static class OnTetheringEventCallback {
2731
2732 /**
2733 * Called when tethering upstream changed. This can be called multiple times and can be
2734 * called any time.
2735 *
2736 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2737 * have any upstream.
2738 */
2739 public void onUpstreamChanged(@Nullable Network network) {}
2740 }
2741
markchien75721e42020-01-21 13:11:06 +08002742 @GuardedBy("mTetheringEventCallbacks")
2743 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2744 mTetheringEventCallbacks = new ArrayMap<>();
2745
markchiena005c992019-02-27 14:56:11 +08002746 /**
2747 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002748 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002749 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2750 * with a null argument. The same callback object cannot be registered twice.
2751 *
2752 * @param executor the executor on which callback will be invoked.
2753 * @param callback the callback to be called when tethering has change events.
markchien75721e42020-01-21 13:11:06 +08002754 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002755 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002756 * @hide
2757 */
2758 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002759 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002760 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2761 public void registerTetheringEventCallback(
2762 @NonNull @CallbackExecutor Executor executor,
2763 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002764 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchiena005c992019-02-27 14:56:11 +08002765
markchien75721e42020-01-21 13:11:06 +08002766 final TetheringEventCallback tetherCallback =
2767 new TetheringEventCallback() {
2768 @Override
2769 public void onUpstreamChanged(@Nullable Network network) {
2770 callback.onUpstreamChanged(network);
2771 }
2772 };
2773
2774 synchronized (mTetheringEventCallbacks) {
2775 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002776 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002777 }
markchiena005c992019-02-27 14:56:11 +08002778 }
2779
2780 /**
2781 * Remove tethering event callback previously registered with
2782 * {@link #registerTetheringEventCallback}.
2783 *
2784 * @param callback previously registered callback.
markchien75721e42020-01-21 13:11:06 +08002785 *
2786 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002787 * @hide
2788 */
2789 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002790 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002791 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2792 public void unregisterTetheringEventCallback(
2793 @NonNull final OnTetheringEventCallback callback) {
markchien75721e42020-01-21 13:11:06 +08002794 Objects.requireNonNull(callback, "The callback must be non-null");
2795 synchronized (mTetheringEventCallbacks) {
2796 final TetheringEventCallback tetherCallback =
2797 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002798 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002799 }
markchiena005c992019-02-27 14:56:11 +08002800 }
2801
2802
2803 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002804 * Get the list of regular expressions that define any tetherable
2805 * USB network interfaces. If USB tethering is not supported by the
2806 * device, this list should be empty.
2807 *
2808 * @return an array of 0 or more regular expression Strings defining
2809 * what interfaces are considered tetherable usb interfaces.
2810 *
markchien75721e42020-01-21 13:11:06 +08002811 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002812 * {@hide}
2813 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002814 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002815 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002816 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002817 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002818 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002819 }
2820
2821 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002822 * Get the list of regular expressions that define any tetherable
2823 * Wifi network interfaces. If Wifi tethering is not supported by the
2824 * device, this list should be empty.
2825 *
2826 * @return an array of 0 or more regular expression Strings defining
2827 * what interfaces are considered tetherable wifi interfaces.
2828 *
markchien75721e42020-01-21 13:11:06 +08002829 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002830 * {@hide}
2831 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002832 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002833 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002834 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002835 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002836 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002837 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002838
Danica Chang96567052010-08-11 14:54:43 -07002839 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002840 * Get the list of regular expressions that define any tetherable
2841 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2842 * device, this list should be empty.
2843 *
2844 * @return an array of 0 or more regular expression Strings defining
2845 * what interfaces are considered tetherable bluetooth interfaces.
2846 *
markchien75721e42020-01-21 13:11:06 +08002847 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2848 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002849 * {@hide}
2850 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002851 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002852 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002853 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002854 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002855 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002856 }
2857
Mike Lockwooded4a1742011-07-19 13:04:47 -07002858 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002859 * Attempt to both alter the mode of USB and Tethering of USB. A
2860 * utility method to deal with some of the complexity of USB - will
2861 * attempt to switch to Rndis and subsequently tether the resulting
2862 * interface on {@code true} or turn off tethering and switch off
2863 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002864 *
2865 * <p>This method requires the caller to hold either the
2866 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2867 * or the ability to modify system settings as determined by
2868 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002869 *
2870 * @param enable a boolean - {@code true} to enable tethering
2871 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002872 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002873 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002874 * {@hide}
2875 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002876 @UnsupportedAppUsage
markchien10ddd022020-01-20 19:31:56 +08002877 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002878 public int setUsbTethering(boolean enable) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002879 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002880 }
2881
markchien75721e42020-01-21 13:11:06 +08002882 /**
2883 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2884 * {@hide}
2885 */
markchien5bd499c2019-01-16 17:44:13 +08002886 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002887 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002888 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien75721e42020-01-21 13:11:06 +08002889 /**
2890 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2891 * {@hide}
2892 */
2893 @Deprecated
2894 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2895 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2896 /**
2897 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2898 * {@hide}
2899 */
2900 @Deprecated
2901 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2902 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2903 /**
2904 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2905 * {@hide}
2906 */
2907 @Deprecated
2908 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2909 /**
2910 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2911 * {@hide}
2912 */
2913 @Deprecated
2914 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2915 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2916 /**
markchien68b67842020-03-19 13:37:43 +08002917 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002918 * {@hide}
2919 */
2920 @Deprecated
markchien68b67842020-03-19 13:37:43 +08002921 public static final int TETHER_ERROR_MASTER_ERROR =
2922 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien75721e42020-01-21 13:11:06 +08002923 /**
2924 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2925 * {@hide}
2926 */
2927 @Deprecated
2928 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2929 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2930 /**
2931 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2932 * {@hide}
2933 */
2934 @Deprecated
2935 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2936 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2937 /**
markchien68b67842020-03-19 13:37:43 +08002938 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002939 * {@hide}
2940 */
2941 @Deprecated
2942 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002943 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002944 /**
markchien68b67842020-03-19 13:37:43 +08002945 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002946 * {@hide}
2947 */
2948 @Deprecated
2949 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002950 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002951 /**
2952 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2953 * {@hide}
2954 */
2955 @Deprecated
2956 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2957 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2958 /**
markchien68b67842020-03-19 13:37:43 +08002959 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien75721e42020-01-21 13:11:06 +08002960 * {@hide}
2961 */
markchien5bd499c2019-01-16 17:44:13 +08002962 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002963 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002964 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien75721e42020-01-21 13:11:06 +08002965 /**
2966 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2967 * {@hide}
2968 */
2969 @Deprecated
2970 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2971 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2972 /**
2973 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2974 * {@hide}
2975 */
markchien5bd499c2019-01-16 17:44:13 +08002976 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002977 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002978 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002979
2980 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002981 * Get a more detailed error code after a Tethering or Untethering
2982 * request asynchronously failed.
2983 *
2984 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002985 * @return error The error code of the last error tethering or untethering the named
2986 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002987 *
markchien75721e42020-01-21 13:11:06 +08002988 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002989 * {@hide}
2990 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002991 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002992 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien75721e42020-01-21 13:11:06 +08002993 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002994 public int getLastTetherError(String iface) {
markchien68b67842020-03-19 13:37:43 +08002995 int error = mTetheringManager.getLastTetherError(iface);
2996 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2997 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2998 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2999 // instead.
3000 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3001 }
3002 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003003 }
3004
markchiendd41c822019-03-06 16:25:00 +08003005 /** @hide */
3006 @Retention(RetentionPolicy.SOURCE)
3007 @IntDef(value = {
3008 TETHER_ERROR_NO_ERROR,
3009 TETHER_ERROR_PROVISION_FAILED,
3010 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3011 })
3012 public @interface EntitlementResultCode {
3013 }
3014
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003015 /**
markchiendd41c822019-03-06 16:25:00 +08003016 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08003017 * entitlement succeeded.
markchien75721e42020-01-21 13:11:06 +08003018 *
3019 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08003020 * @hide
3021 */
3022 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003023 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08003024 public interface OnTetheringEntitlementResultListener {
3025 /**
3026 * Called to notify entitlement result.
3027 *
3028 * @param resultCode an int value of entitlement result. It may be one of
3029 * {@link #TETHER_ERROR_NO_ERROR},
3030 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3031 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3032 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07003033 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08003034 }
3035
3036 /**
markchien5bd499c2019-01-16 17:44:13 +08003037 * Get the last value of the entitlement check on this downstream. If the cached value is
3038 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3039 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3040 * guaranteed that the UI-based entitlement check will complete in any specific time period
3041 * and may in fact never complete. Any successful entitlement check the platform performs for
3042 * any reason will update the cached value.
3043 *
3044 * @param type the downstream type of tethering. Must be one of
3045 * {@link #TETHERING_WIFI},
3046 * {@link #TETHERING_USB}, or
3047 * {@link #TETHERING_BLUETOOTH}.
3048 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08003049 * @param executor the executor on which callback will be invoked.
3050 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3051 * notify the caller of the result of entitlement check. The listener may be called zero
3052 * or one time.
markchien75721e42020-01-21 13:11:06 +08003053 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08003054 * {@hide}
3055 */
3056 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003057 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08003058 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08003059 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3060 @NonNull @CallbackExecutor Executor executor,
3061 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003062 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchiendd41c822019-03-06 16:25:00 +08003063 ResultReceiver wrappedListener = new ResultReceiver(null) {
3064 @Override
3065 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslin9cc04192021-03-04 09:38:21 +08003066 final long token = Binder.clearCallingIdentity();
3067 try {
3068 executor.execute(() -> {
3069 listener.onTetheringEntitlementResult(resultCode);
3070 });
3071 } finally {
3072 Binder.restoreCallingIdentity(token);
3073 }
markchiendd41c822019-03-06 16:25:00 +08003074 }
3075 };
3076
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00003077 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienb0bb7862019-12-16 20:15:20 +08003078 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08003079 }
3080
3081 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003082 * Report network connectivity status. This is currently used only
3083 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003084 * <p>This method requires the caller to hold the permission
3085 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003086 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003087 * @param networkType The type of network you want to report on
3088 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09003089 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003090 * {@hide}
3091 */
3092 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003093 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003094 try {
3095 mService.reportInetCondition(networkType, percentage);
3096 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003097 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003098 }
3099 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003100
3101 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003102 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07003103 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003104 * the framework to re-evaluate network connectivity and/or switch to another
3105 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003106 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003107 * @param network The {@link Network} the application was attempting to use
3108 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04003109 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3110 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003111 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003112 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09003113 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003114 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003115 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04003116 // One of these will be ignored because it matches system's current state.
3117 // The other will trigger the necessary reevaluation.
3118 mService.reportNetworkConnectivity(network, true);
3119 mService.reportNetworkConnectivity(network, false);
3120 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003121 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003122 }
3123 }
3124
3125 /**
3126 * Report to the framework whether a network has working connectivity.
3127 * This provides a hint to the system that a particular network is providing
3128 * working connectivity or not. In response the framework may re-evaluate
3129 * the network's connectivity and might take further action thereafter.
3130 *
3131 * @param network The {@link Network} the application was attempting to use
3132 * or {@code null} to indicate the current default network.
3133 * @param hasConnectivity {@code true} if the application was able to successfully access the
3134 * Internet using {@code network} or {@code false} if not.
3135 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003136 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003137 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003138 try {
3139 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003140 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003141 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003142 }
3143 }
3144
3145 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003146 * Set a network-independent global http proxy. This is not normally what you want
3147 * for typical HTTP proxies - they are general network dependent. However if you're
3148 * doing something unusual like general internal filtering this may be useful. On
3149 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003150 *
3151 * @param p A {@link ProxyInfo} object defining the new global
3152 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003153 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003154 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003155 @SystemApi(client = MODULE_LIBRARIES)
paulhuec0a9632019-08-12 16:25:11 +08003156 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003157 public void setGlobalProxy(@Nullable ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003158 try {
3159 mService.setGlobalProxy(p);
3160 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003161 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003162 }
3163 }
3164
3165 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003166 * Retrieve any network-independent global HTTP proxy.
3167 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003168 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003169 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003170 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003171 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003172 @SystemApi(client = MODULE_LIBRARIES)
3173 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04003174 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003175 try {
3176 return mService.getGlobalProxy();
3177 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003178 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003179 }
3180 }
3181
3182 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003183 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3184 * network-specific HTTP proxy. If {@code network} is null, the
3185 * network-specific proxy returned is the proxy of the default active
3186 * network.
3187 *
3188 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3189 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3190 * or when {@code network} is {@code null},
3191 * the {@code ProxyInfo} for the default active network. Returns
3192 * {@code null} when no proxy applies or the caller doesn't have
3193 * permission to use {@code network}.
3194 * @hide
3195 */
3196 public ProxyInfo getProxyForNetwork(Network network) {
3197 try {
3198 return mService.getProxyForNetwork(network);
3199 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003200 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003201 }
3202 }
3203
3204 /**
Paul Jensen12131352014-12-10 15:12:18 -05003205 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3206 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003207 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003208 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003209 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003210 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003211 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003212 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003213 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003214 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003215 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003216 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003217
3218 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003219 * Returns true if the hardware supports the given network type
3220 * else it returns false. This doesn't indicate we have coverage
3221 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003222 * hardware supports it. For example a GSM phone without a SIM
3223 * should still return {@code true} for mobile data, but a wifi only
3224 * tablet would return {@code false}.
3225 *
3226 * @param networkType The network type we'd like to check
3227 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003228 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003229 * @hide
3230 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003231 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003232 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003233 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003234 public boolean isNetworkSupported(int networkType) {
3235 try {
3236 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003237 } catch (RemoteException e) {
3238 throw e.rethrowFromSystemServer();
3239 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003240 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003241
3242 /**
3243 * Returns if the currently active data network is metered. A network is
3244 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003245 * that connection due to monetary costs, data limitations or
3246 * battery/performance issues. You should check this before doing large
3247 * data transfers, and warn the user or delay the operation until another
3248 * network is available.
3249 *
3250 * @return {@code true} if large transfers should be avoided, otherwise
3251 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003252 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003253 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003254 public boolean isActiveNetworkMetered() {
3255 try {
3256 return mService.isActiveNetworkMetered();
3257 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003258 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003259 }
3260 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003261
Robert Greenwalt26744a52013-02-15 10:56:35 -08003262 /**
Sarah Chincab74db2020-11-25 12:15:14 -08003263 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003264 *
Sarah Chincab74db2020-11-25 12:15:14 -08003265 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003266 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003267 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003268 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003269 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003270 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003271 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003272 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003273 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003274 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003275 }
3276 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003277
3278 /**
3279 * Set the value for enabling/disabling airplane mode
3280 *
3281 * @param enable whether to enable airplane mode or not
3282 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003283 * @hide
3284 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003285 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003286 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003287 android.Manifest.permission.NETWORK_SETTINGS,
3288 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3289 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003290 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003291 public void setAirplaneMode(boolean enable) {
3292 try {
3293 mService.setAirplaneMode(enable);
3294 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003295 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003296 }
3297 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003298
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003299 /**
3300 * Registers the specified {@link NetworkProvider}.
3301 * Each listener must only be registered once. The listener can be unregistered with
3302 * {@link #unregisterNetworkProvider}.
3303 *
3304 * @param provider the provider to register
3305 * @return the ID of the provider. This ID must be used by the provider when registering
3306 * {@link android.net.NetworkAgent}s.
3307 * @hide
3308 */
3309 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003310 @RequiresPermission(anyOf = {
3311 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3312 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003313 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3314 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003315 throw new IllegalStateException("NetworkProviders can only be registered once");
3316 }
3317
3318 try {
3319 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3320 provider.getName());
3321 provider.setProviderId(providerId);
3322 } catch (RemoteException e) {
3323 throw e.rethrowFromSystemServer();
3324 }
3325 return provider.getProviderId();
3326 }
3327
3328 /**
3329 * Unregisters the specified NetworkProvider.
3330 *
3331 * @param provider the provider to unregister
3332 * @hide
3333 */
3334 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003335 @RequiresPermission(anyOf = {
3336 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3337 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003338 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3339 try {
3340 mService.unregisterNetworkProvider(provider.getMessenger());
3341 } catch (RemoteException e) {
3342 throw e.rethrowFromSystemServer();
3343 }
3344 provider.setProviderId(NetworkProvider.ID_NONE);
3345 }
3346
Chalard Jean1ef1d902021-01-05 08:40:09 +09003347 /**
3348 * Register or update a network offer with ConnectivityService.
3349 *
3350 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jeand7268cd2021-03-24 17:43:10 +09003351 * them to networking requests made by apps or the system. A callback identifies an offer
3352 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3353 * score and the capabilities of the network it might be able to bring up ; these act as
3354 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jean1ef1d902021-01-05 08:40:09 +09003355 * provider.
3356 *
3357 * The provider is under no obligation to be able to bring up the network it offers at any
3358 * given time. Instead, this mechanism is meant to limit requests received by providers
3359 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3360 * the quality of the network satisfying a given request to their own offer.
3361 *
3362 * An offer can be updated by calling this again with the same callback object. This is
3363 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3364 * provider with the changes caused by the changes in the offer.
3365 *
3366 * @param provider The provider making this offer.
3367 * @param score The prospective score of the network.
3368 * @param caps The prospective capabilities of the network.
3369 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003370 * @hide exposed via the NetworkProvider class.
Chalard Jean1ef1d902021-01-05 08:40:09 +09003371 */
3372 @RequiresPermission(anyOf = {
3373 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3374 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanb004da52021-03-22 22:44:02 +09003375 public void offerNetwork(@NonNull final int providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09003376 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3377 @NonNull final INetworkOfferCallback callback) {
3378 try {
Chalard Jeanb004da52021-03-22 22:44:02 +09003379 mService.offerNetwork(providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09003380 Objects.requireNonNull(score, "null score"),
3381 Objects.requireNonNull(caps, "null caps"),
3382 Objects.requireNonNull(callback, "null callback"));
3383 } catch (RemoteException e) {
3384 throw e.rethrowFromSystemServer();
3385 }
3386 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003387
Chalard Jean1ef1d902021-01-05 08:40:09 +09003388 /**
3389 * Withdraw a network offer made with {@link #offerNetwork}.
3390 *
3391 * @param callback The callback passed at registration time. This must be the same object
3392 * that was passed to {@link #offerNetwork}
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003393 * @hide exposed via the NetworkProvider class.
Chalard Jean1ef1d902021-01-05 08:40:09 +09003394 */
3395 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3396 try {
3397 mService.unofferNetwork(Objects.requireNonNull(callback));
3398 } catch (RemoteException e) {
3399 throw e.rethrowFromSystemServer();
3400 }
3401 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003402 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003403 @RequiresPermission(anyOf = {
3404 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3405 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003406 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3407 try {
3408 mService.declareNetworkRequestUnfulfillable(request);
3409 } catch (RemoteException e) {
3410 throw e.rethrowFromSystemServer();
3411 }
3412 }
3413
Paul Jensenc2569432015-02-13 14:18:39 -05003414 /**
3415 * @hide
3416 * Register a NetworkAgent with ConnectivityService.
Chalard Jean1aea87a2019-12-13 19:47:12 +09003417 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003418 */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003419 @RequiresPermission(anyOf = {
3420 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3421 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003422 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeandd753522020-12-21 18:36:52 +09003423 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3424 int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003425 try {
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003426 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003427 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003428 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003429 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003430 }
3431
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003432 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003433 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3434 * changes. Should be extended by applications wanting notifications.
3435 *
3436 * A {@code NetworkCallback} is registered by calling
3437 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3438 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003439 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003440 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3441 * A {@code NetworkCallback} should be registered at most once at any time.
3442 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003443 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003444 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003445 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003446 * No flags associated with this callback.
3447 * @hide
3448 */
3449 public static final int FLAG_NONE = 0;
3450 /**
3451 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3452 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3453 * <p>
3454 * These include:
3455 * <li> Some transport info instances (retrieved via
3456 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3457 * contain location sensitive information.
3458 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3459 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3460 * </p>
3461 * <p>
3462 * Note:
3463 * <li> Retrieving this location sensitive information (subject to app's location
3464 * permissions) will be noted by system. </li>
3465 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3466 * not include location sensitive info.
3467 * </p>
3468 */
3469 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3470
3471 /** @hide */
3472 @Retention(RetentionPolicy.SOURCE)
3473 @IntDef(flag = true, prefix = "FLAG_", value = {
3474 FLAG_NONE,
3475 FLAG_INCLUDE_LOCATION_INFO
3476 })
3477 public @interface Flag { }
3478
3479 /**
3480 * All the valid flags for error checking.
3481 */
3482 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3483
3484 public NetworkCallback() {
3485 this(FLAG_NONE);
3486 }
3487
3488 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003489 if ((flags & VALID_FLAGS) != flags) {
3490 throw new IllegalArgumentException("Invalid flags");
3491 }
Roshan Pius7992afd2020-12-22 15:10:42 -08003492 mFlags = flags;
3493 }
3494
3495 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003496 * Called when the framework connects to a new network to evaluate whether it satisfies this
3497 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3498 * callback. There is no guarantee that this new network will satisfy any requests, or that
3499 * the network will stay connected for longer than the time necessary to evaluate it.
3500 * <p>
3501 * Most applications <b>should not</b> act on this callback, and should instead use
3502 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3503 * the framework in properly evaluating the network &mdash; for example, an application that
3504 * can automatically log in to a captive portal without user intervention.
3505 *
3506 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003507 *
3508 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003509 */
paulhua9a6e2a2019-03-22 16:35:06 +08003510 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003511
3512 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003513 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003514 * This callback may be called more than once if the {@link Network} that is
3515 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003516 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003517 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003518 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3519 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003520 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003521 * @hide
3522 */
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003523 public final void onAvailable(@NonNull Network network,
paulhua9a6e2a2019-03-22 16:35:06 +08003524 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003525 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003526 // Internally only this method is called when a new network is available, and
3527 // it calls the callback in the same way and order that older versions used
3528 // to call so as not to change the behavior.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003529 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3530 onBlockedStatusChanged(network, blocked);
3531 }
3532
3533 /**
3534 * Legacy variant of onAvailable that takes a boolean blocked reason.
3535 *
3536 * This method has never been public API, but it's not final, so there may be apps that
3537 * implemented it and rely on it being called. Do our best not to break them.
3538 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3539 * this method is called. There does not seem to be a way to avoid this.
3540 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3541 *
3542 * @hide
3543 */
3544 public void onAvailable(@NonNull Network network,
3545 @NonNull NetworkCapabilities networkCapabilities,
3546 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003547 onAvailable(network);
3548 if (!networkCapabilities.hasCapability(
3549 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3550 onNetworkSuspended(network);
3551 }
3552 onCapabilitiesChanged(network, networkCapabilities);
3553 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003554 // No call to onBlockedStatusChanged here. That is done by the caller.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003555 }
3556
3557 /**
3558 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003559 *
3560 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3561 * be available at the same time, and onAvailable will be called for each of these as they
3562 * appear.
3563 *
3564 * <p>For callbacks registered with {@link #requestNetwork} and
3565 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3566 * is the new best network for this request and is now tracked by this callback ; this
3567 * callback will no longer receive method calls about other networks that may have been
3568 * passed to this method previously. The previously-best network may have disconnected, or
3569 * it may still be around and the newly-best network may simply be better.
3570 *
3571 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3572 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3573 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3574 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3575 *
3576 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3577 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3578 * this callback as this is prone to race conditions (there is no guarantee the objects
3579 * returned by these methods will be current). Instead, wait for a call to
3580 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3581 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3582 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003583 *
3584 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003585 */
paulhua9a6e2a2019-03-22 16:35:06 +08003586 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003587
3588 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003589 * Called when the network is about to be lost, typically because there are no outstanding
3590 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3591 * with the new replacement network for graceful handover. This method is not guaranteed
3592 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3593 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003594 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003595 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3596 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3597 * this callback as this is prone to race conditions ; calling these methods while in a
3598 * callback may return an outdated or even a null object.
3599 *
3600 * @param network The {@link Network} that is about to be lost.
3601 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3602 * connected for graceful handover; note that the network may still
3603 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003604 */
paulhua9a6e2a2019-03-22 16:35:06 +08003605 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003606
3607 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003608 * Called when a network disconnects or otherwise no longer satisfies this request or
3609 * callback.
3610 *
3611 * <p>If the callback was registered with requestNetwork() or
3612 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3613 * returned by onAvailable() when that network is lost and no other network satisfies
3614 * the criteria of the request.
3615 *
3616 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3617 * each network which no longer satisfies the criteria of the callback.
3618 *
3619 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3620 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3621 * this callback as this is prone to race conditions ; calling these methods while in a
3622 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003623 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003624 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003625 */
paulhua9a6e2a2019-03-22 16:35:06 +08003626 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003627
3628 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003629 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003630 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3631 * requested network request cannot be fulfilled (whether or not a timeout was
3632 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003633 * {@link NetworkRequest} will have already been removed and released, as if
3634 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003635 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003636 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003637
3638 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003639 * Called when the network corresponding to this request changes capabilities but still
3640 * satisfies the requested criteria.
3641 *
3642 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3643 * to be called immediately after {@link #onAvailable}.
3644 *
3645 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3646 * ConnectivityManager methods in this callback as this is prone to race conditions :
3647 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003648 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003649 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius7992afd2020-12-22 15:10:42 -08003650 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003651 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003652 */
paulhua9a6e2a2019-03-22 16:35:06 +08003653 public void onCapabilitiesChanged(@NonNull Network network,
3654 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003655
3656 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003657 * Called when the network corresponding to this request changes {@link LinkProperties}.
3658 *
3659 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3660 * to be called immediately after {@link #onAvailable}.
3661 *
3662 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3663 * ConnectivityManager methods in this callback as this is prone to race conditions :
3664 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003665 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003666 * @param network The {@link Network} whose link properties have changed.
3667 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003668 */
paulhua9a6e2a2019-03-22 16:35:06 +08003669 public void onLinkPropertiesChanged(@NonNull Network network,
3670 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003671
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003672 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003673 * Called when the network the framework connected to for this request suspends data
3674 * transmission temporarily.
3675 *
3676 * <p>This generally means that while the TCP connections are still live temporarily
3677 * network data fails to transfer. To give a specific example, this is used on cellular
3678 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3679 * means read operations on sockets on this network will block once the buffers are
3680 * drained, and write operations will block once the buffers are full.
3681 *
3682 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3683 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3684 * this callback as this is prone to race conditions (there is no guarantee the objects
3685 * returned by these methods will be current).
3686 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003687 * @hide
3688 */
paulhua9a6e2a2019-03-22 16:35:06 +08003689 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003690
3691 /**
3692 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003693 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3694 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003695
3696 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3697 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3698 * this callback as this is prone to race conditions : calling these methods while in a
3699 * callback may return an outdated or even a null object.
3700 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003701 * @hide
3702 */
paulhua9a6e2a2019-03-22 16:35:06 +08003703 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003704
junyulai5ab727b2018-08-07 19:50:45 +08003705 /**
3706 * Called when access to the specified network is blocked or unblocked.
3707 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003708 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3709 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3710 * this callback as this is prone to race conditions : calling these methods while in a
3711 * callback may return an outdated or even a null object.
3712 *
junyulai5ab727b2018-08-07 19:50:45 +08003713 * @param network The {@link Network} whose blocked status has changed.
3714 * @param blocked The blocked status of this {@link Network}.
3715 */
junyulai61143782019-03-04 22:45:36 +08003716 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003717
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003718 /**
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09003719 * Called when access to the specified network is blocked or unblocked, or the reason for
3720 * access being blocked changes.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003721 *
3722 * If a NetworkCallback object implements this method,
3723 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3724 *
3725 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3726 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3727 * this callback as this is prone to race conditions : calling these methods while in a
3728 * callback may return an outdated or even a null object.
3729 *
3730 * @param network The {@link Network} whose blocked status has changed.
3731 * @param blocked The blocked status of this {@link Network}.
3732 * @hide
3733 */
3734 @SystemApi(client = MODULE_LIBRARIES)
3735 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3736 onBlockedStatusChanged(network, blocked != 0);
3737 }
3738
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003739 private NetworkRequest networkRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -08003740 private final int mFlags;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003741 }
3742
Hugo Benichi145e3792017-05-11 13:16:17 +09003743 /**
3744 * Constant error codes used by ConnectivityService to communicate about failures and errors
3745 * across a Binder boundary.
3746 * @hide
3747 */
3748 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003749 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003750 }
3751
3752 /** @hide */
3753 public static class TooManyRequestsException extends RuntimeException {}
3754
3755 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3756 switch (e.errorCode) {
3757 case Errors.TOO_MANY_REQUESTS:
3758 return new TooManyRequestsException();
3759 default:
3760 Log.w(TAG, "Unknown service error code " + e.errorCode);
3761 return new RuntimeException(e);
3762 }
3763 }
3764
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003765 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003766 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003767 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003768 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003769 /** @hide arg1 = TTL */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003770 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003771 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003772 public static final int CALLBACK_LOST = 4;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003773 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003774 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003775 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003776 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003777 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003778 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003779 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003780 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003781 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003782 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003783 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003784 public static final int CALLBACK_RESUMED = 10;
junyulai5ab727b2018-08-07 19:50:45 +08003785 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003786 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003787
Erik Kline66721822015-11-25 12:49:38 +09003788 /** @hide */
3789 public static String getCallbackName(int whichCallback) {
3790 switch (whichCallback) {
3791 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3792 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3793 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3794 case CALLBACK_LOST: return "CALLBACK_LOST";
3795 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3796 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3797 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003798 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3799 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3800 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003801 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003802 default:
3803 return Integer.toString(whichCallback);
3804 }
3805 }
3806
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003807 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003808 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003809 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003810
Hugo Benichife3325f2016-07-06 22:53:17 +09003811 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003812 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003813 }
3814
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003815 CallbackHandler(Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003816 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003817 }
3818
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003819 @Override
3820 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003821 if (message.what == EXPIRE_LEGACY_REQUEST) {
3822 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3823 return;
3824 }
3825
3826 final NetworkRequest request = getObject(message, NetworkRequest.class);
3827 final Network network = getObject(message, Network.class);
3828 final NetworkCallback callback;
3829 synchronized (sCallbacks) {
3830 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003831 if (callback == null) {
3832 Log.w(TAG,
3833 "callback not found for " + getCallbackName(message.what) + " message");
3834 return;
3835 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003836 if (message.what == CALLBACK_UNAVAIL) {
3837 sCallbacks.remove(request);
3838 callback.networkRequest = ALREADY_UNREGISTERED;
3839 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003840 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003841 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003842 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003843 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003844
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003845 switch (message.what) {
3846 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003847 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003848 break;
3849 }
3850 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003851 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3852 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003853 callback.onAvailable(network, cap, lp, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003854 break;
3855 }
3856 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003857 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003858 break;
3859 }
3860 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003861 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003862 break;
3863 }
3864 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003865 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003866 break;
3867 }
3868 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003869 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3870 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003871 break;
3872 }
3873 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003874 LinkProperties lp = getObject(message, LinkProperties.class);
3875 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003876 break;
3877 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003878 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003879 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003880 break;
3881 }
3882 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003883 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003884 break;
3885 }
junyulai5ab727b2018-08-07 19:50:45 +08003886 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003887 callback.onBlockedStatusChanged(network, message.arg1);
junyulai5ab727b2018-08-07 19:50:45 +08003888 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003889 }
3890 }
3891
Hugo Benichife3325f2016-07-06 22:53:17 +09003892 private <T> T getObject(Message msg, Class<T> c) {
3893 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003894 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003895 }
3896
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003897 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003898 synchronized (sCallbacks) {
3899 if (sCallbackHandler == null) {
3900 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003901 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003902 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003903 }
3904 }
3905
Hugo Benichiec180d52017-02-03 14:18:44 +09003906 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3907 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003908
Lorenzo Colittib199b962021-03-12 22:48:07 +09003909 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3910 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3911 CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003912 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003913 checkCallbackNotNull(callback);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003914 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3915 throw new IllegalArgumentException("null NetworkCapabilities");
3916 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003917 final NetworkRequest request;
Roshan Piusd26ae412020-01-16 12:17:17 -08003918 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003919 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003920 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003921 if (callback.networkRequest != null
3922 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003923 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3924 // and requests (http://b/20701525).
3925 Log.e(TAG, "NetworkCallback was already registered");
3926 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003927 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003928 Binder binder = new Binder();
Roshan Pius7992afd2020-12-22 15:10:42 -08003929 final int callbackFlags = callback.mFlags;
junyulaid1a78162021-01-11 16:53:38 +08003930 if (reqType == LISTEN) {
Roshan Piusd26ae412020-01-16 12:17:17 -08003931 request = mService.listenForNetwork(
Roshan Pius7992afd2020-12-22 15:10:42 -08003932 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08003933 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003934 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003935 request = mService.requestNetwork(
Lorenzo Colittib199b962021-03-12 22:48:07 +09003936 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3937 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003938 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003939 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003940 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003941 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003942 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003943 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003944 } catch (RemoteException e) {
3945 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003946 } catch (ServiceSpecificException e) {
3947 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003948 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003949 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003950 }
3951
Lorenzo Colittib199b962021-03-12 22:48:07 +09003952 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3953 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3954 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3955 legacyType, handler);
3956 }
3957
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003958 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003959 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003960 *
markchien0fe11402020-03-18 21:16:15 +08003961 * This API is only for use in internal system code that requests networks with legacy type and
3962 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchien769c5752020-01-14 12:54:40 +08003963 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003964 *
markchien769c5752020-01-14 12:54:40 +08003965 * @param request {@link NetworkRequest} describing this request.
markchien769c5752020-01-14 12:54:40 +08003966 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3967 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3968 * be a positive value (i.e. >0).
3969 * @param legacyType to specify the network type(#TYPE_*).
3970 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien0fe11402020-03-18 21:16:15 +08003971 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3972 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003973 *
3974 * @hide
3975 */
markchien769c5752020-01-14 12:54:40 +08003976 @SystemApi
markchien0fe11402020-03-18 21:16:15 +08003977 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003978 public void requestNetwork(@NonNull NetworkRequest request,
markchien0fe11402020-03-18 21:16:15 +08003979 int timeoutMs, int legacyType, @NonNull Handler handler,
3980 @NonNull NetworkCallback networkCallback) {
3981 if (legacyType == TYPE_NONE) {
3982 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3983 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003984 CallbackHandler cbHandler = new CallbackHandler(handler);
3985 NetworkCapabilities nc = request.networkCapabilities;
3986 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003987 }
3988
3989 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003990 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003991 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003992 * <p>This method will attempt to find the best network that matches the passed
3993 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3994 * criteria. The platform will evaluate which network is the best at its own discretion.
3995 * Throughput, latency, cost per byte, policy, user preference and other considerations
3996 * may be factored in the decision of what is considered the best network.
3997 *
3998 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3999 * matching this request, while always attempting to match the request to a better network if
4000 * possible. If a better match is found, the platform will switch this request to the now-best
4001 * network and inform the app of the newly best network by invoking
4002 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4003 * will not try to maintain any other network than the best one currently matching the request:
4004 * a network not matching any network request may be disconnected at any time.
4005 *
4006 * <p>For example, an application could use this method to obtain a connected cellular network
4007 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4008 * radio to consume additional power. Or, an application could inform the system that it wants
4009 * a network supporting sending MMSes and have the system let it know about the currently best
4010 * MMS-supporting network through the provided {@link NetworkCallback}.
4011 *
4012 * <p>The status of the request can be followed by listening to the various callbacks described
4013 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4014 * used to direct traffic to the network (although accessing some networks may be subject to
4015 * holding specific permissions). Callers will learn about the specific characteristics of the
4016 * network through
4017 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4018 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4019 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4020 * matching the request at any given time; therefore when a better network matching the request
4021 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4022 * with the new network after which no further updates are given about the previously-best
4023 * network, unless it becomes the best again at some later time. All callbacks are invoked
4024 * in order on the same thread, which by default is a thread created by the framework running
4025 * in the app.
4026 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4027 * callbacks are invoked.
4028 *
4029 * <p>This{@link NetworkRequest} will live until released via
4030 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4031 * which point the system may let go of the network at any time.
4032 *
4033 * <p>A version of this method which takes a timeout is
4034 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4035 * wait for a limited amount of time for the network to become unavailable.
4036 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004037 * <p>It is presently unsupported to request a network with mutable
4038 * {@link NetworkCapabilities} such as
4039 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4040 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4041 * as these {@code NetworkCapabilities} represent states that a particular
4042 * network may never attain, and whether a network will attain these states
4043 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09004044 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004045 *
4046 * <p>This method requires the caller to hold either the
4047 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4048 * or the ability to modify system settings as determined by
4049 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004050 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004051 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4052 * number of outstanding requests to 100 per app (identified by their UID), shared with
4053 * all variants of this method, of {@link #registerNetworkCallback} as well as
4054 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4055 * Requesting a network with this method will count toward this limit. If this limit is
4056 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4057 * make sure to unregister the callbacks with
4058 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4059 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004060 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004061 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4062 * the callback must not be shared - it uniquely specifies this request.
4063 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004064 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4065 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004066 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004067 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004068 public void requestNetwork(@NonNull NetworkRequest request,
4069 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004070 requestNetwork(request, networkCallback, getDefaultHandler());
4071 }
4072
4073 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004074 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004075 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004076 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4077 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004078 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004079 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004080 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4081 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004082 *
4083 * @param request {@link NetworkRequest} describing this request.
4084 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4085 * the callback must not be shared - it uniquely specifies this request.
4086 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004087 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004088 public void requestNetwork(@NonNull NetworkRequest request,
4089 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004090 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004091 NetworkCapabilities nc = request.networkCapabilities;
4092 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004093 }
4094
4095 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004096 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohen67e58a02017-03-01 12:47:28 -08004097 * by a timeout.
4098 *
4099 * This function behaves identically to the non-timed-out version
4100 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4101 * is not found within the given time (in milliseconds) the
4102 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4103 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4104 * not have to be released if timed-out (it is automatically released). Unregistering a
4105 * request that timed out is not an error.
4106 *
4107 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4108 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4109 * for that purpose. Calling this method will attempt to bring up the requested network.
4110 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004111 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004112 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4113 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08004114 *
4115 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004116 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4117 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004118 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4119 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4120 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08004121 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004122 public void requestNetwork(@NonNull NetworkRequest request,
4123 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004124 checkTimeout(timeoutMs);
markchien0fe11402020-03-18 21:16:15 +08004125 NetworkCapabilities nc = request.networkCapabilities;
4126 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4127 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004128 }
4129
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004130 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004131 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004132 * by a timeout.
4133 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004134 * This method behaves identically to
4135 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4136 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08004137 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004138 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004139 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4140 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004141 *
4142 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004143 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4144 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004145 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004146 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4147 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004148 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004149 public void requestNetwork(@NonNull NetworkRequest request,
4150 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004151 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004152 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004153 NetworkCapabilities nc = request.networkCapabilities;
4154 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004155 }
4156
4157 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004158 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004159 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004160 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08004161 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04004162 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4163 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004164 */
Erik Klinefb087f12014-11-19 12:12:24 +09004165 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004166
4167 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004168 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004169 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004170 * {@link android.content.Intent#getParcelableExtra(String)}.
4171 */
Erik Klinefb087f12014-11-19 12:12:24 +09004172 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004173
4174
4175 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004176 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004177 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08004178 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004179 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004180 * the request may outlive the calling application and get called back when a suitable
4181 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004182 * <p>
4183 * The operation is an Intent broadcast that goes to a broadcast receiver that
4184 * you registered with {@link Context#registerReceiver} or through the
4185 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4186 * <p>
4187 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09004188 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4189 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004190 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004191 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004192 * Intent to reserve the network or it will be released shortly after the Intent
4193 * is processed.
4194 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04004195 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004196 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004197 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004198 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08004199 * The request may be released normally by calling
4200 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004201 * <p>It is presently unsupported to request a network with either
4202 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4203 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4204 * as these {@code NetworkCapabilities} represent states that a particular
4205 * network may never attain, and whether a network will attain these states
4206 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09004207 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004208 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004209 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4210 * number of outstanding requests to 100 per app (identified by their UID), shared with
4211 * all variants of this method, of {@link #registerNetworkCallback} as well as
4212 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4213 * Requesting a network with this method will count toward this limit. If this limit is
4214 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4215 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4216 * or {@link #releaseNetworkRequest(PendingIntent)}.
4217 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004218 * <p>This method requires the caller to hold either the
4219 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4220 * or the ability to modify system settings as determined by
4221 * {@link android.provider.Settings.System#canWrite}.</p>
4222 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004223 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004224 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004225 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08004226 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004227 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4228 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004229 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004230 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004231 public void requestNetwork(@NonNull NetworkRequest request,
4232 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004233 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004234 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004235 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004236 mService.pendingRequestForNetwork(
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07004237 request.networkCapabilities, operation, mContext.getOpPackageName(),
4238 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004239 } catch (RemoteException e) {
4240 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004241 } catch (ServiceSpecificException e) {
4242 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004243 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004244 }
4245
4246 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004247 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4248 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004249 * This method has the same behavior as
4250 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004251 * releasing network resources and disconnecting.
4252 *
4253 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4254 * PendingIntent passed to
4255 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4256 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4257 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004258 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004259 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004260 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004261 try {
4262 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004263 } catch (RemoteException e) {
4264 throw e.rethrowFromSystemServer();
4265 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004266 }
4267
Hugo Benichiff4bf602017-05-09 15:19:01 +09004268 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004269 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004270 }
4271
4272 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004273 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004274 }
4275
4276 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004277 if (timeoutMs <= 0) {
4278 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4279 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004280 }
4281
4282 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004283 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004284 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004285 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4286 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004287 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004288 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4289 * number of outstanding requests to 100 per app (identified by their UID), shared with
4290 * all variants of this method, of {@link #requestNetwork} as well as
4291 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4292 * Requesting a network with this method will count toward this limit. If this limit is
4293 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4294 * make sure to unregister the callbacks with
4295 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4296 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004297 * @param request {@link NetworkRequest} describing this request.
4298 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4299 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004300 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004301 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004302 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004303 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004304 public void registerNetworkCallback(@NonNull NetworkRequest request,
4305 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004306 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4307 }
4308
4309 /**
4310 * Registers to receive notifications about all networks which satisfy the given
4311 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004312 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4313 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004314 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004315 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4316 * number of outstanding requests to 100 per app (identified by their UID), shared with
4317 * all variants of this method, of {@link #requestNetwork} as well as
4318 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4319 * Requesting a network with this method will count toward this limit. If this limit is
4320 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4321 * make sure to unregister the callbacks with
4322 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4323 *
4324 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004325 * @param request {@link NetworkRequest} describing this request.
4326 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4327 * networks change state.
4328 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004329 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004330 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004331 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004332 public void registerNetworkCallback(@NonNull NetworkRequest request,
4333 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004334 CallbackHandler cbHandler = new CallbackHandler(handler);
4335 NetworkCapabilities nc = request.networkCapabilities;
4336 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004337 }
4338
4339 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004340 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4341 * {@link NetworkRequest}.
4342 *
4343 * This function behaves identically to the version that takes a NetworkCallback, but instead
4344 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4345 * the request may outlive the calling application and get called back when a suitable
4346 * network is found.
4347 * <p>
4348 * The operation is an Intent broadcast that goes to a broadcast receiver that
4349 * you registered with {@link Context#registerReceiver} or through the
4350 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4351 * <p>
4352 * The operation Intent is delivered with two extras, a {@link Network} typed
4353 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4354 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4355 * the original requests parameters.
4356 * <p>
4357 * If there is already a request for this Intent registered (with the equality of
4358 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4359 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4360 * <p>
4361 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004362 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004363 *
4364 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4365 * number of outstanding requests to 100 per app (identified by their UID), shared with
4366 * all variants of this method, of {@link #requestNetwork} as well as
4367 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4368 * Requesting a network with this method will count toward this limit. If this limit is
4369 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4370 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4371 * or {@link #releaseNetworkRequest(PendingIntent)}.
4372 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004373 * @param request {@link NetworkRequest} describing this request.
4374 * @param operation Action to perform when the network is available (corresponds
4375 * to the {@link NetworkCallback#onAvailable} call. Typically
4376 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004377 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004378 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004379 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004380 public void registerNetworkCallback(@NonNull NetworkRequest request,
4381 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004382 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004383 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004384 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004385 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004386 request.networkCapabilities, operation, mContext.getOpPackageName(),
4387 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004388 } catch (RemoteException e) {
4389 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004390 } catch (ServiceSpecificException e) {
4391 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004392 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004393 }
4394
4395 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004396 * Registers to receive notifications about changes in the application's default network. This
4397 * may be a physical network or a virtual network, such as a VPN that applies to the
4398 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004399 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004400 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004401 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4402 * number of outstanding requests to 100 per app (identified by their UID), shared with
4403 * all variants of this method, of {@link #requestNetwork} as well as
4404 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4405 * Requesting a network with this method will count toward this limit. If this limit is
4406 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4407 * make sure to unregister the callbacks with
4408 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4409 *
Erik Klinee0aed632016-03-16 15:31:39 +09004410 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004411 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004412 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004413 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004414 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004415 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004416 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004417 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4418 }
4419
4420 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004421 * Registers to receive notifications about changes in the application's default network. This
4422 * may be a physical network or a virtual network, such as a VPN that applies to the
4423 * application. The callbacks will continue to be called until either the application exits or
4424 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4425 *
4426 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4427 * number of outstanding requests to 100 per app (identified by their UID), shared with
4428 * all variants of this method, of {@link #requestNetwork} as well as
4429 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4430 * Requesting a network with this method will count toward this limit. If this limit is
4431 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4432 * make sure to unregister the callbacks with
4433 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4434 *
4435 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4436 * application's default network changes.
4437 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4438 * @throws RuntimeException if the app already has too many callbacks registered.
4439 */
4440 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4441 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4442 @NonNull Handler handler) {
Lorenzo Colittib199b962021-03-12 22:48:07 +09004443 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4444 }
4445
4446 /**
4447 * Registers to receive notifications about changes in the default network for the specified
4448 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4449 * UID. The callbacks will continue to be called until either the application exits or
4450 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4451 *
4452 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4453 * number of outstanding requests to 100 per app (identified by their UID), shared with
4454 * all variants of this method, of {@link #requestNetwork} as well as
4455 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4456 * Requesting a network with this method will count toward this limit. If this limit is
4457 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4458 * make sure to unregister the callbacks with
4459 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4460 *
4461 * @param uid the UID for which to track default network changes.
4462 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4463 * UID's default network changes.
4464 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4465 * @throws RuntimeException if the app already has too many callbacks registered.
4466 * @hide
4467 */
Lorenzo Colitti3949d6e2021-03-22 18:23:21 +09004468 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittib199b962021-03-12 22:48:07 +09004469 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4470 @RequiresPermission(anyOf = {
4471 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4472 android.Manifest.permission.NETWORK_SETTINGS})
4473 public void registerDefaultNetworkCallbackAsUid(int uid,
4474 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004475 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colittib199b962021-03-12 22:48:07 +09004476 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004477 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4478 }
4479
4480 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004481 * Registers to receive notifications about changes in the system default network. The callbacks
4482 * will continue to be called until either the application exits or
4483 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004484 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004485 * This method should not be used to determine networking state seen by applications, because in
4486 * many cases, most or even all application traffic may not use the default network directly,
4487 * and traffic from different applications may go on different networks by default. As an
4488 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4489 * and not onto the system default network. Applications or system components desiring to do
4490 * determine network state as seen by applications should use other methods such as
4491 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4492 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004493 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4494 * number of outstanding requests to 100 per app (identified by their UID), shared with
4495 * all variants of this method, of {@link #requestNetwork} as well as
4496 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4497 * Requesting a network with this method will count toward this limit. If this limit is
4498 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4499 * make sure to unregister the callbacks with
4500 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4501 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004502 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4503 * system default network changes.
4504 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004505 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004506 *
4507 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004508 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004509 @SystemApi(client = MODULE_LIBRARIES)
4510 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4511 @RequiresPermission(anyOf = {
4512 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4513 android.Manifest.permission.NETWORK_SETTINGS})
4514 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004515 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004516 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004517 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004518 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004519 }
4520
4521 /**
junyulaibd622262021-03-15 11:48:48 +08004522 * Registers to receive notifications about the best matching network which satisfy the given
4523 * {@link NetworkRequest}. The callbacks will continue to be called until
4524 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4525 * called.
4526 *
4527 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4528 * number of outstanding requests to 100 per app (identified by their UID), shared with
4529 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4530 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4531 * Requesting a network with this method will count toward this limit. If this limit is
4532 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4533 * make sure to unregister the callbacks with
4534 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4535 *
4536 *
4537 * @param request {@link NetworkRequest} describing this request.
4538 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4539 * networks change state.
4540 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4541 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai6b0a6a22021-03-05 15:51:17 +08004542 */
junyulai6b0a6a22021-03-05 15:51:17 +08004543 @SuppressLint("ExecutorRegistration")
4544 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4545 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4546 final NetworkCapabilities nc = request.networkCapabilities;
4547 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai8cae3c72021-03-12 20:05:08 +08004548 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai6b0a6a22021-03-05 15:51:17 +08004549 }
4550
4551 /**
fenglu73169332015-04-21 17:12:05 -07004552 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4553 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4554 * network connection for updated bandwidth information. The caller will be notified via
4555 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004556 * method assumes that the caller has previously called
4557 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4558 * changes.
fenglu76564332015-03-20 11:29:56 -07004559 *
fenglu41808e82015-04-27 14:28:04 -07004560 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004561 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004562 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004563 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004564 try {
fenglu73169332015-04-21 17:12:05 -07004565 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004566 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004567 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004568 }
4569 }
4570
4571 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004572 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004573 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4574 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4575 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004576 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4577 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004578 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004579 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4580 * triggering it as soon as this call returns.
4581 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004582 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004583 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004584 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004585 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004586 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004587 final List<NetworkRequest> reqs = new ArrayList<>();
4588 // Find all requests associated to this callback and stop callback triggers immediately.
4589 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4590 synchronized (sCallbacks) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004591 if (networkCallback.networkRequest == null) {
4592 throw new IllegalArgumentException("NetworkCallback was not registered");
4593 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07004594 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4595 Log.d(TAG, "NetworkCallback was already unregistered");
4596 return;
4597 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004598 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4599 if (e.getValue() == networkCallback) {
4600 reqs.add(e.getKey());
4601 }
4602 }
4603 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4604 for (NetworkRequest r : reqs) {
4605 try {
4606 mService.releaseNetworkRequest(r);
4607 } catch (RemoteException e) {
4608 throw e.rethrowFromSystemServer();
4609 }
4610 // Only remove mapping if rpc was successful.
4611 sCallbacks.remove(r);
4612 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004613 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004614 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004615 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004616
4617 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004618 * Unregisters a callback previously registered via
4619 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4620 *
4621 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4622 * PendingIntent passed to
4623 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4624 * Cannot be null.
4625 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004626 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004627 releaseNetworkRequest(operation);
4628 }
4629
4630 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004631 * Informs the system whether it should switch to {@code network} regardless of whether it is
4632 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4633 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4634 * the system default network regardless of any other network that's currently connected. If
4635 * {@code always} is true, then the choice is remembered, so that the next time the user
4636 * connects to this network, the system will switch to it.
4637 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004638 * @param network The network to accept.
4639 * @param accept Whether to accept the network even if unvalidated.
4640 * @param always Whether to remember this choice in the future.
4641 *
4642 * @hide
4643 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004644 @SystemApi(client = MODULE_LIBRARIES)
4645 @RequiresPermission(anyOf = {
4646 android.Manifest.permission.NETWORK_SETTINGS,
4647 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4648 android.Manifest.permission.NETWORK_STACK,
4649 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4650 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004651 try {
4652 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004653 } catch (RemoteException e) {
4654 throw e.rethrowFromSystemServer();
4655 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004656 }
4657
4658 /**
lucaslin25a50472019-03-12 13:08:03 +08004659 * Informs the system whether it should consider the network as validated even if it only has
4660 * partial connectivity. If {@code accept} is true, then the network will be considered as
4661 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4662 * is remembered, so that the next time the user connects to this network, the system will
4663 * switch to it.
4664 *
4665 * @param network The network to accept.
4666 * @param accept Whether to consider the network as validated even if it has partial
4667 * connectivity.
4668 * @param always Whether to remember this choice in the future.
4669 *
4670 * @hide
4671 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004672 @SystemApi(client = MODULE_LIBRARIES)
4673 @RequiresPermission(anyOf = {
4674 android.Manifest.permission.NETWORK_SETTINGS,
4675 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4676 android.Manifest.permission.NETWORK_STACK,
4677 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4678 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4679 boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004680 try {
4681 mService.setAcceptPartialConnectivity(network, accept, always);
4682 } catch (RemoteException e) {
4683 throw e.rethrowFromSystemServer();
4684 }
4685 }
4686
4687 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004688 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4689 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4690 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4691 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4692 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004693 * @param network The network to accept.
4694 *
4695 * @hide
4696 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004697 @SystemApi(client = MODULE_LIBRARIES)
4698 @RequiresPermission(anyOf = {
4699 android.Manifest.permission.NETWORK_SETTINGS,
4700 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4701 android.Manifest.permission.NETWORK_STACK,
4702 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4703 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004704 try {
4705 mService.setAvoidUnvalidated(network);
4706 } catch (RemoteException e) {
4707 throw e.rethrowFromSystemServer();
4708 }
4709 }
4710
4711 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004712 * Requests that the system open the captive portal app on the specified network.
4713 *
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004714 * <p>This is to be used on networks where a captive portal was detected, as per
4715 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4716 *
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004717 * @param network The network to log into.
4718 *
4719 * @hide
4720 */
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004721 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4722 @RequiresPermission(anyOf = {
4723 android.Manifest.permission.NETWORK_SETTINGS,
4724 android.Manifest.permission.NETWORK_STACK,
4725 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4726 })
4727 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004728 try {
4729 mService.startCaptivePortalApp(network);
4730 } catch (RemoteException e) {
4731 throw e.rethrowFromSystemServer();
4732 }
4733 }
4734
4735 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004736 * Requests that the system open the captive portal app with the specified extras.
4737 *
4738 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4739 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004740 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004741 * @param appExtras Extras to include in the app start intent.
4742 * @hide
4743 */
4744 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004745 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004746 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004747 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004748 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004749 } catch (RemoteException e) {
4750 throw e.rethrowFromSystemServer();
4751 }
4752 }
4753
4754 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004755 * Determine whether the device is configured to avoid bad wifi.
4756 * @hide
4757 */
4758 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004759 @RequiresPermission(anyOf = {
4760 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4761 android.Manifest.permission.NETWORK_STACK})
4762 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004763 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004764 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004765 } catch (RemoteException e) {
4766 throw e.rethrowFromSystemServer();
4767 }
4768 }
4769
4770 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004771 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4772 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004773 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4774 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004775 *
4776 * An example of such an operation might be a time-sensitive foreground activity, such as a
4777 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4778 */
4779 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4780
4781 /**
4782 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4783 * a backup channel for traffic that is primarily going over another network.
4784 *
4785 * An example might be maintaining backup connections to peers or servers for the purpose of
4786 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4787 * on backup paths should be negligible compared to the traffic on the main path.
4788 */
4789 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4790
4791 /**
4792 * It is acceptable to use metered data to improve network latency and performance.
4793 */
4794 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4795
4796 /**
4797 * Return value to use for unmetered networks. On such networks we currently set all the flags
4798 * to true.
4799 * @hide
4800 */
4801 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4802 MULTIPATH_PREFERENCE_HANDOVER |
4803 MULTIPATH_PREFERENCE_RELIABILITY |
4804 MULTIPATH_PREFERENCE_PERFORMANCE;
4805
4806 /** @hide */
4807 @Retention(RetentionPolicy.SOURCE)
4808 @IntDef(flag = true, value = {
4809 MULTIPATH_PREFERENCE_HANDOVER,
4810 MULTIPATH_PREFERENCE_RELIABILITY,
4811 MULTIPATH_PREFERENCE_PERFORMANCE,
4812 })
4813 public @interface MultipathPreference {
4814 }
4815
4816 /**
4817 * Provides a hint to the calling application on whether it is desirable to use the
4818 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4819 * for multipath data transfer on this network when it is not the system default network.
4820 * Applications desiring to use multipath network protocols should call this method before
4821 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004822 *
4823 * @param network The network on which the application desires to use multipath data.
4824 * If {@code null}, this method will return the a preference that will generally
4825 * apply to metered networks.
4826 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4827 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004828 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004829 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004830 try {
4831 return mService.getMultipathPreference(network);
4832 } catch (RemoteException e) {
4833 throw e.rethrowFromSystemServer();
4834 }
4835 }
4836
4837 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004838 * Resets all connectivity manager settings back to factory defaults.
4839 * @hide
4840 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004841 @SystemApi(client = MODULE_LIBRARIES)
4842 @RequiresPermission(anyOf = {
4843 android.Manifest.permission.NETWORK_SETTINGS,
4844 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scottd3bb5082015-03-30 13:17:11 -07004845 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004846 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004847 mService.factoryReset();
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00004848 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004849 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004850 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004851 }
4852 }
4853
4854 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004855 * Binds the current process to {@code network}. All Sockets created in the future
4856 * (and not explicitly bound via a bound SocketFactory from
4857 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4858 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4859 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4860 * work and all host name resolutions will fail. This is by design so an application doesn't
4861 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4862 * To clear binding pass {@code null} for {@code network}. Using individually bound
4863 * Sockets created by Network.getSocketFactory().createSocket() and
4864 * performing network-specific host name resolutions via
4865 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004866 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004867 *
4868 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4869 * the current binding.
4870 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4871 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004872 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004873 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004874 // instantiated.
4875 return setProcessDefaultNetwork(network);
4876 }
4877
4878 /**
4879 * Binds the current process to {@code network}. All Sockets created in the future
4880 * (and not explicitly bound via a bound SocketFactory from
4881 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4882 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4883 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4884 * work and all host name resolutions will fail. This is by design so an application doesn't
4885 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4886 * To clear binding pass {@code null} for {@code network}. Using individually bound
4887 * Sockets created by Network.getSocketFactory().createSocket() and
4888 * performing network-specific host name resolutions via
4889 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4890 * {@code setProcessDefaultNetwork}.
4891 *
4892 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4893 * the current binding.
4894 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4895 * @deprecated This function can throw {@link IllegalStateException}. Use
4896 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4897 * is a direct replacement.
4898 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004899 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004900 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004901 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004902 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4903
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004904 if (netId != NETID_UNSET) {
4905 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004906 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004907
4908 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4909 return false;
4910 }
4911
4912 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004913 // Set HTTP proxy system properties to match network.
4914 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004915 try {
Remi NGUYEN VANa1860ff2021-02-03 10:18:20 +09004916 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004917 } catch (SecurityException e) {
4918 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4919 Log.e(TAG, "Can't set proxy properties", e);
4920 }
Paul Jensen99c36662014-08-27 12:38:45 -04004921 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN33e3abb2021-03-18 23:27:19 +09004922 InetAddressCompat.clearDnsCache();
Paul Jensen99c36662014-08-27 12:38:45 -04004923 // Must flush socket pool as idle sockets will be bound to previous network and may
4924 // cause subsequent fetches to be performed on old network.
4925 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004926 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004927
4928 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004929 }
4930
4931 /**
4932 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004933 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004934 *
4935 * @return {@code Network} to which this process is bound, or {@code null}.
4936 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004937 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004938 public Network getBoundNetworkForProcess() {
4939 // Forcing callers to call thru non-static function ensures ConnectivityManager
4940 // instantiated.
4941 return getProcessDefaultNetwork();
4942 }
4943
4944 /**
4945 * Returns the {@link Network} currently bound to this process via
4946 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4947 *
4948 * @return {@code Network} to which this process is bound, or {@code null}.
4949 * @deprecated Using this function can lead to other functions throwing
4950 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4951 * {@code getBoundNetworkForProcess} is a direct replacement.
4952 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004953 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004954 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004955 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004956 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004957 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004958 return new Network(netId);
4959 }
4960
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004961 private void unsupportedStartingFrom(int version) {
4962 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004963 // The getApplicationInfo() call we make below is not supported in system context. Let
4964 // the call through here, and rely on the fact that ConnectivityService will refuse to
4965 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004966 return;
4967 }
4968
4969 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4970 throw new UnsupportedOperationException(
4971 "This method is not supported in target SDK version " + version + " and above");
4972 }
4973 }
4974
4975 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4976 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004977 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004978 // remove these exemptions. Note that this check is not secure, and apps can still access these
4979 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4980 // so is unsupported and may break in the future. http://b/22728205
4981 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07004982 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004983 }
4984
Paul Jensene98c6e02014-05-29 10:12:39 -04004985 /**
4986 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04004987 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04004988 *
4989 * @param network The {@link Network} to bind host resolutions from the current process to, or
4990 * {@code null} to clear the current binding.
4991 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4992 * @hide
4993 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4994 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004995 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00004996 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04004997 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04004998 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09004999 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04005000 }
Felipe Lemed16384b2016-01-22 09:44:57 -08005001
5002 /**
5003 * Device is not restricting metered network activity while application is running on
5004 * background.
5005 */
5006 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5007
5008 /**
5009 * Device is restricting metered network activity while application is running on background,
5010 * but application is allowed to bypass it.
5011 * <p>
5012 * In this state, application should take action to mitigate metered network access.
5013 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5014 */
5015 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5016
5017 /**
5018 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08005019 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08005020 * In this state, application should not try to use the network while running on background,
5021 * because it would be denied.
5022 */
5023 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5024
Felipe Leme6a5b7692016-01-27 14:46:39 -08005025 /**
5026 * A change in the background metered network activity restriction has occurred.
5027 * <p>
5028 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5029 * applies to them.
5030 * <p>
5031 * This is only sent to registered receivers, not manifest receivers.
5032 */
5033 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5034 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5035 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5036
Felipe Leme1b42ef92016-01-25 11:48:04 -08005037 /** @hide */
5038 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08005039 @IntDef(flag = false, value = {
5040 RESTRICT_BACKGROUND_STATUS_DISABLED,
5041 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5042 RESTRICT_BACKGROUND_STATUS_ENABLED,
5043 })
Felipe Lemed16384b2016-01-22 09:44:57 -08005044 public @interface RestrictBackgroundStatus {
5045 }
5046
Felipe Lemed16384b2016-01-22 09:44:57 -08005047 /**
5048 * Determines if the calling application is subject to metered network restrictions while
5049 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07005050 *
5051 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5052 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5053 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08005054 */
5055 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5056 try {
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09005057 return mService.getRestrictBackgroundStatusByCaller();
Felipe Lemed16384b2016-01-22 09:44:57 -08005058 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07005059 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08005060 }
5061 }
Ricky Waid53cf002018-01-23 04:09:45 +00005062
5063 /**
5064 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00005065 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5066 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00005067 *
5068 * @return Hash of network watchlist config file. Null if config does not exist.
5069 */
Chalard Jean42a9c292019-01-07 19:26:34 +09005070 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00005071 public byte[] getNetworkWatchlistConfigHash() {
5072 try {
5073 return mService.getNetworkWatchlistConfigHash();
5074 } catch (RemoteException e) {
5075 Log.e(TAG, "Unable to get watchlist config hash");
5076 throw e.rethrowFromSystemServer();
5077 }
5078 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005079
5080 /**
5081 * Returns the {@code uid} of the owner of a network connection.
5082 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08005083 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5084 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005085 * @param local The local {@link InetSocketAddress} of a connection.
5086 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005087 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08005088 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5089 * android.os.Process#INVALID_UID} if the connection is not found.
5090 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5091 * user.
5092 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005093 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08005094 public int getConnectionOwnerUid(
5095 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005096 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5097 try {
5098 return mService.getConnectionOwnerUid(connectionInfo);
5099 } catch (RemoteException e) {
5100 throw e.rethrowFromSystemServer();
5101 }
5102 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09005103
5104 private void printStackTrace() {
5105 if (DEBUG) {
5106 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5107 final StringBuffer sb = new StringBuffer();
5108 for (int i = 3; i < callStack.length; i++) {
5109 final String stackTrace = callStack[i].toString();
5110 if (stackTrace == null || stackTrace.contains("android.os")) {
5111 break;
5112 }
5113 sb.append(" [").append(stackTrace).append("]");
5114 }
5115 Log.d(TAG, "StackLog:" + sb.toString());
5116 }
5117 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005118
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09005119 /** @hide */
5120 public TestNetworkManager startOrGetTestNetworkManager() {
5121 final IBinder tnBinder;
5122 try {
5123 tnBinder = mService.startOrGetTestNetworkService();
5124 } catch (RemoteException e) {
5125 throw e.rethrowFromSystemServer();
5126 }
5127
5128 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5129 }
5130
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09005131 /** @hide */
5132 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5133 return new ConnectivityDiagnosticsManager(mContext, mService);
5134 }
5135
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005136 /**
5137 * Simulates a Data Stall for the specified Network.
5138 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09005139 * <p>This method should only be used for tests.
5140 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005141 * <p>The caller must be the owner of the specified Network.
5142 *
5143 * @param detectionMethod The detection method used to identify the Data Stall.
5144 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
5145 * @param network The Network for which a Data Stall is being simluated.
5146 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5147 * @throws SecurityException if the caller is not the owner of the given network.
5148 * @hide
5149 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09005150 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005151 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5152 android.Manifest.permission.NETWORK_STACK})
5153 public void simulateDataStall(int detectionMethod, long timestampMillis,
5154 @NonNull Network network, @NonNull PersistableBundle extras) {
5155 try {
5156 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5157 } catch (RemoteException e) {
5158 e.rethrowFromSystemServer();
5159 }
5160 }
James Mattisdcea9fb2020-10-28 21:48:54 -07005161
Daniel Bright60f02ed2020-06-15 16:10:01 -07005162 @NonNull
5163 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5164
5165 /**
5166 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5167 * receive available QoS events related to the {@link Network} and local ip + port
5168 * specified within socketInfo.
5169 * <p/>
5170 * The same {@link QosCallback} must be unregistered before being registered a second time,
5171 * otherwise {@link QosCallbackRegistrationException} is thrown.
5172 * <p/>
5173 * This API does not, in itself, require any permission if called with a network that is not
5174 * restricted. However, the underlying implementation currently only supports the IMS network,
5175 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5176 * useful, because they'd never be called back on networks that they would have access to.
5177 *
5178 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5179 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5180 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5181 * @throws RuntimeException if the app already has too many callbacks registered.
5182 *
5183 * Exceptions after the time of registration is passed through
5184 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5185 *
5186 * @param socketInfo the socket information used to match QoS events
Daniel Bright60f02ed2020-06-15 16:10:01 -07005187 * @param executor The executor on which the callback will be invoked. The provided
5188 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Brightb953a3e2021-03-10 11:51:50 -08005189 * callbacks cannot be guaranteed.onQosCallbackRegistered
5190 * @param callback receives qos events that satisfy socketInfo
Daniel Bright60f02ed2020-06-15 16:10:01 -07005191 *
5192 * @hide
5193 */
5194 @SystemApi
5195 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Brightb953a3e2021-03-10 11:51:50 -08005196 @CallbackExecutor @NonNull final Executor executor,
5197 @NonNull final QosCallback callback) {
Daniel Bright60f02ed2020-06-15 16:10:01 -07005198 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005199 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Brightb953a3e2021-03-10 11:51:50 -08005200 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005201
5202 try {
5203 synchronized (mQosCallbackConnections) {
5204 if (getQosCallbackConnection(callback) == null) {
5205 final QosCallbackConnection connection =
5206 new QosCallbackConnection(this, callback, executor);
5207 mQosCallbackConnections.add(connection);
5208 mService.registerQosSocketCallback(socketInfo, connection);
5209 } else {
5210 Log.e(TAG, "registerQosCallback: Callback already registered");
5211 throw new QosCallbackRegistrationException();
5212 }
5213 }
5214 } catch (final RemoteException e) {
5215 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5216
5217 // The same unregister method method is called for consistency even though nothing
5218 // will be sent to the ConnectivityService since the callback was never successfully
5219 // registered.
5220 unregisterQosCallback(callback);
5221 e.rethrowFromSystemServer();
5222 } catch (final ServiceSpecificException e) {
5223 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5224 unregisterQosCallback(callback);
5225 throw convertServiceException(e);
5226 }
5227 }
5228
5229 /**
5230 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5231 * events once unregistered and can be registered a second time.
5232 * <p/>
5233 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5234 *
5235 * @param callback the callback being unregistered
5236 *
5237 * @hide
5238 */
5239 @SystemApi
5240 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5241 Objects.requireNonNull(callback, "The callback must be non-null");
5242 try {
5243 synchronized (mQosCallbackConnections) {
5244 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5245 if (connection != null) {
5246 connection.stopReceivingMessages();
5247 mService.unregisterQosCallback(connection);
5248 mQosCallbackConnections.remove(connection);
5249 } else {
5250 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5251 }
5252 }
5253 } catch (final RemoteException e) {
5254 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5255 e.rethrowFromSystemServer();
5256 }
5257 }
5258
5259 /**
5260 * Gets the connection related to the callback.
5261 *
5262 * @param callback the callback to look up
5263 * @return the related connection
5264 */
5265 @Nullable
5266 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5267 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5268 // Checking by reference here is intentional
5269 if (connection.getCallback() == callback) {
5270 return connection;
5271 }
5272 }
5273 return null;
5274 }
Junyu Lai23568a42021-01-19 11:10:56 +00005275
5276 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08005277 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Lai23568a42021-01-19 11:10:56 +00005278 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5279 * be used to request that the system provide a network without causing the network to be
5280 * in the foreground.
5281 *
5282 * <p>This method will attempt to find the best network that matches the passed
5283 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5284 * criteria. The platform will evaluate which network is the best at its own discretion.
5285 * Throughput, latency, cost per byte, policy, user preference and other considerations
5286 * may be factored in the decision of what is considered the best network.
5287 *
5288 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5289 * matching this request, while always attempting to match the request to a better network if
5290 * possible. If a better match is found, the platform will switch this request to the now-best
5291 * network and inform the app of the newly best network by invoking
5292 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5293 * will not try to maintain any other network than the best one currently matching the request:
5294 * a network not matching any network request may be disconnected at any time.
5295 *
5296 * <p>For example, an application could use this method to obtain a connected cellular network
5297 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5298 * radio to consume additional power. Or, an application could inform the system that it wants
5299 * a network supporting sending MMSes and have the system let it know about the currently best
5300 * MMS-supporting network through the provided {@link NetworkCallback}.
5301 *
5302 * <p>The status of the request can be followed by listening to the various callbacks described
5303 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5304 * used to direct traffic to the network (although accessing some networks may be subject to
5305 * holding specific permissions). Callers will learn about the specific characteristics of the
5306 * network through
5307 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5308 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5309 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5310 * matching the request at any given time; therefore when a better network matching the request
5311 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5312 * with the new network after which no further updates are given about the previously-best
5313 * network, unless it becomes the best again at some later time. All callbacks are invoked
5314 * in order on the same thread, which by default is a thread created by the framework running
5315 * in the app.
5316 *
5317 * <p>This{@link NetworkRequest} will live until released via
5318 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5319 * which point the system may let go of the network at any time.
5320 *
5321 * <p>It is presently unsupported to request a network with mutable
5322 * {@link NetworkCapabilities} such as
5323 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5324 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5325 * as these {@code NetworkCapabilities} represent states that a particular
5326 * network may never attain, and whether a network will attain these states
5327 * is unknown prior to bringing up the network so the framework does not
5328 * know how to go about satisfying a request with these capabilities.
5329 *
5330 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5331 * number of outstanding requests to 100 per app (identified by their UID), shared with
5332 * all variants of this method, of {@link #registerNetworkCallback} as well as
5333 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5334 * Requesting a network with this method will count toward this limit. If this limit is
5335 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5336 * make sure to unregister the callbacks with
5337 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5338 *
5339 * @param request {@link NetworkRequest} describing this request.
5340 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5341 * If null, the callback is invoked on the default internal Handler.
5342 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5343 * the callback must not be shared - it uniquely specifies this request.
5344 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5345 * @throws SecurityException if missing the appropriate permissions.
5346 * @throws RuntimeException if the app already has too many callbacks registered.
5347 *
5348 * @hide
5349 */
5350 @SystemApi(client = MODULE_LIBRARIES)
5351 @SuppressLint("ExecutorRegistration")
5352 @RequiresPermission(anyOf = {
5353 android.Manifest.permission.NETWORK_SETTINGS,
5354 android.Manifest.permission.NETWORK_STACK,
5355 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5356 })
5357 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaif4bc12f2021-03-09 20:49:48 +08005358 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Lai23568a42021-01-19 11:10:56 +00005359 final NetworkCapabilities nc = request.networkCapabilities;
5360 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaif4bc12f2021-03-09 20:49:48 +08005361 TYPE_NONE, new CallbackHandler(handler));
Junyu Lai23568a42021-01-19 11:10:56 +00005362 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005363
5364 /**
James Mattis6e6fabf2021-01-10 14:24:24 -08005365 * Used by automotive devices to set the network preferences used to direct traffic at an
5366 * application level as per the given OemNetworkPreferences. An example use-case would be an
5367 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5368 * vehicle via a particular network.
5369 *
5370 * Calling this will overwrite the existing preference.
5371 *
5372 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5373 * @param executor the executor on which listener will be invoked.
5374 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5375 * communicate completion of setOemNetworkPreference(). This will only be
5376 * called once upon successful completion of setOemNetworkPreference().
5377 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5378 * @throws SecurityException if missing the appropriate permissions.
5379 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005380 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005381 */
James Mattis7a253542021-01-26 16:23:52 -08005382 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005383 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005384 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005385 @Nullable @CallbackExecutor final Executor executor,
Chalard Jeancc9ad152021-03-03 16:37:13 +09005386 @Nullable final Runnable listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08005387 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5388 if (null != listener) {
5389 Objects.requireNonNull(executor, "Executor must be non-null");
5390 }
Chalard Jeancc9ad152021-03-03 16:37:13 +09005391 final IOnCompleteListener listenerInternal = listener == null ? null :
5392 new IOnCompleteListener.Stub() {
James Mattis6e6fabf2021-01-10 14:24:24 -08005393 @Override
5394 public void onComplete() {
Chalard Jeancc9ad152021-03-03 16:37:13 +09005395 executor.execute(listener::run);
James Mattis6e6fabf2021-01-10 14:24:24 -08005396 }
5397 };
5398
5399 try {
5400 mService.setOemNetworkPreference(preference, listenerInternal);
5401 } catch (RemoteException e) {
5402 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5403 throw e.rethrowFromSystemServer();
5404 }
5405 }
lucaslin1a6095c2021-03-12 00:46:33 +08005406
Chalard Jean03433052021-02-25 17:23:40 +09005407 /**
5408 * Request that a user profile is put by default on a network matching a given preference.
5409 *
5410 * See the documentation for the individual preferences for a description of the supported
5411 * behaviors.
5412 *
5413 * @param profile the profile concerned.
5414 * @param preference the preference for this profile.
5415 * @param executor an executor to execute the listener on. Optional if listener is null.
5416 * @param listener an optional listener to listen for completion of the operation.
5417 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5418 * @throws SecurityException if missing the appropriate permissions.
5419 * @hide
5420 */
Chalard Jeancc9ad152021-03-03 16:37:13 +09005421 // This function is for establishing per-profile default networking and can only be called by
5422 // the device policy manager, running as the system server. It would make no sense to call it
5423 // on a context for a user because it does not establish a setting on behalf of a user, rather
5424 // it establishes a setting for a user on behalf of the DPM.
5425 @SuppressLint({"UserHandle"})
5426 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09005427 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5428 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5429 @ProfileNetworkPreference final int preference,
5430 @Nullable @CallbackExecutor final Executor executor,
5431 @Nullable final Runnable listener) {
5432 if (null != listener) {
5433 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5434 }
5435 final IOnCompleteListener proxy;
5436 if (null == listener) {
5437 proxy = null;
5438 } else {
5439 proxy = new IOnCompleteListener.Stub() {
5440 @Override
5441 public void onComplete() {
5442 executor.execute(listener::run);
5443 }
5444 };
5445 }
5446 try {
5447 mService.setProfileNetworkPreference(profile, preference, proxy);
5448 } catch (RemoteException e) {
5449 throw e.rethrowFromSystemServer();
5450 }
5451 }
5452
lucaslin1a6095c2021-03-12 00:46:33 +08005453 // The first network ID of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005454 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin1a6095c2021-03-12 00:46:33 +08005455 // The network ID range of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005456 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin1a6095c2021-03-12 00:46:33 +08005457
5458 /**
5459 * Get the network ID range reserved for IPSec tunnel interfaces.
5460 *
5461 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5462 * @hide
5463 */
5464 @SystemApi(client = MODULE_LIBRARIES)
5465 @NonNull
5466 public static Range<Integer> getIpSecNetIdRange() {
5467 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5468 }
lucaslin50205af2021-03-12 16:11:27 +08005469
5470 /**
5471 * Get private DNS mode from settings.
5472 *
lucaslin73c98602021-03-17 14:53:35 +08005473 * @param context The Context to query the private DNS mode from settings.
lucaslin50205af2021-03-12 16:11:27 +08005474 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5475 *
5476 * @hide
5477 */
5478 @SystemApi(client = MODULE_LIBRARIES)
5479 @NonNull
5480 @PrivateDnsMode
lucaslinacd3ded2021-03-16 17:11:14 +08005481 public static String getPrivateDnsMode(@NonNull Context context) {
5482 final ContentResolver cr = context.getContentResolver();
lucaslin50205af2021-03-12 16:11:27 +08005483 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5484 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5485 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5486 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5487 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5488 return mode;
5489 }
paulhu28321462021-03-25 12:36:56 +08005490
5491 /**
5492 * Set private DNS mode to settings.
5493 *
5494 * @param context The {@link Context} to set the private DNS mode.
5495 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5496 *
5497 * @hide
5498 */
5499 @SystemApi(client = MODULE_LIBRARIES)
5500 public static void setPrivateDnsMode(@NonNull Context context,
5501 @NonNull @PrivateDnsMode String mode) {
5502 if (!(mode == PRIVATE_DNS_MODE_OFF
5503 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5504 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5505 throw new IllegalArgumentException("Invalid private dns mode");
5506 }
5507 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5508 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005509}