blob: 2f6c2a27397147ff01c9abd8ec9960d3a6d3e4da [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
lifr5f1c1102021-03-30 21:04:53 +08001196 *
1197 * @hide
Robin Leeda4d2e22016-03-24 12:07:00 +00001198 */
paulhuec0a9632019-08-12 16:25:11 +08001199 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001200 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001201 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001202 return getActiveNetworkForUid(uid, false);
1203 }
1204
1205 /** {@hide} */
1206 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001207 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001208 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001209 } catch (RemoteException e) {
1210 throw e.rethrowFromSystemServer();
1211 }
1212 }
1213
1214 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001215 * Adds or removes a requirement for given UID ranges to use the VPN.
1216 *
1217 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1218 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1219 * otherwise have permission to bypass the VPN (e.g., because they have the
1220 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1221 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1222 * set to {@code false}, a previously-added restriction is removed.
1223 * <p>
1224 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1225 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1226 * remove a previously-added range, the exact range must be removed as is.
1227 * <p>
1228 * The changes are applied asynchronously and may not have been applied by the time the method
1229 * returns. Apps will be notified about any changes that apply to them via
1230 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1231 * effect.
1232 * <p>
1233 * This method should be called only by the VPN code.
1234 *
1235 * @param ranges the UID ranges to restrict
1236 * @param requireVpn whether the specified UID ranges must use a VPN
1237 *
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001238 * @hide
1239 */
1240 @RequiresPermission(anyOf = {
1241 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001242 android.Manifest.permission.NETWORK_STACK,
1243 android.Manifest.permission.NETWORK_SETTINGS})
1244 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001245 public void setRequireVpnForUids(boolean requireVpn,
1246 @NonNull Collection<Range<Integer>> ranges) {
1247 Objects.requireNonNull(ranges);
1248 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1249 // This method is not necessarily expected to be used outside the system server, so
1250 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1251 // stack process, or by tests.
1252 UidRange[] rangesArray = new UidRange[ranges.size()];
1253 int index = 0;
1254 for (Range<Integer> range : ranges) {
1255 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1256 }
1257 try {
1258 mService.setRequireVpnForUids(requireVpn, rangesArray);
1259 } catch (RemoteException e) {
1260 throw e.rethrowFromSystemServer();
1261 }
1262 }
1263
1264 /**
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001265 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1266 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1267 * but is still supported for backwards compatibility.
1268 * <p>
1269 * This type of VPN is assumed always to use the system default network, and must always declare
1270 * exactly one underlying network, which is the network that was the default when the VPN
1271 * connected.
1272 * <p>
1273 * Calling this method with {@code true} enables legacy behaviour, specifically:
1274 * <ul>
1275 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1276 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1277 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1278 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1279 * underlying the VPN.</li>
1280 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1281 * similarly replaced by the VPN network state.</li>
1282 * <li>Information on current network interfaces passed to NetworkStatsService will not
1283 * include any VPN interfaces.</li>
1284 * </ul>
1285 *
1286 * @param enabled whether legacy lockdown VPN is enabled or disabled
1287 *
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001288 * @hide
1289 */
1290 @RequiresPermission(anyOf = {
1291 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin5140e482021-03-22 11:51:27 +08001292 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001293 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin5140e482021-03-22 11:51:27 +08001294 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001295 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1296 try {
1297 mService.setLegacyLockdownVpnEnabled(enabled);
1298 } catch (RemoteException e) {
1299 throw e.rethrowFromSystemServer();
1300 }
1301 }
1302
1303 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001304 * Returns details about the currently active default data network
1305 * for a given uid. This is for internal use only to avoid spying
1306 * other apps.
1307 *
1308 * @return a {@link NetworkInfo} object for the current default network
1309 * for the given uid or {@code null} if no default network is
1310 * available for the specified uid.
1311 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001312 * {@hide}
1313 */
paulhuec0a9632019-08-12 16:25:11 +08001314 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001315 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001316 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001317 return getActiveNetworkInfoForUid(uid, false);
1318 }
1319
1320 /** {@hide} */
1321 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001322 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001323 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001324 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001325 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001326 }
1327 }
1328
Robert Greenwalt26744a52013-02-15 10:56:35 -08001329 /**
1330 * Returns connection status information about a particular
1331 * network type.
1332 *
1333 * @param networkType integer specifying which networkType in
1334 * which you're interested.
1335 * @return a {@link NetworkInfo} object for the requested
1336 * network type or {@code null} if the type is not
Chalard Jean7c85ba42018-03-29 17:45:24 +09001337 * supported by the device. If {@code networkType} is
1338 * TYPE_VPN and a VPN is active for the calling app,
1339 * then this method will try to return one of the
1340 * underlying networks for the VPN or null if the
1341 * VPN agent didn't specify any.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001342 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001343 * @deprecated This method does not support multiple connected networks
1344 * of the same type. Use {@link #getAllNetworks} and
1345 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001346 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001347 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001348 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001349 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001350 public NetworkInfo getNetworkInfo(int networkType) {
1351 try {
1352 return mService.getNetworkInfo(networkType);
1353 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001354 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001355 }
1356 }
1357
Robert Greenwalt26744a52013-02-15 10:56:35 -08001358 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001359 * Returns connection status information about a particular
1360 * Network.
1361 *
1362 * @param network {@link Network} specifying which network
1363 * in which you're interested.
1364 * @return a {@link NetworkInfo} object for the requested
1365 * network or {@code null} if the {@code Network}
1366 * is not valid.
junyulai5c2f6262018-12-13 12:47:51 +08001367 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001368 */
junyulai5c2f6262018-12-13 12:47:51 +08001369 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001370 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001371 @Nullable
1372 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001373 return getNetworkInfoForUid(network, Process.myUid(), false);
1374 }
1375
1376 /** {@hide} */
1377 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001378 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001379 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001380 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001381 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001382 }
1383 }
1384
1385 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001386 * Returns connection status information about all network
1387 * types supported by the device.
1388 *
1389 * @return an array of {@link NetworkInfo} objects. Check each
1390 * {@link NetworkInfo#getType} for which type each applies.
1391 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001392 * @deprecated This method does not support multiple connected networks
1393 * of the same type. Use {@link #getAllNetworks} and
1394 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001395 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001396 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001397 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001398 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001399 public NetworkInfo[] getAllNetworkInfo() {
1400 try {
1401 return mService.getAllNetworkInfo();
1402 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001403 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001404 }
1405 }
1406
Robert Greenwalt26744a52013-02-15 10:56:35 -08001407 /**
junyulai57840802021-03-03 12:09:05 +08001408 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1409 * connected.
1410 * @hide
1411 */
1412 @SystemApi(client = MODULE_LIBRARIES)
1413 @RequiresPermission(anyOf = {
1414 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1415 android.Manifest.permission.NETWORK_STACK,
1416 android.Manifest.permission.NETWORK_SETTINGS})
1417 @NonNull
1418 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1419 try {
1420 return mService.getAllNetworkStateSnapshot();
1421 } catch (RemoteException e) {
1422 throw e.rethrowFromSystemServer();
1423 }
1424 }
1425
1426 /**
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001427 * Returns the {@link Network} object currently serving a given type, or
1428 * null if the given type is not connected.
1429 *
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001430 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04001431 * @deprecated This method does not support multiple connected networks
1432 * of the same type. Use {@link #getAllNetworks} and
1433 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001434 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001435 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001436 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001437 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001438 public Network getNetworkForType(int networkType) {
1439 try {
1440 return mService.getNetworkForType(networkType);
1441 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001442 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001443 }
1444 }
1445
1446 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001447 * Returns an array of all {@link Network} currently tracked by the
1448 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001449 *
1450 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001451 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001452 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001453 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001454 public Network[] getAllNetworks() {
1455 try {
1456 return mService.getAllNetworks();
1457 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001458 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001459 }
1460 }
1461
1462 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001463 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001464 * the Networks that applications run by the given user will use by default.
1465 * @hide
1466 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001467 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001468 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1469 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001470 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001471 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001472 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001473 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001474 }
1475 }
1476
1477 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001478 * Returns the IP information for the current default network.
1479 *
1480 * @return a {@link LinkProperties} object describing the IP info
1481 * for the current default network, or {@code null} if there
1482 * is no current default network.
1483 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001484 * {@hide}
Chalard Jeancc47b522019-01-11 16:47:53 +09001485 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1486 * value of {@link #getActiveNetwork()} instead. In particular,
1487 * this method will return non-null LinkProperties even if the
1488 * app is blocked by policy from using this network.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001489 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001490 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-01-11 16:47:53 +09001491 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001492 public LinkProperties getActiveLinkProperties() {
1493 try {
1494 return mService.getActiveLinkProperties();
1495 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001496 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001497 }
1498 }
1499
Robert Greenwalt26744a52013-02-15 10:56:35 -08001500 /**
1501 * Returns the IP information for a given network type.
1502 *
1503 * @param networkType the network type of interest.
1504 * @return a {@link LinkProperties} object describing the IP info
1505 * for the given networkType, or {@code null} if there is
1506 * no current default network.
1507 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001508 * {@hide}
Paul Jensena8e6dc62015-03-18 12:23:02 -04001509 * @deprecated This method does not support multiple connected networks
1510 * of the same type. Use {@link #getAllNetworks},
1511 * {@link #getNetworkInfo(android.net.Network)}, and
1512 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001513 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001514 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001515 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001516 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001517 public LinkProperties getLinkProperties(int networkType) {
1518 try {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001519 return mService.getLinkPropertiesForType(networkType);
1520 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001521 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001522 }
1523 }
1524
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001525 /**
1526 * Get the {@link LinkProperties} for the given {@link Network}. This
1527 * will return {@code null} if the network is unknown.
1528 *
1529 * @param network The {@link Network} object identifying the network in question.
1530 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001531 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001532 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001533 @Nullable
1534 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001535 try {
1536 return mService.getLinkProperties(network);
1537 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001538 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001539 }
1540 }
1541
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001542 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001543 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001544 * will return {@code null} if the network is unknown.
1545 *
Roshan Pius7992afd2020-12-22 15:10:42 -08001546 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1547 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1548 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1549 * this location sensitive information (subject to app's location permissions) will be
1550 * noted by system. To include any location sensitive data in {@link TransportInfo},
1551 * use a {@link NetworkCallback} with
1552 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1553 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001554 * @param network The {@link Network} object identifying the network in question.
Roshan Pius7992afd2020-12-22 15:10:42 -08001555 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001556 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001557 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001558 @Nullable
1559 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001560 try {
Roshan Piusc97d8062020-12-17 14:53:09 -08001561 return mService.getNetworkCapabilities(
1562 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001563 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001564 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001565 }
1566 }
1567
Robert Greenwalt26744a52013-02-15 10:56:35 -08001568 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001569 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001570 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1571 * portal is present.
1572 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1573 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1574 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001575 * The system network validation may be using different strategies to detect captive portals,
1576 * so this method does not necessarily return a URL used by the system. It only returns a URL
1577 * that may be relevant for other components trying to detect captive portals.
paulhuec0a9632019-08-12 16:25:11 +08001578 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001579 * @hide
paulhuec0a9632019-08-12 16:25:11 +08001580 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1581 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001582 */
paulhuec0a9632019-08-12 16:25:11 +08001583 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001584 @SystemApi
paulhuec0a9632019-08-12 16:25:11 +08001585 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001586 public String getCaptivePortalServerUrl() {
1587 try {
1588 return mService.getCaptivePortalServerUrl();
1589 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001590 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001591 }
1592 }
1593
1594 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001595 * Tells the underlying networking system that the caller wants to
1596 * begin using the named feature. The interpretation of {@code feature}
1597 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001598 *
1599 * <p>This method requires the caller to hold either the
1600 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1601 * or the ability to modify system settings as determined by
1602 * {@link android.provider.Settings.System#canWrite}.</p>
1603 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001604 * @param networkType specifies which network the request pertains to
1605 * @param feature the name of the feature to be used
1606 * @return an integer value representing the outcome of the request.
1607 * The interpretation of this value is specific to each networking
1608 * implementation+feature combination, except that the value {@code -1}
1609 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001610 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001611 * @deprecated Deprecated in favor of the cleaner
1612 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001613 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001614 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001615 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001616 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001617 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001618 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001619 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001620 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1621 if (netCap == null) {
1622 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1623 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001624 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001625 }
1626
1627 NetworkRequest request = null;
1628 synchronized (sLegacyRequests) {
1629 LegacyRequest l = sLegacyRequests.get(netCap);
1630 if (l != null) {
1631 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1632 renewRequestLocked(l);
1633 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001634 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001635 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001636 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001637 }
1638 }
1639
1640 request = requestNetworkForFeatureLocked(netCap);
1641 }
1642 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001643 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001644 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001645 } else {
1646 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001647 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001648 }
1649 }
1650
1651 /**
1652 * Tells the underlying networking system that the caller is finished
1653 * using the named feature. The interpretation of {@code feature}
1654 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001655 *
1656 * <p>This method requires the caller to hold either the
1657 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1658 * or the ability to modify system settings as determined by
1659 * {@link android.provider.Settings.System#canWrite}.</p>
1660 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001661 * @param networkType specifies which network the request pertains to
1662 * @param feature the name of the feature that is no longer needed
1663 * @return an integer value representing the outcome of the request.
1664 * The interpretation of this value is specific to each networking
1665 * implementation+feature combination, except that the value {@code -1}
1666 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001667 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001668 * @deprecated Deprecated in favor of the cleaner
1669 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001670 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001671 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001672 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001673 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001674 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001675 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001676 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001677 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1678 if (netCap == null) {
1679 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1680 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001681 return -1;
1682 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001683
Paul Jensen034dea32014-12-17 10:39:34 -05001684 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001685 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001686 }
1687 return 1;
1688 }
1689
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001690 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001691 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1692 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001693 switch (feature) {
1694 case "enableCBS":
1695 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1696 case "enableDUN":
1697 case "enableDUNAlways":
1698 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1699 case "enableFOTA":
1700 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1701 case "enableHIPRI":
1702 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1703 case "enableIMS":
1704 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1705 case "enableMMS":
1706 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1707 case "enableSUPL":
1708 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1709 default:
1710 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001711 }
Erik Kline50068e52017-01-26 18:08:28 +09001712 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1713 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001714 }
1715 return null;
1716 }
1717
Robert Greenwalt5a367872014-06-02 15:32:02 -07001718 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001719 if (netCap == null) return TYPE_NONE;
1720 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1721 return TYPE_MOBILE_CBS;
1722 }
1723 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1724 return TYPE_MOBILE_IMS;
1725 }
1726 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1727 return TYPE_MOBILE_FOTA;
1728 }
1729 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1730 return TYPE_MOBILE_DUN;
1731 }
1732 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1733 return TYPE_MOBILE_SUPL;
1734 }
1735 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1736 return TYPE_MOBILE_MMS;
1737 }
1738 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1739 return TYPE_MOBILE_HIPRI;
1740 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001741 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1742 return TYPE_WIFI_P2P;
1743 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001744 return TYPE_NONE;
1745 }
1746
1747 private static class LegacyRequest {
1748 NetworkCapabilities networkCapabilities;
1749 NetworkRequest networkRequest;
1750 int expireSequenceNumber;
1751 Network currentNetwork;
1752 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001753
1754 private void clearDnsBinding() {
1755 if (currentNetwork != null) {
1756 currentNetwork = null;
1757 setProcessDefaultNetworkForHostResolution(null);
1758 }
1759 }
1760
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001761 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001762 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001763 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001764 currentNetwork = network;
1765 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001766 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001767 }
1768 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001769 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001770 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001771 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1772 }
1773 };
1774 }
1775
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001776 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001777 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1778 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001779
1780 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1781 synchronized (sLegacyRequests) {
1782 LegacyRequest l = sLegacyRequests.get(netCap);
1783 if (l != null) return l.networkRequest;
1784 }
1785 return null;
1786 }
1787
1788 private void renewRequestLocked(LegacyRequest l) {
1789 l.expireSequenceNumber++;
1790 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1791 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1792 }
1793
1794 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1795 int ourSeqNum = -1;
1796 synchronized (sLegacyRequests) {
1797 LegacyRequest l = sLegacyRequests.get(netCap);
1798 if (l == null) return;
1799 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001800 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001801 }
1802 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1803 }
1804
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001805 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001806 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1807 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001808 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001809 try {
1810 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001811 } catch (RemoteException e) {
1812 throw e.rethrowFromSystemServer();
1813 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001814 LegacyRequest l = new LegacyRequest();
1815 l.networkCapabilities = netCap;
1816 l.delay = delay;
1817 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001818 l.networkRequest = sendRequestForNetwork(
1819 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001820 if (l.networkRequest == null) return null;
1821 sLegacyRequests.put(netCap, l);
1822 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1823 return l.networkRequest;
1824 }
1825
1826 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1827 if (delay >= 0) {
1828 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001829 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001830 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1831 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001832 }
1833 }
1834
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001835 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001836 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1837 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001838 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001839 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001840 }
Paul Jensen034dea32014-12-17 10:39:34 -05001841 if (l == null) return false;
1842 unregisterNetworkCallback(l.networkCallback);
1843 l.clearDnsBinding();
1844 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001845 }
1846
Erik Kline50068e52017-01-26 18:08:28 +09001847 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1848 static {
1849 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1850 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1851 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1852 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1853 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1854 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1855 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1856 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1857 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1858 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1859 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1860 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1861 }
1862
1863 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1864 static {
1865 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1866 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1867 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1868 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1869 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1870 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1871 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1872 }
1873
1874 /**
1875 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1876 * instance suitable for registering a request or callback. Throws an
1877 * IllegalArgumentException if no mapping from the legacy type to
1878 * NetworkCapabilities is known.
1879 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001880 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1881 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001882 * @hide
1883 */
1884 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1885 final NetworkCapabilities nc = new NetworkCapabilities();
1886
1887 // Map from type to transports.
1888 final int NOT_FOUND = -1;
1889 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001890 if (transport == NOT_FOUND) {
1891 throw new IllegalArgumentException("unknown legacy type: " + type);
1892 }
Erik Kline50068e52017-01-26 18:08:28 +09001893 nc.addTransportType(transport);
1894
1895 // Map from type to capabilities.
1896 nc.addCapability(sLegacyTypeToCapability.get(
1897 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1898 nc.maybeMarkCapabilitiesRestricted();
1899 return nc;
1900 }
1901
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001902 /** @hide */
1903 public static class PacketKeepaliveCallback {
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001904 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayevfc03a992019-11-15 19:12:49 +00001905 public PacketKeepaliveCallback() {
1906 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001907 /** The requested keepalive was successfully started. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001908 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001909 public void onStarted() {}
1910 /** The keepalive was successfully stopped. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001911 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001912 public void onStopped() {}
1913 /** An error occurred. */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001914 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001915 public void onError(int error) {}
1916 }
1917
1918 /**
1919 * Allows applications to request that the system periodically send specific packets on their
1920 * behalf, using hardware offload to save battery power.
1921 *
1922 * To request that the system send keepalives, call one of the methods that return a
1923 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1924 * passing in a non-null callback. If the callback is successfully started, the callback's
1925 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1926 * specifying one of the {@code ERROR_*} constants in this class.
1927 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001928 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1929 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1930 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001931 *
junyulaia86defc2018-12-27 17:25:29 +08001932 * @deprecated Use {@link SocketKeepalive} instead.
1933 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001934 * @hide
1935 */
1936 public class PacketKeepalive {
1937
1938 private static final String TAG = "PacketKeepalive";
1939
1940 /** @hide */
1941 public static final int SUCCESS = 0;
1942
1943 /** @hide */
1944 public static final int NO_KEEPALIVE = -1;
1945
1946 /** @hide */
1947 public static final int BINDER_DIED = -10;
1948
1949 /** The specified {@code Network} is not connected. */
1950 public static final int ERROR_INVALID_NETWORK = -20;
1951 /** The specified IP addresses are invalid. For example, the specified source IP address is
1952 * not configured on the specified {@code Network}. */
1953 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1954 /** The requested port is invalid. */
1955 public static final int ERROR_INVALID_PORT = -22;
1956 /** The packet length is invalid (e.g., too long). */
1957 public static final int ERROR_INVALID_LENGTH = -23;
1958 /** The packet transmission interval is invalid (e.g., too short). */
1959 public static final int ERROR_INVALID_INTERVAL = -24;
1960
1961 /** The hardware does not support this request. */
1962 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001963 /** The hardware returned an error. */
1964 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001965
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001966 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001967 public static final int NATT_PORT = 4500;
1968
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001969 /** The minimum interval in seconds between keepalive packet transmissions */
1970 public static final int MIN_INTERVAL = 10;
1971
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001972 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001973 private final ISocketKeepaliveCallback mCallback;
1974 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001975
1976 private volatile Integer mSlot;
1977
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00001978 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001979 public void stop() {
1980 try {
junyulai9f872232019-01-16 20:23:34 +08001981 mExecutor.execute(() -> {
1982 try {
1983 if (mSlot != null) {
1984 mService.stopKeepalive(mNetwork, mSlot);
1985 }
1986 } catch (RemoteException e) {
1987 Log.e(TAG, "Error stopping packet keepalive: ", e);
1988 throw e.rethrowFromSystemServer();
1989 }
1990 });
1991 } catch (RejectedExecutionException e) {
1992 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001993 }
1994 }
1995
1996 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00001997 Objects.requireNonNull(network, "network cannot be null");
1998 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001999 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08002000 mExecutor = Executors.newSingleThreadExecutor();
2001 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002002 @Override
junyulai9f872232019-01-16 20:23:34 +08002003 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08002004 final long token = Binder.clearCallingIdentity();
2005 try {
2006 mExecutor.execute(() -> {
2007 mSlot = slot;
2008 callback.onStarted();
2009 });
2010 } finally {
2011 Binder.restoreCallingIdentity(token);
2012 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002013 }
junyulai9f872232019-01-16 20:23:34 +08002014
2015 @Override
2016 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08002017 final long token = Binder.clearCallingIdentity();
2018 try {
2019 mExecutor.execute(() -> {
2020 mSlot = null;
2021 callback.onStopped();
2022 });
2023 } finally {
2024 Binder.restoreCallingIdentity(token);
2025 }
junyulai9f872232019-01-16 20:23:34 +08002026 mExecutor.shutdown();
2027 }
2028
2029 @Override
2030 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08002031 final long token = Binder.clearCallingIdentity();
2032 try {
2033 mExecutor.execute(() -> {
2034 mSlot = null;
2035 callback.onError(error);
2036 });
2037 } finally {
2038 Binder.restoreCallingIdentity(token);
2039 }
junyulai9f872232019-01-16 20:23:34 +08002040 mExecutor.shutdown();
2041 }
2042
2043 @Override
2044 public void onDataReceived() {
2045 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2046 // this callback when data is received.
2047 }
2048 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002049 }
2050 }
2051
2052 /**
2053 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2054 *
junyulaia86defc2018-12-27 17:25:29 +08002055 * @deprecated Use {@link #createSocketKeepalive} instead.
2056 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002057 * @hide
2058 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002059 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002060 public PacketKeepalive startNattKeepalive(
2061 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2062 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2063 final PacketKeepalive k = new PacketKeepalive(network, callback);
2064 try {
junyulai9f872232019-01-16 20:23:34 +08002065 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002066 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2067 } catch (RemoteException e) {
2068 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08002069 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002070 }
2071 return k;
2072 }
2073
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002074 // Construct an invalid fd.
2075 private ParcelFileDescriptor createInvalidFd() {
2076 final int invalidFd = -1;
2077 return ParcelFileDescriptor.adoptFd(invalidFd);
2078 }
2079
The Android Open Source Project28527d22009-03-03 19:31:44 -08002080 /**
junyulaia86defc2018-12-27 17:25:29 +08002081 * Request that keepalives be started on a IPsec NAT-T socket.
2082 *
2083 * @param network The {@link Network} the socket is on.
2084 * @param socket The socket that needs to be kept alive.
2085 * @param source The source address of the {@link UdpEncapsulationSocket}.
2086 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2087 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2088 * must run callback sequentially, otherwise the order of callbacks cannot be
2089 * guaranteed.
2090 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2091 * changes. Must be extended by applications that use this API.
2092 *
junyulaic7ea1242019-01-08 20:04:33 +08002093 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2094 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08002095 **/
junyulai61143782019-03-04 22:45:36 +08002096 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08002097 @NonNull UdpEncapsulationSocket socket,
2098 @NonNull InetAddress source,
2099 @NonNull InetAddress destination,
2100 @NonNull @CallbackExecutor Executor executor,
2101 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002102 ParcelFileDescriptor dup;
2103 try {
junyulaic4fb2482019-03-27 11:00:37 +08002104 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2105 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08002106 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2107 } catch (IOException ignored) {
2108 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2109 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002110 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002111 }
2112 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2113 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08002114 }
2115
2116 /**
2117 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2118 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2119 *
2120 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08002121 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2122 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2123 * from that port.
junyulai48a59382019-01-15 11:32:44 +08002124 * @param source The source address of the {@link UdpEncapsulationSocket}.
2125 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2126 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2127 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2128 * must run callback sequentially, otherwise the order of callbacks cannot be
2129 * guaranteed.
2130 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2131 * changes. Must be extended by applications that use this API.
2132 *
junyulaic7ea1242019-01-08 20:04:33 +08002133 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2134 * given socket.
junyulai48a59382019-01-15 11:32:44 +08002135 * @hide
2136 */
2137 @SystemApi
2138 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002139 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2140 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08002141 @NonNull InetAddress source,
2142 @NonNull InetAddress destination,
2143 @NonNull @CallbackExecutor Executor executor,
2144 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002145 ParcelFileDescriptor dup;
2146 try {
junyulaic4fb2482019-03-27 11:00:37 +08002147 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08002148 dup = pfd.dup();
2149 } catch (IOException ignored) {
2150 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2151 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002152 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002153 }
2154 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VAN642d6ab2021-03-11 10:56:49 +00002155 -1 /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08002156 }
2157
2158 /**
junyulaic7ea1242019-01-08 20:04:33 +08002159 * Request that keepalives be started on a TCP socket.
2160 * The socket must be established.
2161 *
2162 * @param network The {@link Network} the socket is on.
2163 * @param socket The socket that needs to be kept alive.
2164 * @param executor The executor on which callback will be invoked. This implementation assumes
2165 * the provided {@link Executor} runs the callbacks in sequence with no
2166 * concurrency. Failing this, no guarantee of correctness can be made. It is
2167 * the responsibility of the caller to ensure the executor provides this
2168 * guarantee. A simple way of creating such an executor is with the standard
2169 * tool {@code Executors.newSingleThreadExecutor}.
2170 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2171 * changes. Must be extended by applications that use this API.
2172 *
2173 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2174 * given socket.
2175 * @hide
2176 */
2177 @SystemApi
2178 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002179 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002180 @NonNull Socket socket,
2181 @NonNull Executor executor,
2182 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002183 ParcelFileDescriptor dup;
2184 try {
2185 dup = ParcelFileDescriptor.fromSocket(socket);
2186 } catch (UncheckedIOException ignored) {
2187 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2188 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002189 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002190 }
2191 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002192 }
2193
2194 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002195 * Ensure that a network route exists to deliver traffic to the specified
2196 * host via the specified network interface. An attempt to add a route that
2197 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002198 *
2199 * <p>This method requires the caller to hold either the
2200 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2201 * or the ability to modify system settings as determined by
2202 * {@link android.provider.Settings.System#canWrite}.</p>
2203 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002204 * @param networkType the type of the network over which traffic to the specified
2205 * host is to be routed
2206 * @param hostAddress the IP address of the host to which the route is desired
2207 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002208 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002209 * @deprecated Deprecated in favor of the
2210 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2211 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002212 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002213 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002214 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002215 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002216 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002217 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002218 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002219 }
2220
2221 /**
2222 * Ensure that a network route exists to deliver traffic to the specified
2223 * host via the specified network interface. An attempt to add a route that
2224 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002225 *
2226 * <p>This method requires the caller to hold either the
2227 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2228 * or the ability to modify system settings as determined by
2229 * {@link android.provider.Settings.System#canWrite}.</p>
2230 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002231 * @param networkType the type of the network over which traffic to the specified
2232 * host is to be routed
2233 * @param hostAddress the IP address of the host to which the route is desired
2234 * @return {@code true} on success, {@code false} on failure
2235 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002236 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002237 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002238 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002239 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002240 @UnsupportedAppUsage
lucaslin5140e482021-03-22 11:51:27 +08002241 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002242 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002243 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002244 try {
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002245 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2246 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002247 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002248 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002249 }
2250 }
2251
2252 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002253 * @return the context's attribution tag
2254 */
2255 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2256 private @Nullable String getAttributionTag() {
2257 return mContext.getAttributionTag();
2258 }
2259
2260 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002261 * Returns the value of the setting for background data usage. If false,
2262 * applications should not use the network if the application is not in the
2263 * foreground. Developers should respect this setting, and check the value
2264 * of this before performing any background data operations.
2265 * <p>
2266 * All applications that have background services that use the network
2267 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002268 * <p>
Scott Main50589142011-10-06 18:32:43 -07002269 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002270 * background data depends on several combined factors, and this method will
2271 * always return {@code true}. Instead, when background data is unavailable,
2272 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002273 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002274 * @return Whether background data usage is allowed.
2275 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002276 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002277 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002278 // assume that background data is allowed; final authority is
2279 // NetworkInfo which may be blocked.
2280 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002281 }
2282
2283 /**
2284 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002285 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002286 * @param allowBackgroundData Whether an application should use data while
2287 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002288 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002289 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2290 * @see #getBackgroundDataSetting()
2291 * @hide
2292 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002293 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002294 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002295 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002296 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002297 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002298
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002299 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002300 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002301 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002302 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002303 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002304 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002305 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002306 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2307 if (tm != null) {
2308 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2309 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2310 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2311 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2312 + " retVal=" + retVal);
2313 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002314 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002315 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002316 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002317 }
2318
The Android Open Source Project28527d22009-03-03 19:31:44 -08002319 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002320 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002321 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002322 */
2323 public interface OnNetworkActiveListener {
2324 /**
2325 * Called on the main thread of the process to report that the current data network
2326 * has become active, and it is now a good time to perform any pending network
2327 * operations. Note that this listener only tells you when the network becomes
2328 * active; if at any other time you want to know whether it is active (and thus okay
2329 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002330 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002331 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002332 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002333 }
2334
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002335 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002336 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002337
2338 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002339 * Start listening to reports when the system's default data network is active, meaning it is
2340 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2341 * to determine the current state of the system's default network after registering the
2342 * listener.
2343 * <p>
2344 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002345 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002346 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002347 *
2348 * @param l The listener to be told when the network is active.
2349 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002350 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002351 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2352 @Override
2353 public void onNetworkActive() throws RemoteException {
2354 l.onNetworkActive();
2355 }
2356 };
2357
2358 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002359 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002360 mNetworkActivityListeners.put(l, rl);
2361 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002362 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002363 }
2364 }
2365
2366 /**
2367 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002368 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002369 *
2370 * @param l Previously registered listener.
2371 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002372 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002373 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002374 if (rl == null) {
2375 throw new IllegalArgumentException("Listener was not registered.");
2376 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002377 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002378 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002379 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002380 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002381 }
2382 }
2383
2384 /**
2385 * Return whether the data network is currently active. An active network means that
2386 * it is currently in a high power state for performing data transmission. On some
2387 * types of networks, it may be expensive to move and stay in such a state, so it is
2388 * more power efficient to batch network traffic together when the radio is already in
2389 * this state. This method tells you whether right now is currently a good time to
2390 * initiate network traffic, as the network is already active.
2391 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002392 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002393 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002394 return mService.isDefaultNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002395 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002396 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002397 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002398 }
2399
2400 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002401 * {@hide}
2402 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002403 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002404 mContext = Objects.requireNonNull(context, "missing context");
2405 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002406 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002407 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002408 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002409
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002410 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002411 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002412 public static ConnectivityManager from(Context context) {
2413 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2414 }
2415
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002416 /** @hide */
2417 public NetworkRequest getDefaultRequest() {
2418 try {
2419 // This is not racy as the default request is final in ConnectivityService.
2420 return mService.getDefaultRequest();
2421 } catch (RemoteException e) {
2422 throw e.rethrowFromSystemServer();
2423 }
2424 }
2425
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002426 /**
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07002427 * Check if the package is a allowed to write settings. This also accounts that such an access
2428 * happened.
2429 *
2430 * @return {@code true} iff the package is allowed to write settings.
2431 */
2432 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2433 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2434 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2435 boolean throwException) {
2436 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2437 callingAttributionTag, throwException);
2438 }
2439
2440 /**
Paul Jensen12131352014-12-10 15:12:18 -05002441 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2442 * situations where a Context pointer is unavailable.
2443 * @hide
2444 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002445 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002446 static ConnectivityManager getInstanceOrNull() {
2447 return sInstance;
2448 }
2449
2450 /**
2451 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2452 * situations where a Context pointer is unavailable.
2453 * @hide
2454 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002455 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002456 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002457 private static ConnectivityManager getInstance() {
2458 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002459 throw new IllegalStateException("No ConnectivityManager yet constructed");
2460 }
Paul Jensen895c3942015-03-10 10:54:12 -04002461 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002462 }
2463
2464 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002465 * Get the set of tetherable, available interfaces. This list is limited by
2466 * device configuration and current interface existence.
2467 *
2468 * @return an array of 0 or more Strings of tetherable interface names.
2469 *
markchien75721e42020-01-21 13:11:06 +08002470 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002471 * {@hide}
2472 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002473 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002474 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002475 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002476 public String[] getTetherableIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002477 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002478 }
2479
2480 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002481 * Get the set of tethered interfaces.
2482 *
2483 * @return an array of 0 or more String of currently tethered interface names.
2484 *
markchien75721e42020-01-21 13:11:06 +08002485 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002486 * {@hide}
2487 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002488 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002489 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002490 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002491 public String[] getTetheredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002492 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002493 }
2494
2495 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002496 * Get the set of interface names which attempted to tether but
2497 * failed. Re-attempting to tether may cause them to reset to the Tethered
2498 * state. Alternatively, causing the interface to be destroyed and recreated
2499 * may cause them to reset to the available state.
2500 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2501 * information on the cause of the errors.
2502 *
2503 * @return an array of 0 or more String indicating the interface names
2504 * which failed to tether.
2505 *
markchien75721e42020-01-21 13:11:06 +08002506 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002507 * {@hide}
2508 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002509 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002510 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002511 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002512 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002513 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002514 }
2515
2516 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002517 * Get the set of tethered dhcp ranges.
2518 *
markchien9e046242020-02-06 19:23:26 +08002519 * @deprecated This method is not supported.
2520 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002521 * {@hide}
2522 */
paulhuec0a9632019-08-12 16:25:11 +08002523 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien75721e42020-01-21 13:11:06 +08002524 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002525 public String[] getTetheredDhcpRanges() {
markchien9e046242020-02-06 19:23:26 +08002526 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002527 }
2528
2529 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002530 * Attempt to tether the named interface. This will setup a dhcp server
2531 * on the interface, forward and NAT IP packets and forward DNS requests
2532 * to the best active upstream network interface. Note that if no upstream
2533 * IP network interface is available, dhcp will still run and traffic will be
2534 * allowed between the tethered devices and this device, though upstream net
2535 * access will of course fail until an upstream network interface becomes
2536 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002537 *
2538 * <p>This method requires the caller to hold either the
2539 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2540 * or the ability to modify system settings as determined by
2541 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002542 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002543 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2544 * and WifiStateMachine which need direct access. All other clients should use
2545 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2546 * logic.</p>
2547 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002548 * @param iface the interface name to tether.
2549 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002550 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002551 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002552 * {@hide}
2553 */
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002554 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien10ddd022020-01-20 19:31:56 +08002555 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002556 public int tether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002557 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002558 }
2559
2560 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002561 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002562 *
2563 * <p>This method requires the caller to hold either the
2564 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2565 * or the ability to modify system settings as determined by
2566 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002567 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002568 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2569 * and WifiStateMachine which need direct access. All other clients should use
2570 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2571 * logic.</p>
2572 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002573 * @param iface the interface name to untether.
2574 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2575 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002576 * {@hide}
2577 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002578 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002579 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002580 public int untether(String iface) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002581 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002582 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002583
2584 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002585 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002586 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002587 * due to device configuration.
2588 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002589 * <p>If this app does not have permission to use this API, it will always
2590 * return false rather than throw an exception.</p>
2591 *
2592 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2593 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2594 *
2595 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2596 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2597 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002598 * @return a boolean - {@code true} indicating Tethering is supported.
2599 *
markchien75721e42020-01-21 13:11:06 +08002600 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002601 * {@hide}
2602 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002603 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002604 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2605 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002606 public boolean isTetheringSupported() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002607 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002608 }
2609
2610 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002611 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien10ddd022020-01-20 19:31:56 +08002612 *
2613 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002614 * @hide
2615 */
2616 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002617 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002618 public static abstract class OnStartTetheringCallback {
2619 /**
2620 * Called when tethering has been successfully started.
2621 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002622 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002623
2624 /**
2625 * Called when starting tethering failed.
2626 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002627 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002628 }
2629
2630 /**
2631 * Convenient overload for
2632 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2633 * handler to run on the current thread's {@link Looper}.
markchien10ddd022020-01-20 19:31:56 +08002634 *
2635 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002636 * @hide
2637 */
2638 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002639 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002640 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002641 public void startTethering(int type, boolean showProvisioningUi,
2642 final OnStartTetheringCallback callback) {
2643 startTethering(type, showProvisioningUi, callback, null);
2644 }
2645
2646 /**
2647 * Runs tether provisioning for the given type if needed and then starts tethering if
2648 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2649 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2650 * schedules tether provisioning re-checks if appropriate.
2651 *
2652 * @param type The type of tethering to start. Must be one of
2653 * {@link ConnectivityManager.TETHERING_WIFI},
2654 * {@link ConnectivityManager.TETHERING_USB}, or
2655 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2656 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2657 * is one. This should be true the first time this function is called and also any time
2658 * the user can see this UI. It gives users information from their carrier about the
2659 * check failing and how they can sign up for tethering if possible.
2660 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2661 * of the result of trying to tether.
2662 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien10ddd022020-01-20 19:31:56 +08002663 *
2664 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002665 * @hide
2666 */
2667 @SystemApi
markchien10ddd022020-01-20 19:31:56 +08002668 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002669 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002670 public void startTethering(int type, boolean showProvisioningUi,
2671 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002672 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002673
markchien10ddd022020-01-20 19:31:56 +08002674 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002675 @Override
markchien10ddd022020-01-20 19:31:56 +08002676 public void execute(Runnable command) {
2677 if (handler == null) {
2678 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002679 } else {
markchien10ddd022020-01-20 19:31:56 +08002680 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002681 }
2682 }
2683 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002684
markchien10ddd022020-01-20 19:31:56 +08002685 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2686 @Override
2687 public void onTetheringStarted() {
2688 callback.onTetheringStarted();
2689 }
2690
2691 @Override
markchien68b67842020-03-19 13:37:43 +08002692 public void onTetheringFailed(final int error) {
markchien10ddd022020-01-20 19:31:56 +08002693 callback.onTetheringFailed();
2694 }
2695 };
2696
2697 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien68b67842020-03-19 13:37:43 +08002698 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien10ddd022020-01-20 19:31:56 +08002699
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002700 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002701 }
2702
2703 /**
2704 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2705 * applicable.
2706 *
2707 * @param type The type of tethering to stop. Must be one of
2708 * {@link ConnectivityManager.TETHERING_WIFI},
2709 * {@link ConnectivityManager.TETHERING_USB}, or
2710 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien75721e42020-01-21 13:11:06 +08002711 *
2712 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002713 * @hide
2714 */
2715 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002716 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002717 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002718 public void stopTethering(int type) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002719 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002720 }
2721
2722 /**
markchiena005c992019-02-27 14:56:11 +08002723 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2724 * upstream status.
2725 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002726 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien75721e42020-01-21 13:11:06 +08002727 * @hide
markchiena005c992019-02-27 14:56:11 +08002728 */
2729 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002730 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002731 public abstract static class OnTetheringEventCallback {
2732
2733 /**
2734 * Called when tethering upstream changed. This can be called multiple times and can be
2735 * called any time.
2736 *
2737 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2738 * have any upstream.
2739 */
2740 public void onUpstreamChanged(@Nullable Network network) {}
2741 }
2742
markchien75721e42020-01-21 13:11:06 +08002743 @GuardedBy("mTetheringEventCallbacks")
2744 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2745 mTetheringEventCallbacks = new ArrayMap<>();
2746
markchiena005c992019-02-27 14:56:11 +08002747 /**
2748 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002749 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002750 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2751 * with a null argument. The same callback object cannot be registered twice.
2752 *
2753 * @param executor the executor on which callback will be invoked.
2754 * @param callback the callback to be called when tethering has change events.
markchien75721e42020-01-21 13:11:06 +08002755 *
Nathan Haroldf6fc8ab2020-01-23 18:03:46 -08002756 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002757 * @hide
2758 */
2759 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002760 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002761 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2762 public void registerTetheringEventCallback(
2763 @NonNull @CallbackExecutor Executor executor,
2764 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00002765 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchiena005c992019-02-27 14:56:11 +08002766
markchien75721e42020-01-21 13:11:06 +08002767 final TetheringEventCallback tetherCallback =
2768 new TetheringEventCallback() {
2769 @Override
2770 public void onUpstreamChanged(@Nullable Network network) {
2771 callback.onUpstreamChanged(network);
2772 }
2773 };
2774
2775 synchronized (mTetheringEventCallbacks) {
2776 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002777 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002778 }
markchiena005c992019-02-27 14:56:11 +08002779 }
2780
2781 /**
2782 * Remove tethering event callback previously registered with
2783 * {@link #registerTetheringEventCallback}.
2784 *
2785 * @param callback previously registered callback.
markchien75721e42020-01-21 13:11:06 +08002786 *
2787 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002788 * @hide
2789 */
2790 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002791 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002792 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2793 public void unregisterTetheringEventCallback(
2794 @NonNull final OnTetheringEventCallback callback) {
markchien75721e42020-01-21 13:11:06 +08002795 Objects.requireNonNull(callback, "The callback must be non-null");
2796 synchronized (mTetheringEventCallbacks) {
2797 final TetheringEventCallback tetherCallback =
2798 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002799 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien75721e42020-01-21 13:11:06 +08002800 }
markchiena005c992019-02-27 14:56:11 +08002801 }
2802
2803
2804 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002805 * Get the list of regular expressions that define any tetherable
2806 * USB network interfaces. If USB tethering is not supported by the
2807 * device, this list should be empty.
2808 *
2809 * @return an array of 0 or more regular expression Strings defining
2810 * what interfaces are considered tetherable usb interfaces.
2811 *
markchien75721e42020-01-21 13:11:06 +08002812 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002813 * {@hide}
2814 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002815 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002816 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002817 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002818 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002819 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002820 }
2821
2822 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002823 * Get the list of regular expressions that define any tetherable
2824 * Wifi network interfaces. If Wifi tethering is not supported by the
2825 * device, this list should be empty.
2826 *
2827 * @return an array of 0 or more regular expression Strings defining
2828 * what interfaces are considered tetherable wifi interfaces.
2829 *
markchien75721e42020-01-21 13:11:06 +08002830 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002831 * {@hide}
2832 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002833 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002834 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002835 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002836 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002837 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002838 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002839
Danica Chang96567052010-08-11 14:54:43 -07002840 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002841 * Get the list of regular expressions that define any tetherable
2842 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2843 * device, this list should be empty.
2844 *
2845 * @return an array of 0 or more regular expression Strings defining
2846 * what interfaces are considered tetherable bluetooth interfaces.
2847 *
markchien75721e42020-01-21 13:11:06 +08002848 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2849 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002850 * {@hide}
2851 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002852 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002853 @UnsupportedAppUsage
markchien75721e42020-01-21 13:11:06 +08002854 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002855 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002856 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002857 }
2858
Mike Lockwooded4a1742011-07-19 13:04:47 -07002859 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002860 * Attempt to both alter the mode of USB and Tethering of USB. A
2861 * utility method to deal with some of the complexity of USB - will
2862 * attempt to switch to Rndis and subsequently tether the resulting
2863 * interface on {@code true} or turn off tethering and switch off
2864 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002865 *
2866 * <p>This method requires the caller to hold either the
2867 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2868 * or the ability to modify system settings as determined by
2869 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002870 *
2871 * @param enable a boolean - {@code true} to enable tethering
2872 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien10ddd022020-01-20 19:31:56 +08002873 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002874 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002875 * {@hide}
2876 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002877 @UnsupportedAppUsage
markchien10ddd022020-01-20 19:31:56 +08002878 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002879 public int setUsbTethering(boolean enable) {
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00002880 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002881 }
2882
markchien75721e42020-01-21 13:11:06 +08002883 /**
2884 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2885 * {@hide}
2886 */
markchien5bd499c2019-01-16 17:44:13 +08002887 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002888 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002889 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien75721e42020-01-21 13:11:06 +08002890 /**
2891 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2892 * {@hide}
2893 */
2894 @Deprecated
2895 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2896 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2897 /**
2898 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2899 * {@hide}
2900 */
2901 @Deprecated
2902 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2903 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2904 /**
2905 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2906 * {@hide}
2907 */
2908 @Deprecated
2909 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2910 /**
2911 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2912 * {@hide}
2913 */
2914 @Deprecated
2915 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2916 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2917 /**
markchien68b67842020-03-19 13:37:43 +08002918 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002919 * {@hide}
2920 */
2921 @Deprecated
markchien68b67842020-03-19 13:37:43 +08002922 public static final int TETHER_ERROR_MASTER_ERROR =
2923 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien75721e42020-01-21 13:11:06 +08002924 /**
2925 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2926 * {@hide}
2927 */
2928 @Deprecated
2929 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2930 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2931 /**
2932 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2933 * {@hide}
2934 */
2935 @Deprecated
2936 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2937 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2938 /**
markchien68b67842020-03-19 13:37:43 +08002939 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002940 * {@hide}
2941 */
2942 @Deprecated
2943 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002944 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002945 /**
markchien68b67842020-03-19 13:37:43 +08002946 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien75721e42020-01-21 13:11:06 +08002947 * {@hide}
2948 */
2949 @Deprecated
2950 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien68b67842020-03-19 13:37:43 +08002951 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien75721e42020-01-21 13:11:06 +08002952 /**
2953 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2954 * {@hide}
2955 */
2956 @Deprecated
2957 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2958 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2959 /**
markchien68b67842020-03-19 13:37:43 +08002960 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien75721e42020-01-21 13:11:06 +08002961 * {@hide}
2962 */
markchien5bd499c2019-01-16 17:44:13 +08002963 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002964 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002965 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien75721e42020-01-21 13:11:06 +08002966 /**
2967 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2968 * {@hide}
2969 */
2970 @Deprecated
2971 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2972 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2973 /**
2974 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2975 * {@hide}
2976 */
markchien5bd499c2019-01-16 17:44:13 +08002977 @SystemApi
markchien75721e42020-01-21 13:11:06 +08002978 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002979 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002980
2981 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002982 * Get a more detailed error code after a Tethering or Untethering
2983 * request asynchronously failed.
2984 *
2985 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002986 * @return error The error code of the last error tethering or untethering the named
2987 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002988 *
markchien75721e42020-01-21 13:11:06 +08002989 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002990 * {@hide}
2991 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002992 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00002993 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien75721e42020-01-21 13:11:06 +08002994 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002995 public int getLastTetherError(String iface) {
markchien68b67842020-03-19 13:37:43 +08002996 int error = mTetheringManager.getLastTetherError(iface);
2997 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2998 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2999 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3000 // instead.
3001 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3002 }
3003 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003004 }
3005
markchiendd41c822019-03-06 16:25:00 +08003006 /** @hide */
3007 @Retention(RetentionPolicy.SOURCE)
3008 @IntDef(value = {
3009 TETHER_ERROR_NO_ERROR,
3010 TETHER_ERROR_PROVISION_FAILED,
3011 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3012 })
3013 public @interface EntitlementResultCode {
3014 }
3015
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003016 /**
markchiendd41c822019-03-06 16:25:00 +08003017 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08003018 * entitlement succeeded.
markchien75721e42020-01-21 13:11:06 +08003019 *
3020 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08003021 * @hide
3022 */
3023 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003024 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08003025 public interface OnTetheringEntitlementResultListener {
3026 /**
3027 * Called to notify entitlement result.
3028 *
3029 * @param resultCode an int value of entitlement result. It may be one of
3030 * {@link #TETHER_ERROR_NO_ERROR},
3031 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3032 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3033 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07003034 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08003035 }
3036
3037 /**
markchien5bd499c2019-01-16 17:44:13 +08003038 * Get the last value of the entitlement check on this downstream. If the cached value is
3039 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3040 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3041 * guaranteed that the UI-based entitlement check will complete in any specific time period
3042 * and may in fact never complete. Any successful entitlement check the platform performs for
3043 * any reason will update the cached value.
3044 *
3045 * @param type the downstream type of tethering. Must be one of
3046 * {@link #TETHERING_WIFI},
3047 * {@link #TETHERING_USB}, or
3048 * {@link #TETHERING_BLUETOOTH}.
3049 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08003050 * @param executor the executor on which callback will be invoked.
3051 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3052 * notify the caller of the result of entitlement check. The listener may be called zero
3053 * or one time.
markchien75721e42020-01-21 13:11:06 +08003054 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08003055 * {@hide}
3056 */
3057 @SystemApi
markchien75721e42020-01-21 13:11:06 +08003058 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08003059 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08003060 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3061 @NonNull @CallbackExecutor Executor executor,
3062 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003063 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchiendd41c822019-03-06 16:25:00 +08003064 ResultReceiver wrappedListener = new ResultReceiver(null) {
3065 @Override
3066 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslin9cc04192021-03-04 09:38:21 +08003067 final long token = Binder.clearCallingIdentity();
3068 try {
3069 executor.execute(() -> {
3070 listener.onTetheringEntitlementResult(resultCode);
3071 });
3072 } finally {
3073 Binder.restoreCallingIdentity(token);
3074 }
markchiendd41c822019-03-06 16:25:00 +08003075 }
3076 };
3077
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00003078 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienb0bb7862019-12-16 20:15:20 +08003079 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08003080 }
3081
3082 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003083 * Report network connectivity status. This is currently used only
3084 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003085 * <p>This method requires the caller to hold the permission
3086 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003087 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003088 * @param networkType The type of network you want to report on
3089 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09003090 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003091 * {@hide}
3092 */
3093 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003094 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003095 try {
3096 mService.reportInetCondition(networkType, percentage);
3097 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003098 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003099 }
3100 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003101
3102 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003103 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07003104 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003105 * the framework to re-evaluate network connectivity and/or switch to another
3106 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003107 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003108 * @param network The {@link Network} the application was attempting to use
3109 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04003110 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3111 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003112 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003113 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09003114 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003115 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003116 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04003117 // One of these will be ignored because it matches system's current state.
3118 // The other will trigger the necessary reevaluation.
3119 mService.reportNetworkConnectivity(network, true);
3120 mService.reportNetworkConnectivity(network, false);
3121 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003122 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003123 }
3124 }
3125
3126 /**
3127 * Report to the framework whether a network has working connectivity.
3128 * This provides a hint to the system that a particular network is providing
3129 * working connectivity or not. In response the framework may re-evaluate
3130 * the network's connectivity and might take further action thereafter.
3131 *
3132 * @param network The {@link Network} the application was attempting to use
3133 * or {@code null} to indicate the current default network.
3134 * @param hasConnectivity {@code true} if the application was able to successfully access the
3135 * Internet using {@code network} or {@code false} if not.
3136 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003137 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003138 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003139 try {
3140 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003141 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003142 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003143 }
3144 }
3145
3146 /**
Chalard Jeanaac3b872021-03-17 17:03:34 +09003147 * Set a network-independent global HTTP proxy.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003148 *
Chalard Jeanaac3b872021-03-17 17:03:34 +09003149 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3150 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3151 * accessing any network, regardless of what the settings for that network are.
3152 *
3153 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3154 * proxy is likely to break networking on multiple networks. This method is only meant
3155 * for device policy clients looking to do general internal filtering or similar use cases.
3156 *
3157 * {@see #getGlobalProxy}
3158 * {@see LinkProperties#getHttpProxy}
3159 *
3160 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3161 * method with a {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003162 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003163 */
Chalard Jeanaac3b872021-03-17 17:03:34 +09003164 // Used by Device Policy Manager to set the global proxy.
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003165 @SystemApi(client = MODULE_LIBRARIES)
paulhuec0a9632019-08-12 16:25:11 +08003166 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeanaac3b872021-03-17 17:03:34 +09003167 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003168 try {
3169 mService.setGlobalProxy(p);
3170 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003171 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003172 }
3173 }
3174
3175 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003176 * Retrieve any network-independent global HTTP proxy.
3177 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003178 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003179 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003180 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003181 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08003182 @SystemApi(client = MODULE_LIBRARIES)
3183 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04003184 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003185 try {
3186 return mService.getGlobalProxy();
3187 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003188 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003189 }
3190 }
3191
3192 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003193 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3194 * network-specific HTTP proxy. If {@code network} is null, the
3195 * network-specific proxy returned is the proxy of the default active
3196 * network.
3197 *
3198 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3199 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3200 * or when {@code network} is {@code null},
3201 * the {@code ProxyInfo} for the default active network. Returns
3202 * {@code null} when no proxy applies or the caller doesn't have
3203 * permission to use {@code network}.
3204 * @hide
3205 */
3206 public ProxyInfo getProxyForNetwork(Network network) {
3207 try {
3208 return mService.getProxyForNetwork(network);
3209 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003210 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003211 }
3212 }
3213
3214 /**
Paul Jensen12131352014-12-10 15:12:18 -05003215 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3216 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003217 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003218 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003219 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003220 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003221 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003222 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003223 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003224 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003225 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003226 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003227
3228 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003229 * Returns true if the hardware supports the given network type
3230 * else it returns false. This doesn't indicate we have coverage
3231 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003232 * hardware supports it. For example a GSM phone without a SIM
3233 * should still return {@code true} for mobile data, but a wifi only
3234 * tablet would return {@code false}.
3235 *
3236 * @param networkType The network type we'd like to check
3237 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003238 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003239 * @hide
3240 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003241 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003242 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003243 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003244 public boolean isNetworkSupported(int networkType) {
3245 try {
3246 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003247 } catch (RemoteException e) {
3248 throw e.rethrowFromSystemServer();
3249 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003250 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003251
3252 /**
3253 * Returns if the currently active data network is metered. A network is
3254 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003255 * that connection due to monetary costs, data limitations or
3256 * battery/performance issues. You should check this before doing large
3257 * data transfers, and warn the user or delay the operation until another
3258 * network is available.
3259 *
3260 * @return {@code true} if large transfers should be avoided, otherwise
3261 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003262 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003263 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003264 public boolean isActiveNetworkMetered() {
3265 try {
3266 return mService.isActiveNetworkMetered();
3267 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003268 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003269 }
3270 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003271
Robert Greenwalt26744a52013-02-15 10:56:35 -08003272 /**
Sarah Chincab74db2020-11-25 12:15:14 -08003273 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003274 *
Sarah Chincab74db2020-11-25 12:15:14 -08003275 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003276 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003277 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003278 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003279 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003280 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003281 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003282 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003283 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003284 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003285 }
3286 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003287
3288 /**
3289 * Set the value for enabling/disabling airplane mode
3290 *
3291 * @param enable whether to enable airplane mode or not
3292 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003293 * @hide
3294 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003295 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003296 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003297 android.Manifest.permission.NETWORK_SETTINGS,
3298 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3299 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003300 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003301 public void setAirplaneMode(boolean enable) {
3302 try {
3303 mService.setAirplaneMode(enable);
3304 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003305 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003306 }
3307 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003308
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003309 /**
3310 * Registers the specified {@link NetworkProvider}.
3311 * Each listener must only be registered once. The listener can be unregistered with
3312 * {@link #unregisterNetworkProvider}.
3313 *
3314 * @param provider the provider to register
3315 * @return the ID of the provider. This ID must be used by the provider when registering
3316 * {@link android.net.NetworkAgent}s.
3317 * @hide
3318 */
3319 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003320 @RequiresPermission(anyOf = {
3321 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3322 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003323 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3324 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003325 throw new IllegalStateException("NetworkProviders can only be registered once");
3326 }
3327
3328 try {
3329 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3330 provider.getName());
3331 provider.setProviderId(providerId);
3332 } catch (RemoteException e) {
3333 throw e.rethrowFromSystemServer();
3334 }
3335 return provider.getProviderId();
3336 }
3337
3338 /**
3339 * Unregisters the specified NetworkProvider.
3340 *
3341 * @param provider the provider to unregister
3342 * @hide
3343 */
3344 @SystemApi
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003345 @RequiresPermission(anyOf = {
3346 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3347 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003348 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3349 try {
3350 mService.unregisterNetworkProvider(provider.getMessenger());
3351 } catch (RemoteException e) {
3352 throw e.rethrowFromSystemServer();
3353 }
3354 provider.setProviderId(NetworkProvider.ID_NONE);
3355 }
3356
Chalard Jean1ef1d902021-01-05 08:40:09 +09003357 /**
3358 * Register or update a network offer with ConnectivityService.
3359 *
3360 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jeand7268cd2021-03-24 17:43:10 +09003361 * them to networking requests made by apps or the system. A callback identifies an offer
3362 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3363 * score and the capabilities of the network it might be able to bring up ; these act as
3364 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jean1ef1d902021-01-05 08:40:09 +09003365 * provider.
3366 *
3367 * The provider is under no obligation to be able to bring up the network it offers at any
3368 * given time. Instead, this mechanism is meant to limit requests received by providers
3369 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3370 * the quality of the network satisfying a given request to their own offer.
3371 *
3372 * An offer can be updated by calling this again with the same callback object. This is
3373 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3374 * provider with the changes caused by the changes in the offer.
3375 *
3376 * @param provider The provider making this offer.
3377 * @param score The prospective score of the network.
3378 * @param caps The prospective capabilities of the network.
3379 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003380 * @hide exposed via the NetworkProvider class.
Chalard Jean1ef1d902021-01-05 08:40:09 +09003381 */
3382 @RequiresPermission(anyOf = {
3383 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3384 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanb004da52021-03-22 22:44:02 +09003385 public void offerNetwork(@NonNull final int providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09003386 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3387 @NonNull final INetworkOfferCallback callback) {
3388 try {
Chalard Jeanb004da52021-03-22 22:44:02 +09003389 mService.offerNetwork(providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09003390 Objects.requireNonNull(score, "null score"),
3391 Objects.requireNonNull(caps, "null caps"),
3392 Objects.requireNonNull(callback, "null callback"));
3393 } catch (RemoteException e) {
3394 throw e.rethrowFromSystemServer();
3395 }
3396 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003397
Chalard Jean1ef1d902021-01-05 08:40:09 +09003398 /**
3399 * Withdraw a network offer made with {@link #offerNetwork}.
3400 *
3401 * @param callback The callback passed at registration time. This must be the same object
3402 * that was passed to {@link #offerNetwork}
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003403 * @hide exposed via the NetworkProvider class.
Chalard Jean1ef1d902021-01-05 08:40:09 +09003404 */
3405 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3406 try {
3407 mService.unofferNetwork(Objects.requireNonNull(callback));
3408 } catch (RemoteException e) {
3409 throw e.rethrowFromSystemServer();
3410 }
3411 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003412 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003413 @RequiresPermission(anyOf = {
3414 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3415 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003416 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3417 try {
3418 mService.declareNetworkRequestUnfulfillable(request);
3419 } catch (RemoteException e) {
3420 throw e.rethrowFromSystemServer();
3421 }
3422 }
3423
Paul Jensenc2569432015-02-13 14:18:39 -05003424 /**
3425 * @hide
3426 * Register a NetworkAgent with ConnectivityService.
Chalard Jean1aea87a2019-12-13 19:47:12 +09003427 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003428 */
Automerger Merge Workeref12b642020-03-04 18:04:01 +00003429 @RequiresPermission(anyOf = {
3430 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3431 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003432 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeandd753522020-12-21 18:36:52 +09003433 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3434 int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003435 try {
Remi NGUYEN VAN37ebfa82020-12-23 12:45:08 +09003436 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003437 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003438 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003439 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003440 }
3441
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003442 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003443 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3444 * changes. Should be extended by applications wanting notifications.
3445 *
3446 * A {@code NetworkCallback} is registered by calling
3447 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3448 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003449 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003450 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3451 * A {@code NetworkCallback} should be registered at most once at any time.
3452 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003453 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003454 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003455 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003456 * No flags associated with this callback.
3457 * @hide
3458 */
3459 public static final int FLAG_NONE = 0;
3460 /**
3461 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3462 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3463 * <p>
3464 * These include:
3465 * <li> Some transport info instances (retrieved via
3466 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3467 * contain location sensitive information.
3468 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3469 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3470 * </p>
3471 * <p>
3472 * Note:
3473 * <li> Retrieving this location sensitive information (subject to app's location
3474 * permissions) will be noted by system. </li>
3475 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3476 * not include location sensitive info.
3477 * </p>
3478 */
Roshan Piusf75ffaa2021-03-11 21:16:44 -08003479 // Note: Some existing fields which are location sensitive may still be included without
3480 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Pius7992afd2020-12-22 15:10:42 -08003481 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3482
3483 /** @hide */
3484 @Retention(RetentionPolicy.SOURCE)
3485 @IntDef(flag = true, prefix = "FLAG_", value = {
3486 FLAG_NONE,
3487 FLAG_INCLUDE_LOCATION_INFO
3488 })
3489 public @interface Flag { }
3490
3491 /**
3492 * All the valid flags for error checking.
3493 */
3494 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3495
3496 public NetworkCallback() {
3497 this(FLAG_NONE);
3498 }
3499
3500 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003501 if ((flags & VALID_FLAGS) != flags) {
3502 throw new IllegalArgumentException("Invalid flags");
3503 }
Roshan Pius7992afd2020-12-22 15:10:42 -08003504 mFlags = flags;
3505 }
3506
3507 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003508 * Called when the framework connects to a new network to evaluate whether it satisfies this
3509 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3510 * callback. There is no guarantee that this new network will satisfy any requests, or that
3511 * the network will stay connected for longer than the time necessary to evaluate it.
3512 * <p>
3513 * Most applications <b>should not</b> act on this callback, and should instead use
3514 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3515 * the framework in properly evaluating the network &mdash; for example, an application that
3516 * can automatically log in to a captive portal without user intervention.
3517 *
3518 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003519 *
3520 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003521 */
paulhua9a6e2a2019-03-22 16:35:06 +08003522 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003523
3524 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003525 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003526 * This callback may be called more than once if the {@link Network} that is
3527 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003528 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003529 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003530 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3531 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003532 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003533 * @hide
3534 */
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003535 public final void onAvailable(@NonNull Network network,
paulhua9a6e2a2019-03-22 16:35:06 +08003536 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003537 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003538 // Internally only this method is called when a new network is available, and
3539 // it calls the callback in the same way and order that older versions used
3540 // to call so as not to change the behavior.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003541 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3542 onBlockedStatusChanged(network, blocked);
3543 }
3544
3545 /**
3546 * Legacy variant of onAvailable that takes a boolean blocked reason.
3547 *
3548 * This method has never been public API, but it's not final, so there may be apps that
3549 * implemented it and rely on it being called. Do our best not to break them.
3550 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3551 * this method is called. There does not seem to be a way to avoid this.
3552 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3553 *
3554 * @hide
3555 */
3556 public void onAvailable(@NonNull Network network,
3557 @NonNull NetworkCapabilities networkCapabilities,
3558 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003559 onAvailable(network);
3560 if (!networkCapabilities.hasCapability(
3561 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3562 onNetworkSuspended(network);
3563 }
3564 onCapabilitiesChanged(network, networkCapabilities);
3565 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003566 // No call to onBlockedStatusChanged here. That is done by the caller.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003567 }
3568
3569 /**
3570 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003571 *
3572 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3573 * be available at the same time, and onAvailable will be called for each of these as they
3574 * appear.
3575 *
3576 * <p>For callbacks registered with {@link #requestNetwork} and
3577 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3578 * is the new best network for this request and is now tracked by this callback ; this
3579 * callback will no longer receive method calls about other networks that may have been
3580 * passed to this method previously. The previously-best network may have disconnected, or
3581 * it may still be around and the newly-best network may simply be better.
3582 *
3583 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3584 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3585 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3586 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3587 *
3588 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3589 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3590 * this callback as this is prone to race conditions (there is no guarantee the objects
3591 * returned by these methods will be current). Instead, wait for a call to
3592 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3593 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3594 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003595 *
3596 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003597 */
paulhua9a6e2a2019-03-22 16:35:06 +08003598 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003599
3600 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003601 * Called when the network is about to be lost, typically because there are no outstanding
3602 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3603 * with the new replacement network for graceful handover. This method is not guaranteed
3604 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3605 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003606 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003607 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3608 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3609 * this callback as this is prone to race conditions ; calling these methods while in a
3610 * callback may return an outdated or even a null object.
3611 *
3612 * @param network The {@link Network} that is about to be lost.
3613 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3614 * connected for graceful handover; note that the network may still
3615 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003616 */
paulhua9a6e2a2019-03-22 16:35:06 +08003617 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003618
3619 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003620 * Called when a network disconnects or otherwise no longer satisfies this request or
3621 * callback.
3622 *
3623 * <p>If the callback was registered with requestNetwork() or
3624 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3625 * returned by onAvailable() when that network is lost and no other network satisfies
3626 * the criteria of the request.
3627 *
3628 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3629 * each network which no longer satisfies the criteria of the callback.
3630 *
3631 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3632 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3633 * this callback as this is prone to race conditions ; calling these methods while in a
3634 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003635 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003636 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003637 */
paulhua9a6e2a2019-03-22 16:35:06 +08003638 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003639
3640 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003641 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003642 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3643 * requested network request cannot be fulfilled (whether or not a timeout was
3644 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003645 * {@link NetworkRequest} will have already been removed and released, as if
3646 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003647 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003648 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003649
3650 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003651 * Called when the network corresponding to this request changes capabilities but still
3652 * satisfies the requested criteria.
3653 *
3654 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3655 * to be called immediately after {@link #onAvailable}.
3656 *
3657 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3658 * ConnectivityManager methods in this callback as this is prone to race conditions :
3659 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003660 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003661 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius7992afd2020-12-22 15:10:42 -08003662 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003663 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003664 */
paulhua9a6e2a2019-03-22 16:35:06 +08003665 public void onCapabilitiesChanged(@NonNull Network network,
3666 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003667
3668 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003669 * Called when the network corresponding to this request changes {@link LinkProperties}.
3670 *
3671 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3672 * to be called immediately after {@link #onAvailable}.
3673 *
3674 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3675 * ConnectivityManager methods in this callback as this is prone to race conditions :
3676 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003677 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003678 * @param network The {@link Network} whose link properties have changed.
3679 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003680 */
paulhua9a6e2a2019-03-22 16:35:06 +08003681 public void onLinkPropertiesChanged(@NonNull Network network,
3682 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003683
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003684 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003685 * Called when the network the framework connected to for this request suspends data
3686 * transmission temporarily.
3687 *
3688 * <p>This generally means that while the TCP connections are still live temporarily
3689 * network data fails to transfer. To give a specific example, this is used on cellular
3690 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3691 * means read operations on sockets on this network will block once the buffers are
3692 * drained, and write operations will block once the buffers are full.
3693 *
3694 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3695 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3696 * this callback as this is prone to race conditions (there is no guarantee the objects
3697 * returned by these methods will be current).
3698 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003699 * @hide
3700 */
paulhua9a6e2a2019-03-22 16:35:06 +08003701 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003702
3703 /**
3704 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003705 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3706 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003707
3708 * <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 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003713 * @hide
3714 */
paulhua9a6e2a2019-03-22 16:35:06 +08003715 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003716
junyulai5ab727b2018-08-07 19:50:45 +08003717 /**
3718 * Called when access to the specified network is blocked or unblocked.
3719 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003720 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3721 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3722 * this callback as this is prone to race conditions : calling these methods while in a
3723 * callback may return an outdated or even a null object.
3724 *
junyulai5ab727b2018-08-07 19:50:45 +08003725 * @param network The {@link Network} whose blocked status has changed.
3726 * @param blocked The blocked status of this {@link Network}.
3727 */
junyulai61143782019-03-04 22:45:36 +08003728 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003729
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003730 /**
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09003731 * Called when access to the specified network is blocked or unblocked, or the reason for
3732 * access being blocked changes.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003733 *
3734 * If a NetworkCallback object implements this method,
3735 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3736 *
3737 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3738 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3739 * this callback as this is prone to race conditions : calling these methods while in a
3740 * callback may return an outdated or even a null object.
3741 *
3742 * @param network The {@link Network} whose blocked status has changed.
3743 * @param blocked The blocked status of this {@link Network}.
3744 * @hide
3745 */
3746 @SystemApi(client = MODULE_LIBRARIES)
3747 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3748 onBlockedStatusChanged(network, blocked != 0);
3749 }
3750
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003751 private NetworkRequest networkRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -08003752 private final int mFlags;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003753 }
3754
Hugo Benichi145e3792017-05-11 13:16:17 +09003755 /**
3756 * Constant error codes used by ConnectivityService to communicate about failures and errors
3757 * across a Binder boundary.
3758 * @hide
3759 */
3760 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003761 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003762 }
3763
3764 /** @hide */
3765 public static class TooManyRequestsException extends RuntimeException {}
3766
3767 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3768 switch (e.errorCode) {
3769 case Errors.TOO_MANY_REQUESTS:
3770 return new TooManyRequestsException();
3771 default:
3772 Log.w(TAG, "Unknown service error code " + e.errorCode);
3773 return new RuntimeException(e);
3774 }
3775 }
3776
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003777 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003778 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003779 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003780 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003781 /** @hide arg1 = TTL */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003782 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003783 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003784 public static final int CALLBACK_LOST = 4;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003785 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003786 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003787 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003788 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003789 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003790 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003791 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003792 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003793 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003794 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003795 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003796 public static final int CALLBACK_RESUMED = 10;
junyulai5ab727b2018-08-07 19:50:45 +08003797 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003798 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003799
Erik Kline66721822015-11-25 12:49:38 +09003800 /** @hide */
3801 public static String getCallbackName(int whichCallback) {
3802 switch (whichCallback) {
3803 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3804 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3805 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3806 case CALLBACK_LOST: return "CALLBACK_LOST";
3807 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3808 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3809 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003810 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3811 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3812 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003813 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003814 default:
3815 return Integer.toString(whichCallback);
3816 }
3817 }
3818
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003819 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003820 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003821 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003822
Hugo Benichife3325f2016-07-06 22:53:17 +09003823 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003824 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003825 }
3826
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003827 CallbackHandler(Handler handler) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003828 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003829 }
3830
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003831 @Override
3832 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003833 if (message.what == EXPIRE_LEGACY_REQUEST) {
3834 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3835 return;
3836 }
3837
3838 final NetworkRequest request = getObject(message, NetworkRequest.class);
3839 final Network network = getObject(message, Network.class);
3840 final NetworkCallback callback;
3841 synchronized (sCallbacks) {
3842 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003843 if (callback == null) {
3844 Log.w(TAG,
3845 "callback not found for " + getCallbackName(message.what) + " message");
3846 return;
3847 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003848 if (message.what == CALLBACK_UNAVAIL) {
3849 sCallbacks.remove(request);
3850 callback.networkRequest = ALREADY_UNREGISTERED;
3851 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003852 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003853 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003854 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003855 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003856
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003857 switch (message.what) {
3858 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003859 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003860 break;
3861 }
3862 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003863 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3864 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003865 callback.onAvailable(network, cap, lp, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003866 break;
3867 }
3868 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003869 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003870 break;
3871 }
3872 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003873 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003874 break;
3875 }
3876 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003877 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003878 break;
3879 }
3880 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003881 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3882 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003883 break;
3884 }
3885 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003886 LinkProperties lp = getObject(message, LinkProperties.class);
3887 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003888 break;
3889 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003890 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003891 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003892 break;
3893 }
3894 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003895 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003896 break;
3897 }
junyulai5ab727b2018-08-07 19:50:45 +08003898 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti60104f52021-03-18 00:54:57 +09003899 callback.onBlockedStatusChanged(network, message.arg1);
junyulai5ab727b2018-08-07 19:50:45 +08003900 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003901 }
3902 }
3903
Hugo Benichife3325f2016-07-06 22:53:17 +09003904 private <T> T getObject(Message msg, Class<T> c) {
3905 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003906 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003907 }
3908
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003909 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003910 synchronized (sCallbacks) {
3911 if (sCallbackHandler == null) {
3912 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003913 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003914 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003915 }
3916 }
3917
Hugo Benichiec180d52017-02-03 14:18:44 +09003918 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3919 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003920
Lorenzo Colittib199b962021-03-12 22:48:07 +09003921 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3922 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3923 CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003924 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003925 checkCallbackNotNull(callback);
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00003926 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3927 throw new IllegalArgumentException("null NetworkCapabilities");
3928 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003929 final NetworkRequest request;
Roshan Piusd26ae412020-01-16 12:17:17 -08003930 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003931 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003932 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003933 if (callback.networkRequest != null
3934 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003935 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3936 // and requests (http://b/20701525).
3937 Log.e(TAG, "NetworkCallback was already registered");
3938 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003939 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003940 Binder binder = new Binder();
Roshan Pius7992afd2020-12-22 15:10:42 -08003941 final int callbackFlags = callback.mFlags;
junyulaid1a78162021-01-11 16:53:38 +08003942 if (reqType == LISTEN) {
Roshan Piusd26ae412020-01-16 12:17:17 -08003943 request = mService.listenForNetwork(
Roshan Pius7992afd2020-12-22 15:10:42 -08003944 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08003945 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003946 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003947 request = mService.requestNetwork(
Lorenzo Colittib199b962021-03-12 22:48:07 +09003948 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3949 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003950 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003951 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003952 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003953 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003954 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003955 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003956 } catch (RemoteException e) {
3957 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003958 } catch (ServiceSpecificException e) {
3959 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003960 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003961 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003962 }
3963
Lorenzo Colittib199b962021-03-12 22:48:07 +09003964 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3965 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3966 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3967 legacyType, handler);
3968 }
3969
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003970 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003971 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003972 *
markchien0fe11402020-03-18 21:16:15 +08003973 * This API is only for use in internal system code that requests networks with legacy type and
3974 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchien769c5752020-01-14 12:54:40 +08003975 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003976 *
markchien769c5752020-01-14 12:54:40 +08003977 * @param request {@link NetworkRequest} describing this request.
markchien769c5752020-01-14 12:54:40 +08003978 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3979 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3980 * be a positive value (i.e. >0).
3981 * @param legacyType to specify the network type(#TYPE_*).
3982 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien0fe11402020-03-18 21:16:15 +08003983 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3984 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003985 *
3986 * @hide
3987 */
markchien769c5752020-01-14 12:54:40 +08003988 @SystemApi
markchien0fe11402020-03-18 21:16:15 +08003989 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003990 public void requestNetwork(@NonNull NetworkRequest request,
markchien0fe11402020-03-18 21:16:15 +08003991 int timeoutMs, int legacyType, @NonNull Handler handler,
3992 @NonNull NetworkCallback networkCallback) {
3993 if (legacyType == TYPE_NONE) {
3994 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3995 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003996 CallbackHandler cbHandler = new CallbackHandler(handler);
3997 NetworkCapabilities nc = request.networkCapabilities;
3998 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003999 }
4000
4001 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004002 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004003 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004004 * <p>This method will attempt to find the best network that matches the passed
4005 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4006 * criteria. The platform will evaluate which network is the best at its own discretion.
4007 * Throughput, latency, cost per byte, policy, user preference and other considerations
4008 * may be factored in the decision of what is considered the best network.
4009 *
4010 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4011 * matching this request, while always attempting to match the request to a better network if
4012 * possible. If a better match is found, the platform will switch this request to the now-best
4013 * network and inform the app of the newly best network by invoking
4014 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4015 * will not try to maintain any other network than the best one currently matching the request:
4016 * a network not matching any network request may be disconnected at any time.
4017 *
4018 * <p>For example, an application could use this method to obtain a connected cellular network
4019 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4020 * radio to consume additional power. Or, an application could inform the system that it wants
4021 * a network supporting sending MMSes and have the system let it know about the currently best
4022 * MMS-supporting network through the provided {@link NetworkCallback}.
4023 *
4024 * <p>The status of the request can be followed by listening to the various callbacks described
4025 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4026 * used to direct traffic to the network (although accessing some networks may be subject to
4027 * holding specific permissions). Callers will learn about the specific characteristics of the
4028 * network through
4029 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4030 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4031 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4032 * matching the request at any given time; therefore when a better network matching the request
4033 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4034 * with the new network after which no further updates are given about the previously-best
4035 * network, unless it becomes the best again at some later time. All callbacks are invoked
4036 * in order on the same thread, which by default is a thread created by the framework running
4037 * in the app.
4038 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4039 * callbacks are invoked.
4040 *
4041 * <p>This{@link NetworkRequest} will live until released via
4042 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4043 * which point the system may let go of the network at any time.
4044 *
4045 * <p>A version of this method which takes a timeout is
4046 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4047 * wait for a limited amount of time for the network to become unavailable.
4048 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004049 * <p>It is presently unsupported to request a network with mutable
4050 * {@link NetworkCapabilities} such as
4051 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4052 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4053 * as these {@code NetworkCapabilities} represent states that a particular
4054 * network may never attain, and whether a network will attain these states
4055 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09004056 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004057 *
4058 * <p>This method requires the caller to hold either the
4059 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4060 * or the ability to modify system settings as determined by
4061 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004062 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004063 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4064 * number of outstanding requests to 100 per app (identified by their UID), shared with
4065 * all variants of this method, of {@link #registerNetworkCallback} as well as
4066 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4067 * Requesting a network with this method will count toward this limit. If this limit is
4068 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4069 * make sure to unregister the callbacks with
4070 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4071 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004072 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004073 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4074 * the callback must not be shared - it uniquely specifies this request.
4075 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004076 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4077 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004078 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004079 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004080 public void requestNetwork(@NonNull NetworkRequest request,
4081 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004082 requestNetwork(request, networkCallback, getDefaultHandler());
4083 }
4084
4085 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004086 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004087 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004088 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4089 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004090 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004091 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004092 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4093 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004094 *
4095 * @param request {@link NetworkRequest} describing this request.
4096 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4097 * the callback must not be shared - it uniquely specifies this request.
4098 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004099 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004100 public void requestNetwork(@NonNull NetworkRequest request,
4101 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004102 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004103 NetworkCapabilities nc = request.networkCapabilities;
4104 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004105 }
4106
4107 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004108 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohen67e58a02017-03-01 12:47:28 -08004109 * by a timeout.
4110 *
4111 * This function behaves identically to the non-timed-out version
4112 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4113 * is not found within the given time (in milliseconds) the
4114 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4115 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4116 * not have to be released if timed-out (it is automatically released). Unregistering a
4117 * request that timed out is not an error.
4118 *
4119 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4120 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4121 * for that purpose. Calling this method will attempt to bring up the requested network.
4122 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004123 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004124 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4125 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08004126 *
4127 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004128 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4129 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004130 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4131 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4132 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08004133 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004134 public void requestNetwork(@NonNull NetworkRequest request,
4135 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004136 checkTimeout(timeoutMs);
markchien0fe11402020-03-18 21:16:15 +08004137 NetworkCapabilities nc = request.networkCapabilities;
4138 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4139 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004140 }
4141
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004142 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004143 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004144 * by a timeout.
4145 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004146 * This method behaves identically to
4147 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4148 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08004149 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09004150 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09004151 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4152 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004153 *
4154 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08004155 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4156 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004157 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004158 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4159 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004160 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004161 public void requestNetwork(@NonNull NetworkRequest request,
4162 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09004163 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004164 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien0fe11402020-03-18 21:16:15 +08004165 NetworkCapabilities nc = request.networkCapabilities;
4166 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004167 }
4168
4169 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004170 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004171 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004172 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08004173 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04004174 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4175 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004176 */
Erik Klinefb087f12014-11-19 12:12:24 +09004177 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004178
4179 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004180 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08004181 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004182 * {@link android.content.Intent#getParcelableExtra(String)}.
4183 */
Erik Klinefb087f12014-11-19 12:12:24 +09004184 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004185
4186
4187 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08004188 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004189 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08004190 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004191 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004192 * the request may outlive the calling application and get called back when a suitable
4193 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004194 * <p>
4195 * The operation is an Intent broadcast that goes to a broadcast receiver that
4196 * you registered with {@link Context#registerReceiver} or through the
4197 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4198 * <p>
4199 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09004200 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4201 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004202 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004203 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004204 * Intent to reserve the network or it will be released shortly after the Intent
4205 * is processed.
4206 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04004207 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004208 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004209 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004210 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08004211 * The request may be released normally by calling
4212 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004213 * <p>It is presently unsupported to request a network with either
4214 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4215 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4216 * as these {@code NetworkCapabilities} represent states that a particular
4217 * network may never attain, and whether a network will attain these states
4218 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09004219 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004220 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004221 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4222 * number of outstanding requests to 100 per app (identified by their UID), shared with
4223 * all variants of this method, of {@link #registerNetworkCallback} as well as
4224 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4225 * Requesting a network with this method will count toward this limit. If this limit is
4226 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4227 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4228 * or {@link #releaseNetworkRequest(PendingIntent)}.
4229 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004230 * <p>This method requires the caller to hold either the
4231 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4232 * or the ability to modify system settings as determined by
4233 * {@link android.provider.Settings.System#canWrite}.</p>
4234 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004235 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004236 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004237 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08004238 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004239 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4240 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004241 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004242 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004243 public void requestNetwork(@NonNull NetworkRequest request,
4244 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004245 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004246 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004247 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004248 mService.pendingRequestForNetwork(
Philip P. Moltmannddbcf5b2020-03-24 15:57:49 -07004249 request.networkCapabilities, operation, mContext.getOpPackageName(),
4250 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004251 } catch (RemoteException e) {
4252 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004253 } catch (ServiceSpecificException e) {
4254 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004255 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004256 }
4257
4258 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004259 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4260 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004261 * This method has the same behavior as
4262 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004263 * releasing network resources and disconnecting.
4264 *
4265 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4266 * PendingIntent passed to
4267 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4268 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4269 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004270 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004271 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004272 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004273 try {
4274 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004275 } catch (RemoteException e) {
4276 throw e.rethrowFromSystemServer();
4277 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004278 }
4279
Hugo Benichiff4bf602017-05-09 15:19:01 +09004280 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004281 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004282 }
4283
4284 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004285 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004286 }
4287
4288 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004289 if (timeoutMs <= 0) {
4290 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4291 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004292 }
4293
4294 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004295 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004296 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004297 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4298 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004299 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004300 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4301 * number of outstanding requests to 100 per app (identified by their UID), shared with
4302 * all variants of this method, of {@link #requestNetwork} as well as
4303 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4304 * Requesting a network with this method will count toward this limit. If this limit is
4305 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4306 * make sure to unregister the callbacks with
4307 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4308 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004309 * @param request {@link NetworkRequest} describing this request.
4310 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4311 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004312 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004313 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004314 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004315 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004316 public void registerNetworkCallback(@NonNull NetworkRequest request,
4317 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004318 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4319 }
4320
4321 /**
4322 * Registers to receive notifications about all networks which satisfy the given
4323 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004324 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4325 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004326 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004327 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4328 * number of outstanding requests to 100 per app (identified by their UID), shared with
4329 * all variants of this method, of {@link #requestNetwork} as well as
4330 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4331 * Requesting a network with this method will count toward this limit. If this limit is
4332 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4333 * make sure to unregister the callbacks with
4334 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4335 *
4336 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004337 * @param request {@link NetworkRequest} describing this request.
4338 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4339 * networks change state.
4340 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004341 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004342 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004343 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004344 public void registerNetworkCallback(@NonNull NetworkRequest request,
4345 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004346 CallbackHandler cbHandler = new CallbackHandler(handler);
4347 NetworkCapabilities nc = request.networkCapabilities;
4348 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004349 }
4350
4351 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004352 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4353 * {@link NetworkRequest}.
4354 *
4355 * This function behaves identically to the version that takes a NetworkCallback, but instead
4356 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4357 * the request may outlive the calling application and get called back when a suitable
4358 * network is found.
4359 * <p>
4360 * The operation is an Intent broadcast that goes to a broadcast receiver that
4361 * you registered with {@link Context#registerReceiver} or through the
4362 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4363 * <p>
4364 * The operation Intent is delivered with two extras, a {@link Network} typed
4365 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4366 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4367 * the original requests parameters.
4368 * <p>
4369 * If there is already a request for this Intent registered (with the equality of
4370 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4371 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4372 * <p>
4373 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004374 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004375 *
4376 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4377 * number of outstanding requests to 100 per app (identified by their UID), shared with
4378 * all variants of this method, of {@link #requestNetwork} as well as
4379 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4380 * Requesting a network with this method will count toward this limit. If this limit is
4381 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4382 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4383 * or {@link #releaseNetworkRequest(PendingIntent)}.
4384 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004385 * @param request {@link NetworkRequest} describing this request.
4386 * @param operation Action to perform when the network is available (corresponds
4387 * to the {@link NetworkCallback#onAvailable} call. Typically
4388 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004389 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004390 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004391 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004392 public void registerNetworkCallback(@NonNull NetworkRequest request,
4393 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004394 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004395 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004396 try {
Roshan Piusd26ae412020-01-16 12:17:17 -08004397 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004398 request.networkCapabilities, operation, mContext.getOpPackageName(),
4399 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004400 } catch (RemoteException e) {
4401 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004402 } catch (ServiceSpecificException e) {
4403 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004404 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004405 }
4406
4407 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004408 * Registers to receive notifications about changes in the application's default network. This
4409 * may be a physical network or a virtual network, such as a VPN that applies to the
4410 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004411 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004412 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004413 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4414 * number of outstanding requests to 100 per app (identified by their UID), shared with
4415 * all variants of this method, of {@link #requestNetwork} as well as
4416 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4417 * Requesting a network with this method will count toward this limit. If this limit is
4418 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4419 * make sure to unregister the callbacks with
4420 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4421 *
Erik Klinee0aed632016-03-16 15:31:39 +09004422 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004423 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004424 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004425 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004426 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004427 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004428 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004429 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4430 }
4431
4432 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004433 * Registers to receive notifications about changes in the application's default network. This
4434 * may be a physical network or a virtual network, such as a VPN that applies to the
4435 * application. The callbacks will continue to be called until either the application exits or
4436 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4437 *
4438 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4439 * number of outstanding requests to 100 per app (identified by their UID), shared with
4440 * all variants of this method, of {@link #requestNetwork} as well as
4441 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4442 * Requesting a network with this method will count toward this limit. If this limit is
4443 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4444 * make sure to unregister the callbacks with
4445 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4446 *
4447 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4448 * application's default network changes.
4449 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4450 * @throws RuntimeException if the app already has too many callbacks registered.
4451 */
4452 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4453 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4454 @NonNull Handler handler) {
Lorenzo Colittib199b962021-03-12 22:48:07 +09004455 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4456 }
4457
4458 /**
4459 * Registers to receive notifications about changes in the default network for the specified
4460 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4461 * UID. The callbacks will continue to be called until either the application exits or
4462 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4463 *
4464 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4465 * number of outstanding requests to 100 per app (identified by their UID), shared with
4466 * all variants of this method, of {@link #requestNetwork} as well as
4467 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4468 * Requesting a network with this method will count toward this limit. If this limit is
4469 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4470 * make sure to unregister the callbacks with
4471 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4472 *
4473 * @param uid the UID for which to track default network changes.
4474 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4475 * UID's default network changes.
4476 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4477 * @throws RuntimeException if the app already has too many callbacks registered.
4478 * @hide
4479 */
Lorenzo Colitti3949d6e2021-03-22 18:23:21 +09004480 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittib199b962021-03-12 22:48:07 +09004481 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4482 @RequiresPermission(anyOf = {
4483 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4484 android.Manifest.permission.NETWORK_SETTINGS})
4485 public void registerDefaultNetworkCallbackAsUid(int uid,
4486 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004487 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colittib199b962021-03-12 22:48:07 +09004488 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004489 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4490 }
4491
4492 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004493 * Registers to receive notifications about changes in the system default network. The callbacks
4494 * will continue to be called until either the application exits or
4495 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004496 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004497 * This method should not be used to determine networking state seen by applications, because in
4498 * many cases, most or even all application traffic may not use the default network directly,
4499 * and traffic from different applications may go on different networks by default. As an
4500 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4501 * and not onto the system default network. Applications or system components desiring to do
4502 * determine network state as seen by applications should use other methods such as
4503 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4504 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004505 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4506 * number of outstanding requests to 100 per app (identified by their UID), shared with
4507 * all variants of this method, of {@link #requestNetwork} as well as
4508 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4509 * Requesting a network with this method will count toward this limit. If this limit is
4510 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4511 * make sure to unregister the callbacks with
4512 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4513 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004514 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4515 * system default network changes.
4516 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004517 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004518 *
4519 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004520 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004521 @SystemApi(client = MODULE_LIBRARIES)
4522 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4523 @RequiresPermission(anyOf = {
4524 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4525 android.Manifest.permission.NETWORK_SETTINGS})
4526 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004527 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004528 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004529 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004530 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004531 }
4532
4533 /**
junyulaibd622262021-03-15 11:48:48 +08004534 * Registers to receive notifications about the best matching network which satisfy the given
4535 * {@link NetworkRequest}. The callbacks will continue to be called until
4536 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4537 * called.
4538 *
4539 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4540 * number of outstanding requests to 100 per app (identified by their UID), shared with
4541 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4542 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4543 * Requesting a network with this method will count toward this limit. If this limit is
4544 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4545 * make sure to unregister the callbacks with
4546 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4547 *
4548 *
4549 * @param request {@link NetworkRequest} describing this request.
4550 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4551 * networks change state.
4552 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4553 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai6b0a6a22021-03-05 15:51:17 +08004554 */
junyulai6b0a6a22021-03-05 15:51:17 +08004555 @SuppressLint("ExecutorRegistration")
4556 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4557 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4558 final NetworkCapabilities nc = request.networkCapabilities;
4559 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai8cae3c72021-03-12 20:05:08 +08004560 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai6b0a6a22021-03-05 15:51:17 +08004561 }
4562
4563 /**
fenglu73169332015-04-21 17:12:05 -07004564 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4565 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4566 * network connection for updated bandwidth information. The caller will be notified via
4567 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004568 * method assumes that the caller has previously called
4569 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4570 * changes.
fenglu76564332015-03-20 11:29:56 -07004571 *
fenglu41808e82015-04-27 14:28:04 -07004572 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004573 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004574 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004575 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004576 try {
fenglu73169332015-04-21 17:12:05 -07004577 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004578 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004579 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004580 }
4581 }
4582
4583 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004584 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004585 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4586 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4587 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004588 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4589 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004590 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004591 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4592 * triggering it as soon as this call returns.
4593 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004594 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004595 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004596 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004597 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004598 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004599 final List<NetworkRequest> reqs = new ArrayList<>();
4600 // Find all requests associated to this callback and stop callback triggers immediately.
4601 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4602 synchronized (sCallbacks) {
Remi NGUYEN VANc4dd8c92021-03-15 07:31:54 +00004603 if (networkCallback.networkRequest == null) {
4604 throw new IllegalArgumentException("NetworkCallback was not registered");
4605 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07004606 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4607 Log.d(TAG, "NetworkCallback was already unregistered");
4608 return;
4609 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004610 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4611 if (e.getValue() == networkCallback) {
4612 reqs.add(e.getKey());
4613 }
4614 }
4615 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4616 for (NetworkRequest r : reqs) {
4617 try {
4618 mService.releaseNetworkRequest(r);
4619 } catch (RemoteException e) {
4620 throw e.rethrowFromSystemServer();
4621 }
4622 // Only remove mapping if rpc was successful.
4623 sCallbacks.remove(r);
4624 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004625 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004626 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004627 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004628
4629 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004630 * Unregisters a callback previously registered via
4631 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4632 *
4633 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4634 * PendingIntent passed to
4635 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4636 * Cannot be null.
4637 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004638 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004639 releaseNetworkRequest(operation);
4640 }
4641
4642 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004643 * Informs the system whether it should switch to {@code network} regardless of whether it is
4644 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4645 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4646 * the system default network regardless of any other network that's currently connected. If
4647 * {@code always} is true, then the choice is remembered, so that the next time the user
4648 * connects to this network, the system will switch to it.
4649 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004650 * @param network The network to accept.
4651 * @param accept Whether to accept the network even if unvalidated.
4652 * @param always Whether to remember this choice in the future.
4653 *
4654 * @hide
4655 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004656 @SystemApi(client = MODULE_LIBRARIES)
4657 @RequiresPermission(anyOf = {
4658 android.Manifest.permission.NETWORK_SETTINGS,
4659 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4660 android.Manifest.permission.NETWORK_STACK,
4661 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4662 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004663 try {
4664 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004665 } catch (RemoteException e) {
4666 throw e.rethrowFromSystemServer();
4667 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004668 }
4669
4670 /**
lucaslin25a50472019-03-12 13:08:03 +08004671 * Informs the system whether it should consider the network as validated even if it only has
4672 * partial connectivity. If {@code accept} is true, then the network will be considered as
4673 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4674 * is remembered, so that the next time the user connects to this network, the system will
4675 * switch to it.
4676 *
4677 * @param network The network to accept.
4678 * @param accept Whether to consider the network as validated even if it has partial
4679 * connectivity.
4680 * @param always Whether to remember this choice in the future.
4681 *
4682 * @hide
4683 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004684 @SystemApi(client = MODULE_LIBRARIES)
4685 @RequiresPermission(anyOf = {
4686 android.Manifest.permission.NETWORK_SETTINGS,
4687 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4688 android.Manifest.permission.NETWORK_STACK,
4689 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4690 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4691 boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004692 try {
4693 mService.setAcceptPartialConnectivity(network, accept, always);
4694 } catch (RemoteException e) {
4695 throw e.rethrowFromSystemServer();
4696 }
4697 }
4698
4699 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004700 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4701 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4702 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4703 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4704 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004705 * @param network The network to accept.
4706 *
4707 * @hide
4708 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004709 @SystemApi(client = MODULE_LIBRARIES)
4710 @RequiresPermission(anyOf = {
4711 android.Manifest.permission.NETWORK_SETTINGS,
4712 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4713 android.Manifest.permission.NETWORK_STACK,
4714 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4715 public void setAvoidUnvalidated(@NonNull Network network) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004716 try {
4717 mService.setAvoidUnvalidated(network);
4718 } catch (RemoteException e) {
4719 throw e.rethrowFromSystemServer();
4720 }
4721 }
4722
4723 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004724 * Requests that the system open the captive portal app on the specified network.
4725 *
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004726 * <p>This is to be used on networks where a captive portal was detected, as per
4727 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4728 *
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004729 * @param network The network to log into.
4730 *
4731 * @hide
4732 */
Remi NGUYEN VANbffe51d2021-03-16 18:06:06 +09004733 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4734 @RequiresPermission(anyOf = {
4735 android.Manifest.permission.NETWORK_SETTINGS,
4736 android.Manifest.permission.NETWORK_STACK,
4737 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4738 })
4739 public void startCaptivePortalApp(@NonNull Network network) {
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004740 try {
4741 mService.startCaptivePortalApp(network);
4742 } catch (RemoteException e) {
4743 throw e.rethrowFromSystemServer();
4744 }
4745 }
4746
4747 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004748 * Requests that the system open the captive portal app with the specified extras.
4749 *
4750 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4751 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004752 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004753 * @param appExtras Extras to include in the app start intent.
4754 * @hide
4755 */
4756 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004757 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004758 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004759 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004760 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004761 } catch (RemoteException e) {
4762 throw e.rethrowFromSystemServer();
4763 }
4764 }
4765
4766 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004767 * Determine whether the device is configured to avoid bad wifi.
4768 * @hide
4769 */
4770 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004771 @RequiresPermission(anyOf = {
4772 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4773 android.Manifest.permission.NETWORK_STACK})
4774 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004775 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004776 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004777 } catch (RemoteException e) {
4778 throw e.rethrowFromSystemServer();
4779 }
4780 }
4781
4782 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004783 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4784 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004785 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4786 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004787 *
4788 * An example of such an operation might be a time-sensitive foreground activity, such as a
4789 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4790 */
4791 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4792
4793 /**
4794 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4795 * a backup channel for traffic that is primarily going over another network.
4796 *
4797 * An example might be maintaining backup connections to peers or servers for the purpose of
4798 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4799 * on backup paths should be negligible compared to the traffic on the main path.
4800 */
4801 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4802
4803 /**
4804 * It is acceptable to use metered data to improve network latency and performance.
4805 */
4806 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4807
4808 /**
4809 * Return value to use for unmetered networks. On such networks we currently set all the flags
4810 * to true.
4811 * @hide
4812 */
4813 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4814 MULTIPATH_PREFERENCE_HANDOVER |
4815 MULTIPATH_PREFERENCE_RELIABILITY |
4816 MULTIPATH_PREFERENCE_PERFORMANCE;
4817
4818 /** @hide */
4819 @Retention(RetentionPolicy.SOURCE)
4820 @IntDef(flag = true, value = {
4821 MULTIPATH_PREFERENCE_HANDOVER,
4822 MULTIPATH_PREFERENCE_RELIABILITY,
4823 MULTIPATH_PREFERENCE_PERFORMANCE,
4824 })
4825 public @interface MultipathPreference {
4826 }
4827
4828 /**
4829 * Provides a hint to the calling application on whether it is desirable to use the
4830 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4831 * for multipath data transfer on this network when it is not the system default network.
4832 * Applications desiring to use multipath network protocols should call this method before
4833 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004834 *
4835 * @param network The network on which the application desires to use multipath data.
4836 * If {@code null}, this method will return the a preference that will generally
4837 * apply to metered networks.
4838 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4839 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004840 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004841 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004842 try {
4843 return mService.getMultipathPreference(network);
4844 } catch (RemoteException e) {
4845 throw e.rethrowFromSystemServer();
4846 }
4847 }
4848
4849 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004850 * Resets all connectivity manager settings back to factory defaults.
4851 * @hide
4852 */
Chiachang Wang0cefc1c2021-03-18 09:44:34 +08004853 @SystemApi(client = MODULE_LIBRARIES)
4854 @RequiresPermission(anyOf = {
4855 android.Manifest.permission.NETWORK_SETTINGS,
4856 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Stuart Scottd3bb5082015-03-30 13:17:11 -07004857 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004858 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004859 mService.factoryReset();
Automerger Merge Worker9b0c0c62020-03-06 00:38:43 +00004860 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004861 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004862 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004863 }
4864 }
4865
4866 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004867 * Binds the current process to {@code network}. All Sockets created in the future
4868 * (and not explicitly bound via a bound SocketFactory from
4869 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4870 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4871 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4872 * work and all host name resolutions will fail. This is by design so an application doesn't
4873 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4874 * To clear binding pass {@code null} for {@code network}. Using individually bound
4875 * Sockets created by Network.getSocketFactory().createSocket() and
4876 * performing network-specific host name resolutions via
4877 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004878 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004879 *
4880 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4881 * the current binding.
4882 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4883 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004884 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004885 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004886 // instantiated.
4887 return setProcessDefaultNetwork(network);
4888 }
4889
4890 /**
4891 * Binds the current process to {@code network}. All Sockets created in the future
4892 * (and not explicitly bound via a bound SocketFactory from
4893 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4894 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4895 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4896 * work and all host name resolutions will fail. This is by design so an application doesn't
4897 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4898 * To clear binding pass {@code null} for {@code network}. Using individually bound
4899 * Sockets created by Network.getSocketFactory().createSocket() and
4900 * performing network-specific host name resolutions via
4901 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4902 * {@code setProcessDefaultNetwork}.
4903 *
4904 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4905 * the current binding.
4906 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4907 * @deprecated This function can throw {@link IllegalStateException}. Use
4908 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4909 * is a direct replacement.
4910 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004911 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004912 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004913 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004914 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4915
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004916 if (netId != NETID_UNSET) {
4917 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004918 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004919
4920 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4921 return false;
4922 }
4923
4924 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004925 // Set HTTP proxy system properties to match network.
4926 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004927 try {
Remi NGUYEN VANa1860ff2021-02-03 10:18:20 +09004928 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004929 } catch (SecurityException e) {
4930 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4931 Log.e(TAG, "Can't set proxy properties", e);
4932 }
Paul Jensen99c36662014-08-27 12:38:45 -04004933 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN33e3abb2021-03-18 23:27:19 +09004934 InetAddressCompat.clearDnsCache();
Paul Jensen99c36662014-08-27 12:38:45 -04004935 // Must flush socket pool as idle sockets will be bound to previous network and may
4936 // cause subsequent fetches to be performed on old network.
4937 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004938 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004939
4940 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004941 }
4942
4943 /**
4944 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004945 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004946 *
4947 * @return {@code Network} to which this process is bound, or {@code null}.
4948 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004949 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004950 public Network getBoundNetworkForProcess() {
4951 // Forcing callers to call thru non-static function ensures ConnectivityManager
4952 // instantiated.
4953 return getProcessDefaultNetwork();
4954 }
4955
4956 /**
4957 * Returns the {@link Network} currently bound to this process via
4958 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4959 *
4960 * @return {@code Network} to which this process is bound, or {@code null}.
4961 * @deprecated Using this function can lead to other functions throwing
4962 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4963 * {@code getBoundNetworkForProcess} is a direct replacement.
4964 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004965 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004966 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004967 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004968 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004969 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004970 return new Network(netId);
4971 }
4972
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004973 private void unsupportedStartingFrom(int version) {
4974 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004975 // The getApplicationInfo() call we make below is not supported in system context. Let
4976 // the call through here, and rely on the fact that ConnectivityService will refuse to
4977 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004978 return;
4979 }
4980
4981 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4982 throw new UnsupportedOperationException(
4983 "This method is not supported in target SDK version " + version + " and above");
4984 }
4985 }
4986
4987 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4988 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004989 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004990 // remove these exemptions. Note that this check is not secure, and apps can still access these
4991 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4992 // so is unsupported and may break in the future. http://b/22728205
4993 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07004994 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004995 }
4996
Paul Jensene98c6e02014-05-29 10:12:39 -04004997 /**
4998 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04004999 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04005000 *
5001 * @param network The {@link Network} to bind host resolutions from the current process to, or
5002 * {@code null} to clear the current binding.
5003 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5004 * @hide
5005 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5006 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07005007 @Deprecated
Mathew Inwoodd078d3d2020-10-27 11:47:29 +00005008 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04005009 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04005010 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09005011 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04005012 }
Felipe Lemed16384b2016-01-22 09:44:57 -08005013
5014 /**
5015 * Device is not restricting metered network activity while application is running on
5016 * background.
5017 */
5018 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5019
5020 /**
5021 * Device is restricting metered network activity while application is running on background,
5022 * but application is allowed to bypass it.
5023 * <p>
5024 * In this state, application should take action to mitigate metered network access.
5025 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5026 */
5027 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5028
5029 /**
5030 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08005031 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08005032 * In this state, application should not try to use the network while running on background,
5033 * because it would be denied.
5034 */
5035 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5036
Felipe Leme6a5b7692016-01-27 14:46:39 -08005037 /**
5038 * A change in the background metered network activity restriction has occurred.
5039 * <p>
5040 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5041 * applies to them.
5042 * <p>
5043 * This is only sent to registered receivers, not manifest receivers.
5044 */
5045 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5046 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5047 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5048
Felipe Leme1b42ef92016-01-25 11:48:04 -08005049 /** @hide */
5050 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08005051 @IntDef(flag = false, value = {
5052 RESTRICT_BACKGROUND_STATUS_DISABLED,
5053 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5054 RESTRICT_BACKGROUND_STATUS_ENABLED,
5055 })
Felipe Lemed16384b2016-01-22 09:44:57 -08005056 public @interface RestrictBackgroundStatus {
5057 }
5058
Felipe Lemed16384b2016-01-22 09:44:57 -08005059 /**
5060 * Determines if the calling application is subject to metered network restrictions while
5061 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07005062 *
5063 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5064 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5065 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08005066 */
5067 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5068 try {
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09005069 return mService.getRestrictBackgroundStatusByCaller();
Felipe Lemed16384b2016-01-22 09:44:57 -08005070 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07005071 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08005072 }
5073 }
Ricky Waid53cf002018-01-23 04:09:45 +00005074
5075 /**
5076 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00005077 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5078 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00005079 *
5080 * @return Hash of network watchlist config file. Null if config does not exist.
5081 */
Chalard Jean42a9c292019-01-07 19:26:34 +09005082 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00005083 public byte[] getNetworkWatchlistConfigHash() {
5084 try {
5085 return mService.getNetworkWatchlistConfigHash();
5086 } catch (RemoteException e) {
5087 Log.e(TAG, "Unable to get watchlist config hash");
5088 throw e.rethrowFromSystemServer();
5089 }
5090 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005091
5092 /**
5093 * Returns the {@code uid} of the owner of a network connection.
5094 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08005095 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5096 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005097 * @param local The local {@link InetSocketAddress} of a connection.
5098 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005099 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08005100 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5101 * android.os.Process#INVALID_UID} if the connection is not found.
5102 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5103 * user.
5104 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005105 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08005106 public int getConnectionOwnerUid(
5107 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07005108 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5109 try {
5110 return mService.getConnectionOwnerUid(connectionInfo);
5111 } catch (RemoteException e) {
5112 throw e.rethrowFromSystemServer();
5113 }
5114 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09005115
5116 private void printStackTrace() {
5117 if (DEBUG) {
5118 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5119 final StringBuffer sb = new StringBuffer();
5120 for (int i = 3; i < callStack.length; i++) {
5121 final String stackTrace = callStack[i].toString();
5122 if (stackTrace == null || stackTrace.contains("android.os")) {
5123 break;
5124 }
5125 sb.append(" [").append(stackTrace).append("]");
5126 }
5127 Log.d(TAG, "StackLog:" + sb.toString());
5128 }
5129 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005130
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09005131 /** @hide */
5132 public TestNetworkManager startOrGetTestNetworkManager() {
5133 final IBinder tnBinder;
5134 try {
5135 tnBinder = mService.startOrGetTestNetworkService();
5136 } catch (RemoteException e) {
5137 throw e.rethrowFromSystemServer();
5138 }
5139
5140 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5141 }
5142
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09005143 /** @hide */
5144 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5145 return new ConnectivityDiagnosticsManager(mContext, mService);
5146 }
5147
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005148 /**
5149 * Simulates a Data Stall for the specified Network.
5150 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09005151 * <p>This method should only be used for tests.
5152 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005153 * <p>The caller must be the owner of the specified Network.
5154 *
5155 * @param detectionMethod The detection method used to identify the Data Stall.
5156 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
5157 * @param network The Network for which a Data Stall is being simluated.
5158 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5159 * @throws SecurityException if the caller is not the owner of the given network.
5160 * @hide
5161 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09005162 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07005163 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5164 android.Manifest.permission.NETWORK_STACK})
5165 public void simulateDataStall(int detectionMethod, long timestampMillis,
5166 @NonNull Network network, @NonNull PersistableBundle extras) {
5167 try {
5168 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5169 } catch (RemoteException e) {
5170 e.rethrowFromSystemServer();
5171 }
5172 }
James Mattisdcea9fb2020-10-28 21:48:54 -07005173
Daniel Bright60f02ed2020-06-15 16:10:01 -07005174 @NonNull
5175 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5176
5177 /**
5178 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5179 * receive available QoS events related to the {@link Network} and local ip + port
5180 * specified within socketInfo.
5181 * <p/>
5182 * The same {@link QosCallback} must be unregistered before being registered a second time,
5183 * otherwise {@link QosCallbackRegistrationException} is thrown.
5184 * <p/>
5185 * This API does not, in itself, require any permission if called with a network that is not
5186 * restricted. However, the underlying implementation currently only supports the IMS network,
5187 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5188 * useful, because they'd never be called back on networks that they would have access to.
5189 *
5190 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5191 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5192 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5193 * @throws RuntimeException if the app already has too many callbacks registered.
5194 *
5195 * Exceptions after the time of registration is passed through
5196 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5197 *
5198 * @param socketInfo the socket information used to match QoS events
Daniel Bright60f02ed2020-06-15 16:10:01 -07005199 * @param executor The executor on which the callback will be invoked. The provided
5200 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Brightb953a3e2021-03-10 11:51:50 -08005201 * callbacks cannot be guaranteed.onQosCallbackRegistered
5202 * @param callback receives qos events that satisfy socketInfo
Daniel Bright60f02ed2020-06-15 16:10:01 -07005203 *
5204 * @hide
5205 */
5206 @SystemApi
5207 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Brightb953a3e2021-03-10 11:51:50 -08005208 @CallbackExecutor @NonNull final Executor executor,
5209 @NonNull final QosCallback callback) {
Daniel Bright60f02ed2020-06-15 16:10:01 -07005210 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005211 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Brightb953a3e2021-03-10 11:51:50 -08005212 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07005213
5214 try {
5215 synchronized (mQosCallbackConnections) {
5216 if (getQosCallbackConnection(callback) == null) {
5217 final QosCallbackConnection connection =
5218 new QosCallbackConnection(this, callback, executor);
5219 mQosCallbackConnections.add(connection);
5220 mService.registerQosSocketCallback(socketInfo, connection);
5221 } else {
5222 Log.e(TAG, "registerQosCallback: Callback already registered");
5223 throw new QosCallbackRegistrationException();
5224 }
5225 }
5226 } catch (final RemoteException e) {
5227 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5228
5229 // The same unregister method method is called for consistency even though nothing
5230 // will be sent to the ConnectivityService since the callback was never successfully
5231 // registered.
5232 unregisterQosCallback(callback);
5233 e.rethrowFromSystemServer();
5234 } catch (final ServiceSpecificException e) {
5235 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5236 unregisterQosCallback(callback);
5237 throw convertServiceException(e);
5238 }
5239 }
5240
5241 /**
5242 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5243 * events once unregistered and can be registered a second time.
5244 * <p/>
5245 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5246 *
5247 * @param callback the callback being unregistered
5248 *
5249 * @hide
5250 */
5251 @SystemApi
5252 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5253 Objects.requireNonNull(callback, "The callback must be non-null");
5254 try {
5255 synchronized (mQosCallbackConnections) {
5256 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5257 if (connection != null) {
5258 connection.stopReceivingMessages();
5259 mService.unregisterQosCallback(connection);
5260 mQosCallbackConnections.remove(connection);
5261 } else {
5262 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5263 }
5264 }
5265 } catch (final RemoteException e) {
5266 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5267 e.rethrowFromSystemServer();
5268 }
5269 }
5270
5271 /**
5272 * Gets the connection related to the callback.
5273 *
5274 * @param callback the callback to look up
5275 * @return the related connection
5276 */
5277 @Nullable
5278 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5279 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5280 // Checking by reference here is intentional
5281 if (connection.getCallback() == callback) {
5282 return connection;
5283 }
5284 }
5285 return null;
5286 }
Junyu Lai23568a42021-01-19 11:10:56 +00005287
5288 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08005289 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Lai23568a42021-01-19 11:10:56 +00005290 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5291 * be used to request that the system provide a network without causing the network to be
5292 * in the foreground.
5293 *
5294 * <p>This method will attempt to find the best network that matches the passed
5295 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5296 * criteria. The platform will evaluate which network is the best at its own discretion.
5297 * Throughput, latency, cost per byte, policy, user preference and other considerations
5298 * may be factored in the decision of what is considered the best network.
5299 *
5300 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5301 * matching this request, while always attempting to match the request to a better network if
5302 * possible. If a better match is found, the platform will switch this request to the now-best
5303 * network and inform the app of the newly best network by invoking
5304 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5305 * will not try to maintain any other network than the best one currently matching the request:
5306 * a network not matching any network request may be disconnected at any time.
5307 *
5308 * <p>For example, an application could use this method to obtain a connected cellular network
5309 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5310 * radio to consume additional power. Or, an application could inform the system that it wants
5311 * a network supporting sending MMSes and have the system let it know about the currently best
5312 * MMS-supporting network through the provided {@link NetworkCallback}.
5313 *
5314 * <p>The status of the request can be followed by listening to the various callbacks described
5315 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5316 * used to direct traffic to the network (although accessing some networks may be subject to
5317 * holding specific permissions). Callers will learn about the specific characteristics of the
5318 * network through
5319 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5320 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5321 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5322 * matching the request at any given time; therefore when a better network matching the request
5323 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5324 * with the new network after which no further updates are given about the previously-best
5325 * network, unless it becomes the best again at some later time. All callbacks are invoked
5326 * in order on the same thread, which by default is a thread created by the framework running
5327 * in the app.
5328 *
5329 * <p>This{@link NetworkRequest} will live until released via
5330 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5331 * which point the system may let go of the network at any time.
5332 *
5333 * <p>It is presently unsupported to request a network with mutable
5334 * {@link NetworkCapabilities} such as
5335 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5336 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5337 * as these {@code NetworkCapabilities} represent states that a particular
5338 * network may never attain, and whether a network will attain these states
5339 * is unknown prior to bringing up the network so the framework does not
5340 * know how to go about satisfying a request with these capabilities.
5341 *
5342 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5343 * number of outstanding requests to 100 per app (identified by their UID), shared with
5344 * all variants of this method, of {@link #registerNetworkCallback} as well as
5345 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5346 * Requesting a network with this method will count toward this limit. If this limit is
5347 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5348 * make sure to unregister the callbacks with
5349 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5350 *
5351 * @param request {@link NetworkRequest} describing this request.
5352 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5353 * If null, the callback is invoked on the default internal Handler.
5354 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5355 * the callback must not be shared - it uniquely specifies this request.
5356 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5357 * @throws SecurityException if missing the appropriate permissions.
5358 * @throws RuntimeException if the app already has too many callbacks registered.
5359 *
5360 * @hide
5361 */
5362 @SystemApi(client = MODULE_LIBRARIES)
5363 @SuppressLint("ExecutorRegistration")
5364 @RequiresPermission(anyOf = {
5365 android.Manifest.permission.NETWORK_SETTINGS,
5366 android.Manifest.permission.NETWORK_STACK,
5367 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5368 })
5369 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaif4bc12f2021-03-09 20:49:48 +08005370 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Lai23568a42021-01-19 11:10:56 +00005371 final NetworkCapabilities nc = request.networkCapabilities;
5372 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaif4bc12f2021-03-09 20:49:48 +08005373 TYPE_NONE, new CallbackHandler(handler));
Junyu Lai23568a42021-01-19 11:10:56 +00005374 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005375
5376 /**
James Mattis6e6fabf2021-01-10 14:24:24 -08005377 * Used by automotive devices to set the network preferences used to direct traffic at an
5378 * application level as per the given OemNetworkPreferences. An example use-case would be an
5379 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5380 * vehicle via a particular network.
5381 *
5382 * Calling this will overwrite the existing preference.
5383 *
5384 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5385 * @param executor the executor on which listener will be invoked.
5386 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5387 * communicate completion of setOemNetworkPreference(). This will only be
5388 * called once upon successful completion of setOemNetworkPreference().
5389 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5390 * @throws SecurityException if missing the appropriate permissions.
5391 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005392 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005393 */
James Mattis7a253542021-01-26 16:23:52 -08005394 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005395 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005396 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005397 @Nullable @CallbackExecutor final Executor executor,
Chalard Jeancc9ad152021-03-03 16:37:13 +09005398 @Nullable final Runnable listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08005399 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5400 if (null != listener) {
5401 Objects.requireNonNull(executor, "Executor must be non-null");
5402 }
Chalard Jeancc9ad152021-03-03 16:37:13 +09005403 final IOnCompleteListener listenerInternal = listener == null ? null :
5404 new IOnCompleteListener.Stub() {
James Mattis6e6fabf2021-01-10 14:24:24 -08005405 @Override
5406 public void onComplete() {
Chalard Jeancc9ad152021-03-03 16:37:13 +09005407 executor.execute(listener::run);
James Mattis6e6fabf2021-01-10 14:24:24 -08005408 }
5409 };
5410
5411 try {
5412 mService.setOemNetworkPreference(preference, listenerInternal);
5413 } catch (RemoteException e) {
5414 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5415 throw e.rethrowFromSystemServer();
5416 }
5417 }
lucaslin1a6095c2021-03-12 00:46:33 +08005418
Chalard Jean03433052021-02-25 17:23:40 +09005419 /**
5420 * Request that a user profile is put by default on a network matching a given preference.
5421 *
5422 * See the documentation for the individual preferences for a description of the supported
5423 * behaviors.
5424 *
5425 * @param profile the profile concerned.
5426 * @param preference the preference for this profile.
5427 * @param executor an executor to execute the listener on. Optional if listener is null.
5428 * @param listener an optional listener to listen for completion of the operation.
5429 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5430 * @throws SecurityException if missing the appropriate permissions.
5431 * @hide
5432 */
Chalard Jeancc9ad152021-03-03 16:37:13 +09005433 // This function is for establishing per-profile default networking and can only be called by
5434 // the device policy manager, running as the system server. It would make no sense to call it
5435 // on a context for a user because it does not establish a setting on behalf of a user, rather
5436 // it establishes a setting for a user on behalf of the DPM.
5437 @SuppressLint({"UserHandle"})
5438 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09005439 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5440 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5441 @ProfileNetworkPreference final int preference,
5442 @Nullable @CallbackExecutor final Executor executor,
5443 @Nullable final Runnable listener) {
5444 if (null != listener) {
5445 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5446 }
5447 final IOnCompleteListener proxy;
5448 if (null == listener) {
5449 proxy = null;
5450 } else {
5451 proxy = new IOnCompleteListener.Stub() {
5452 @Override
5453 public void onComplete() {
5454 executor.execute(listener::run);
5455 }
5456 };
5457 }
5458 try {
5459 mService.setProfileNetworkPreference(profile, preference, proxy);
5460 } catch (RemoteException e) {
5461 throw e.rethrowFromSystemServer();
5462 }
5463 }
5464
lucaslin1a6095c2021-03-12 00:46:33 +08005465 // The first network ID of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005466 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin1a6095c2021-03-12 00:46:33 +08005467 // The network ID range of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005468 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin1a6095c2021-03-12 00:46:33 +08005469
5470 /**
5471 * Get the network ID range reserved for IPSec tunnel interfaces.
5472 *
5473 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5474 * @hide
5475 */
5476 @SystemApi(client = MODULE_LIBRARIES)
5477 @NonNull
5478 public static Range<Integer> getIpSecNetIdRange() {
5479 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5480 }
lucaslin50205af2021-03-12 16:11:27 +08005481
5482 /**
5483 * Get private DNS mode from settings.
5484 *
lucaslin73c98602021-03-17 14:53:35 +08005485 * @param context The Context to query the private DNS mode from settings.
lucaslin50205af2021-03-12 16:11:27 +08005486 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5487 *
5488 * @hide
5489 */
5490 @SystemApi(client = MODULE_LIBRARIES)
5491 @NonNull
5492 @PrivateDnsMode
lucaslinacd3ded2021-03-16 17:11:14 +08005493 public static String getPrivateDnsMode(@NonNull Context context) {
5494 final ContentResolver cr = context.getContentResolver();
lucaslin50205af2021-03-12 16:11:27 +08005495 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5496 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5497 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5498 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5499 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5500 return mode;
5501 }
paulhu28321462021-03-25 12:36:56 +08005502
5503 /**
5504 * Set private DNS mode to settings.
5505 *
5506 * @param context The {@link Context} to set the private DNS mode.
5507 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5508 *
5509 * @hide
5510 */
5511 @SystemApi(client = MODULE_LIBRARIES)
5512 public static void setPrivateDnsMode(@NonNull Context context,
5513 @NonNull @PrivateDnsMode String mode) {
5514 if (!(mode == PRIVATE_DNS_MODE_OFF
5515 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5516 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5517 throw new IllegalArgumentException("Invalid private dns mode");
5518 }
5519 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5520 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005521}