blob: 3f1ef615706737af57e517d396bf149828621e74 [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 Laia62493f2021-01-19 11:10:56 +000018import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
Junyu Laia62493f2021-01-19 11:10:56 +000019import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaiad010792021-01-11 16:53:38 +080020import static android.net.NetworkRequest.Type.LISTEN;
junyulai1b1c8742021-03-12 20:05:08 +080021import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
junyulaiad010792021-01-11 16:53:38 +080022import static android.net.NetworkRequest.Type.REQUEST;
23import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +090024import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Brightf9e945b2020-06-15 16:10:01 -070025import static android.net.QosCallback.QosCallbackRegistrationException;
lucaslin705c3332021-03-12 17:56:09 +080026import static android.provider.Settings.Global.PRIVATE_DNS_DEFAULT_MODE;
27import static android.provider.Settings.Global.PRIVATE_DNS_MODE;
junyulaid05a1922019-01-15 11:32:44 +080028
junyulai4c95b082018-12-27 17:25:29 +080029import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080030import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090031import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000032import android.annotation.Nullable;
Jeff Sharkey656584a2017-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;
lucaslin705c3332021-03-12 17:56:09 +080036import android.annotation.StringDef;
Junyu Laia62493f2021-01-19 11:10:56 +000037import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080038import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060039import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070040import android.app.PendingIntent;
Artur Satayev9c2add62019-12-10 17:47:52 +000041import android.compat.annotation.UnsupportedAppUsage;
lucaslin705c3332021-03-12 17:56:09 +080042import android.content.ContentResolver;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070043import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070044import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080045import android.net.IpSecManager.UdpEncapsulationSocket;
46import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080047import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080048import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080049import android.net.TetheringManager.TetheringRequest;
Roshan Pius951c0032020-12-22 15:10:42 -080050import android.net.wifi.WifiNetworkSuggestion;
Robert Greenwalt2034b912009-08-12 16:08:25 -070051import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000052import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070053import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080054import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070055import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080056import android.os.IBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070057import android.os.Looper;
58import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070059import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080060import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070061import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090062import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080064import android.os.ResultReceiver;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080065import android.os.ServiceManager;
Hugo Benichia590ab82017-05-11 13:16:17 +090066import android.os.ServiceSpecificException;
Chalard Jeanfa45a682021-02-25 17:23:40 +090067import android.os.UserHandle;
Jeff Sharkey971cd162011-08-29 16:02:57 -070068import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080069import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080070import android.telephony.TelephonyManager;
lucaslin705c3332021-03-12 17:56:09 +080071import android.text.TextUtils;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080072import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070073import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090074import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090075import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080076
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090077import com.android.connectivity.aidl.INetworkAgent;
markchien6ae63e52020-01-21 13:11:06 +080078import com.android.internal.annotations.GuardedBy;
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +000079import com.android.internal.util.Preconditions;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090080import com.android.internal.util.Protocol;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070081
Paul Jensen3e2917c2014-08-27 12:38:45 -040082import libcore.net.event.NetworkEventDispatcher;
83
junyulai7e06ad42019-03-04 22:45:36 +080084import java.io.IOException;
85import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080086import java.lang.annotation.Retention;
87import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090088import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080089import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070090import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080091import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090092import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090093import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080094import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090095import java.util.List;
96import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080097import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080098import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080099import java.util.concurrent.ExecutorService;
100import java.util.concurrent.Executors;
101import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -0800102
The Android Open Source Project28527d22009-03-03 19:31:44 -0800103/**
104 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600105 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800106 * <p>
107 * The primary responsibilities of this class are to:
108 * <ol>
109 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
110 * <li>Send broadcast intents when network connectivity changes</li>
111 * <li>Attempt to "fail over" to another network when connectivity to a network
112 * is lost</li>
113 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
114 * state of the available networks</li>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700115 * <li>Provide an API that allows applications to request and select networks for their data
116 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800117 * </ol>
118 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600119@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700120public class ConnectivityManager {
121 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900122 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700123
The Android Open Source Project28527d22009-03-03 19:31:44 -0800124 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700125 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800126 * been established or lost. The NetworkInfo for the affected network is
127 * sent as an extra; it should be consulted to see what kind of
128 * connectivity event occurred.
129 * <p/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800130 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
131 * broadcast if they declare the broadcast receiver in their manifest. Apps
132 * will still receive broadcasts if they register their
133 * {@link android.content.BroadcastReceiver} with
134 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
135 * and that context is still valid.
136 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800137 * If this is a connection that was the result of failing over from a
138 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
139 * set to true.
140 * <p/>
141 * For a loss of connectivity, if the connectivity manager is attempting
142 * to connect (or has already connected) to another network, the
143 * NetworkInfo for the new network is also passed as an extra. This lets
144 * any receivers of the broadcast know that they should not necessarily
145 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800146 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800147 * the failover attempt succeeded (and so there is still overall data
148 * connectivity), or that the failover attempt failed, meaning that all
149 * connectivity has been lost.
150 * <p/>
151 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
152 * is set to {@code true} if there are no connected networks at all.
Chalard Jean52e23962018-02-10 05:33:50 +0900153 *
154 * @deprecated apps should use the more versatile {@link #requestNetwork},
155 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
156 * functions instead for faster and more detailed updates about the network
157 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800159 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900160 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800161 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700162
The Android Open Source Project28527d22009-03-03 19:31:44 -0800163 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500164 * The device has connected to a network that has presented a captive
165 * portal, which is blocking Internet connectivity. The user was presented
166 * with a notification that network sign in is required,
167 * and the user invoked the notification's action indicating they
Paul Jensen75e0adb2015-05-22 10:50:39 -0400168 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500169 * facilitate signing in to the network. This action includes a
170 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
171 * the network presenting the captive portal; all communication with the
172 * captive portal must be done using this {@code Network} object.
173 * <p/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400174 * This activity includes a {@link CaptivePortal} extra named
175 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
176 * outcomes of the captive portal sign in to the system:
177 * <ul>
178 * <li> When the app handling this action believes the user has signed in to
179 * the network and the captive portal has been dismissed, the app should
180 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
181 * reevaluate the network. If reevaluation finds the network no longer
182 * subject to a captive portal, the network may become the default active
Chalard Jean9dd11612018-06-04 16:52:49 +0900183 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400184 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500185 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400186 * {@link CaptivePortal#ignoreNetwork}. </li>
187 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500188 */
189 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
190 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
191
192 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800193 * The lookup key for a {@link NetworkInfo} object. Retrieve with
194 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700195 *
Chalard Jean97021a12019-01-11 16:47:53 +0900196 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
197 * can't accurately represent modern network characteristics.
198 * Please obtain information about networks from the {@link NetworkCapabilities}
199 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800200 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700201 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800202 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700203
The Android Open Source Project28527d22009-03-03 19:31:44 -0800204 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700205 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700206 *
207 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900208 * @deprecated The network type is not rich enough to represent the characteristics
209 * of modern networks. Please use {@link NetworkCapabilities} instead,
210 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700211 */
Chalard Jean97021a12019-01-11 16:47:53 +0900212 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700213 public static final String EXTRA_NETWORK_TYPE = "networkType";
214
215 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800216 * The lookup key for a boolean that indicates whether a connect event
217 * is for a network to which the connectivity manager was failing over
218 * following a disconnect on another network.
219 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai9826e7f2018-12-13 12:47:51 +0800220 *
221 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222 */
junyulai9826e7f2018-12-13 12:47:51 +0800223 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800224 public static final String EXTRA_IS_FAILOVER = "isFailover";
225 /**
226 * The lookup key for a {@link NetworkInfo} object. This is supplied when
227 * there is another network that it may be possible to connect to. Retrieve with
228 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800229 *
230 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231 */
junyulai9826e7f2018-12-13 12:47:51 +0800232 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800233 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
234 /**
235 * The lookup key for a boolean that indicates whether there is a
236 * complete lack of connectivity, i.e., no network is available.
237 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
238 */
239 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
240 /**
241 * The lookup key for a string that indicates why an attempt to connect
242 * to a network failed. The string has no particular structure. It is
243 * intended to be used in notifications presented to users. Retrieve
244 * it with {@link android.content.Intent#getStringExtra(String)}.
245 */
246 public static final String EXTRA_REASON = "reason";
247 /**
248 * The lookup key for a string that provides optionally supplied
249 * extra information about the network state. The information
250 * may be passed up from the lower networking layers, and its
251 * meaning may be specific to a particular network type. Retrieve
252 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800253 *
254 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800255 */
junyulai9826e7f2018-12-13 12:47:51 +0800256 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800257 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700258 /**
259 * The lookup key for an int that provides information about
260 * our connection to the internet at large. 0 indicates no connection,
261 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700262 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700263 * {@hide}
264 */
265 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800266 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400267 * The lookup key for a {@link CaptivePortal} object included with the
268 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
269 * object can be used to either indicate to the system that the captive
270 * portal has been dismissed or that the user does not want to pursue
271 * signing in to captive portal. Retrieve it with
272 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500273 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400274 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700275
276 /**
277 * Key for passing a URL to the captive portal login activity.
278 */
279 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
280
Paul Jensen60df4aa2015-02-27 22:55:47 -0500281 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900282 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
283 * portal login activity.
284 * {@hide}
285 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900286 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900287 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
288 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
289
290 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900291 * Key for passing a user agent string to the captive portal login activity.
292 * {@hide}
293 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900294 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900295 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
296 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
297
298 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700299 * Broadcast action to indicate the change of data activity status
300 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800301 * The network becomes active when data transmission is started, or
302 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700303 * {@hide}
304 */
305 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900306 public static final String ACTION_DATA_ACTIVITY_CHANGE =
307 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700308 /**
309 * The lookup key for an enum that indicates the network device type on which this data activity
310 * change happens.
311 * {@hide}
312 */
313 public static final String EXTRA_DEVICE_TYPE = "deviceType";
314 /**
315 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
316 * it is actively sending or receiving data and {@code false} means it is idle.
317 * {@hide}
318 */
319 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700320 /**
321 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
322 * {@hide}
323 */
324 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700325
326 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800327 * Broadcast Action: The setting for background data usage has changed
328 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
329 * <p>
330 * If an application uses the network in the background, it should listen
331 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700332 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800333 * <p>
334 *
335 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
336 * of background data depends on several combined factors, and
337 * this broadcast is no longer sent. Instead, when background
338 * data is unavailable, {@link #getActiveNetworkInfo()} will now
339 * appear disconnected. During first boot after a platform
340 * upgrade, this broadcast will be sent once if
341 * {@link #getBackgroundDataSetting()} was {@code false} before
342 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800343 */
344 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800345 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800346 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
347 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
348
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700349 /**
350 * Broadcast Action: The network connection may not be good
351 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
352 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
353 * the network and it's condition.
354 * @hide
355 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800356 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100357 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700358 public static final String INET_CONDITION_ACTION =
359 "android.net.conn.INET_CONDITION_ACTION";
360
Robert Greenwalt2034b912009-08-12 16:08:25 -0700361 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800362 * Broadcast Action: A tetherable connection has come or gone.
363 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900364 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
365 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800366 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
367 * the current state of tethering. Each include a list of
368 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800369 * @hide
370 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800371 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000372 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800373 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800374 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800375
376 /**
377 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800378 * gives a String[] listing all the interfaces configured for
379 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800380 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000381 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800382 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800383
384 /**
385 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900386 * gives a String[] listing all the interfaces currently in local-only
387 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800388 */
markchiena0f8fd92019-12-25 19:40:32 +0800389 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900390
391 /**
392 * @hide
393 * gives a String[] listing all the interfaces currently tethered
394 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
395 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000396 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800397 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800398
399 /**
400 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800401 * gives a String[] listing all the interfaces we tried to tether and
402 * failed. Use {@link #getLastTetherError} to find the error code
403 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800404 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000405 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800406 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800407
408 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800409 * Broadcast Action: The captive portal tracker has finished its test.
410 * Sent only while running Setup Wizard, in lieu of showing a user
411 * notification.
412 * @hide
413 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800414 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800415 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
416 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
417 /**
418 * The lookup key for a boolean that indicates whether a captive portal was detected.
419 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
420 * @hide
421 */
422 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
423
424 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900425 * Action used to display a dialog that asks the user whether to connect to a network that is
426 * not validated. This intent is used to start the dialog in settings via startActivity.
427 *
428 * @hide
429 */
430 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
431
432 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900433 * Action used to display a dialog that asks the user whether to avoid a network that is no
434 * longer validated. This intent is used to start the dialog in settings via startActivity.
435 *
436 * @hide
437 */
438 public static final String ACTION_PROMPT_LOST_VALIDATION =
439 "android.net.conn.PROMPT_LOST_VALIDATION";
440
441 /**
lucaslin2240ef62019-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 */
448 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
449 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
450
451 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800452 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900453 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800454 * @hide
455 */
markchiena0f8fd92019-12-25 19:40:32 +0800456 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800457
458 /**
459 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900460 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800461 * @hide
462 */
463 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900464 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800465
466 /**
467 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900468 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800469 * @hide
470 */
471 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900472 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800473
474 /**
475 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900476 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800477 * @hide
478 */
479 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900480 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800481
482 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800483 * Wifi P2p tethering type.
484 * Wifi P2p tethering is set through events automatically, and don't
485 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
486 * @hide
487 */
markchiena0f8fd92019-12-25 19:40:32 +0800488 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800489
490 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800491 * Extra used for communicating with the TetherService. Includes the type of tethering to
492 * enable if any.
493 * @hide
494 */
markchien6ae63e52020-01-21 13:11:06 +0800495 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800496
497 /**
498 * Extra used for communicating with the TetherService. Includes the type of tethering for
499 * which to cancel provisioning.
500 * @hide
501 */
markchien6ae63e52020-01-21 13:11:06 +0800502 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800503
504 /**
505 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
506 * provisioning.
507 * @hide
508 */
markchien6ae63e52020-01-21 13:11:06 +0800509 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800510
511 /**
512 * Tells the TetherService to run a provision check now.
513 * @hide
514 */
markchien6ae63e52020-01-21 13:11:06 +0800515 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800516
517 /**
518 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
519 * which will receive provisioning results. Can be left empty.
520 * @hide
521 */
markchien6ae63e52020-01-21 13:11:06 +0800522 public static final String EXTRA_PROVISION_CALLBACK =
523 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800524
525 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800526 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700527 * @hide
528 */
paulhu74357e72020-01-13 16:46:45 +0800529 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700530 public static final int TYPE_NONE = -1;
531
532 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900533 * A Mobile data connection. Devices may support more than one.
534 *
535 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
536 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
537 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700538 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900539 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700540 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900541
Robert Greenwalt2034b912009-08-12 16:08:25 -0700542 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900543 * A WIFI data connection. Devices may support more than one.
544 *
545 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
546 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
547 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700548 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900549 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700550 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900551
Robert Greenwalt2034b912009-08-12 16:08:25 -0700552 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800553 * An MMS-specific Mobile data connection. This network type may use the
554 * same network interface as {@link #TYPE_MOBILE} or it may use a different
555 * one. This is used by applications needing to talk to the carrier's
556 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900557 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900558 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900559 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900560 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700561 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700562 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700563 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900564
Robert Greenwalt2034b912009-08-12 16:08:25 -0700565 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800566 * A SUPL-specific Mobile data connection. This network type may use the
567 * same network interface as {@link #TYPE_MOBILE} or it may use a different
568 * one. This is used by applications needing to talk to the carrier's
569 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900570 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900571 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900572 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900573 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700574 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700575 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700576 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900577
Robert Greenwalt2034b912009-08-12 16:08:25 -0700578 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800579 * A DUN-specific Mobile data connection. This network type may use the
580 * same network interface as {@link #TYPE_MOBILE} or it may use a different
581 * one. This is sometimes by the system when setting up an upstream connection
582 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900583 *
584 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
585 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
586 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700587 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900588 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700589 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900590
Robert Greenwalt2034b912009-08-12 16:08:25 -0700591 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800592 * A High Priority Mobile data connection. This network type uses the
593 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900594 * is different.
595 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900596 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
597 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
598 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700599 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700600 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700601 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900602
jshbfa81722010-03-11 15:04:43 -0800603 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900604 * A WiMAX data connection.
605 *
606 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
607 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
608 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800609 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900610 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800611 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800612
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800613 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900614 * A Bluetooth data connection.
615 *
616 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
617 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
618 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800619 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900620 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800621 public static final int TYPE_BLUETOOTH = 7;
622
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700623 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800624 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900625 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700626 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900627 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800628 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800629
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700630 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900631 * An Ethernet data connection.
632 *
633 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
634 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
635 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700636 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900637 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800638 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700639
Wink Savilleb7c92c72011-03-12 14:52:01 -0800640 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800641 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900642 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800643 * {@hide}
644 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900645 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900646 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800647 public static final int TYPE_MOBILE_FOTA = 10;
648
649 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800650 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900651 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800652 * {@hide}
653 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900654 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100655 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800656 public static final int TYPE_MOBILE_IMS = 11;
657
658 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800659 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900660 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800661 * {@hide}
662 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900663 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900664 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800665 public static final int TYPE_MOBILE_CBS = 12;
666
repo syncf5de5572011-07-29 23:55:49 -0700667 /**
668 * A Wi-Fi p2p connection. Only requesting processes will have access to
669 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900670 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700671 * {@hide}
672 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900673 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800674 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700675 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800676
Wink Saville512c2202013-07-29 15:00:57 -0700677 /**
678 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900679 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700680 * {@hide}
681 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900682 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100683 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700684 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700685
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900686 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700687 * Emergency PDN connection for emergency services. This
688 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900689 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700690 * {@hide}
691 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900692 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900693 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700694 public static final int TYPE_MOBILE_EMERGENCY = 15;
695
Hui Lu865b70d2014-01-15 11:05:36 -0500696 /**
697 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900698 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500699 * {@hide}
700 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900701 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900702 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500703 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700704
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700705 /**
706 * A virtual network using one or more native bearers.
707 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900708 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700709 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900710 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700711 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500712
Benedict Wongbdfaa482018-11-14 17:40:55 -0800713 /**
714 * A network that is exclusively meant to be used for testing
715 *
716 * @deprecated Use {@link NetworkCapabilities} instead.
717 * @hide
718 */
719 @Deprecated
720 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700721
Chalard Jeanaea539a2020-03-25 01:24:04 +0900722 /**
723 * @deprecated Use {@link NetworkCapabilities} instead.
724 * @hide
725 */
726 @Deprecated
727 @Retention(RetentionPolicy.SOURCE)
728 @IntDef(prefix = { "TYPE_" }, value = {
729 TYPE_NONE,
730 TYPE_MOBILE,
731 TYPE_WIFI,
732 TYPE_MOBILE_MMS,
733 TYPE_MOBILE_SUPL,
734 TYPE_MOBILE_DUN,
735 TYPE_MOBILE_HIPRI,
736 TYPE_WIMAX,
737 TYPE_BLUETOOTH,
738 TYPE_DUMMY,
739 TYPE_ETHERNET,
740 TYPE_MOBILE_FOTA,
741 TYPE_MOBILE_IMS,
742 TYPE_MOBILE_CBS,
743 TYPE_WIFI_P2P,
744 TYPE_MOBILE_IA,
745 TYPE_MOBILE_EMERGENCY,
746 TYPE_PROXY,
747 TYPE_VPN,
748 TYPE_TEST
749 })
750 public @interface LegacyNetworkType {}
751
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900752 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
753 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
754 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
755 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
756 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
757
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700758 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800759 public static final int MAX_RADIO_TYPE = TYPE_TEST;
760
761 /** {@hide} */
762 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800763
Hugo Benichiad353f42017-06-20 14:07:59 +0900764 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
765
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800766 /**
767 * If you want to set the default network preference,you can directly
768 * change the networkAttributes array in framework's config.xml.
769 *
770 * @deprecated Since we support so many more networks now, the single
771 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800772 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800773 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800774 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800775 * from an App.
776 */
777 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800778 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
779
Jeff Sharkey8c870452012-09-26 22:03:49 -0700780 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700781 * @hide
782 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900783 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700784
Paul Jensen5dea4352014-07-11 12:28:19 -0400785 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900786 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
787 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900788 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900789 * @hide
790 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900791 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900792 new NetworkRequest.Builder().clearCapabilities().build();
793
794 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400795 * A NetID indicating no Network is selected.
796 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
797 * @hide
798 */
799 public static final int NETID_UNSET = 0;
800
Erik Klineb0be3e62017-10-30 15:29:44 +0900801 /**
802 * Private DNS Mode values.
803 *
804 * The "private_dns_mode" global setting stores a String value which is
805 * expected to be one of the following.
806 */
807
808 /**
809 * @hide
810 */
lucaslin705c3332021-03-12 17:56:09 +0800811 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900812 public static final String PRIVATE_DNS_MODE_OFF = "off";
813 /**
814 * @hide
815 */
lucaslin705c3332021-03-12 17:56:09 +0800816 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900817 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
818 /**
819 * @hide
820 */
lucaslin705c3332021-03-12 17:56:09 +0800821 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900822 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin705c3332021-03-12 17:56:09 +0800823
824 /** @hide */
825 @Retention(RetentionPolicy.SOURCE)
826 @StringDef(value = {
827 PRIVATE_DNS_MODE_OFF,
828 PRIVATE_DNS_MODE_OPPORTUNISTIC,
829 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
830 })
831 public @interface PrivateDnsMode {}
Erik Klineb0be3e62017-10-30 15:29:44 +0900832
Chalard Jeana3b77512019-04-09 15:46:21 +0900833 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700834 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900835
Paul Jensenc0618a62014-12-10 15:12:18 -0500836 /**
837 * A kludge to facilitate static access where a Context pointer isn't available, like in the
838 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
839 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
840 * methods that take a Context argument.
841 */
842 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800843
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900844 private final Context mContext;
845
Felipe Leme30511352016-01-22 09:44:57 -0800846 private INetworkPolicyManager mNPManager;
Amos Bianchia9b415a2020-03-04 11:07:38 -0800847 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800848
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800849 /**
850 * Tests if a given integer represents a valid network type.
851 * @param networkType the type to be tested
852 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400853 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
854 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800855 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700856 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700857 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900858 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800859 }
860
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800861 /**
862 * Returns a non-localized string representing a given network type.
863 * ONLY used for debugging output.
864 * @param type the type needing naming
865 * @return a String for the given type, or a string version of the type ("87")
866 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900867 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800868 * {@hide}
869 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900870 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000871 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700872 public static String getNetworkTypeName(int type) {
873 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900874 case TYPE_NONE:
875 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700876 case TYPE_MOBILE:
877 return "MOBILE";
878 case TYPE_WIFI:
879 return "WIFI";
880 case TYPE_MOBILE_MMS:
881 return "MOBILE_MMS";
882 case TYPE_MOBILE_SUPL:
883 return "MOBILE_SUPL";
884 case TYPE_MOBILE_DUN:
885 return "MOBILE_DUN";
886 case TYPE_MOBILE_HIPRI:
887 return "MOBILE_HIPRI";
888 case TYPE_WIMAX:
889 return "WIMAX";
890 case TYPE_BLUETOOTH:
891 return "BLUETOOTH";
892 case TYPE_DUMMY:
893 return "DUMMY";
894 case TYPE_ETHERNET:
895 return "ETHERNET";
896 case TYPE_MOBILE_FOTA:
897 return "MOBILE_FOTA";
898 case TYPE_MOBILE_IMS:
899 return "MOBILE_IMS";
900 case TYPE_MOBILE_CBS:
901 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700902 case TYPE_WIFI_P2P:
903 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700904 case TYPE_MOBILE_IA:
905 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700906 case TYPE_MOBILE_EMERGENCY:
907 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500908 case TYPE_PROXY:
909 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900910 case TYPE_VPN:
911 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700912 default:
913 return Integer.toString(type);
914 }
915 }
916
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800917 /**
Aaron Huang96011892020-06-27 07:18:23 +0800918 * @hide
919 * TODO: Expose for SystemServer when becomes a module.
920 */
921 public void systemReady() {
922 try {
923 mService.systemReady();
924 } catch (RemoteException e) {
925 throw e.rethrowFromSystemServer();
926 }
927 }
928
929 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800930 * Checks if a given type uses the cellular data connection.
931 * This should be replaced in the future by a network property.
932 * @param networkType the type to check
933 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900934 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800935 * {@hide}
936 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900937 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900938 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700939 public static boolean isNetworkTypeMobile(int networkType) {
940 switch (networkType) {
941 case TYPE_MOBILE:
942 case TYPE_MOBILE_MMS:
943 case TYPE_MOBILE_SUPL:
944 case TYPE_MOBILE_DUN:
945 case TYPE_MOBILE_HIPRI:
946 case TYPE_MOBILE_FOTA:
947 case TYPE_MOBILE_IMS:
948 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -0700949 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -0700950 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700951 return true;
952 default:
953 return false;
954 }
955 }
956
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800957 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700958 * Checks if the given network type is backed by a Wi-Fi radio.
959 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900960 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700961 * @hide
962 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900963 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700964 public static boolean isNetworkTypeWifi(int networkType) {
965 switch (networkType) {
966 case TYPE_WIFI:
967 case TYPE_WIFI_P2P:
968 return true;
969 default:
970 return false;
971 }
972 }
973
974 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +0900975 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
976 * Specify that the traffic for this user should by follow the default rules.
977 * @hide
978 */
Chalard Jeanb43f3962021-03-17 14:33:24 +0900979 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +0900980 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
981
982 /**
983 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
984 * Specify that the traffic for this user should by default go on a network with
985 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
986 * if no such network is available.
987 * @hide
988 */
Chalard Jeanb43f3962021-03-17 14:33:24 +0900989 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +0900990 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
991
992 /** @hide */
993 @Retention(RetentionPolicy.SOURCE)
994 @IntDef(value = {
995 PROFILE_NETWORK_PREFERENCE_DEFAULT,
996 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
997 })
998 public @interface ProfileNetworkPreference {
999 }
1000
1001 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001002 * Specifies the preferred network type. When the device has more
1003 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001004 *
1005 * @param preference the network type to prefer over all others. It is
1006 * unspecified what happens to the old preferred network in the
1007 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001008 * @deprecated Functionality has been removed as it no longer makes sense,
1009 * with many more than two networks - we'd need an array to express
1010 * preference. Instead we use dynamic network properties of
1011 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001012 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001013 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001014 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001015 }
1016
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001017 /**
1018 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001019 *
1020 * @return an integer representing the preferred network type
1021 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001022 * @deprecated Functionality has been removed as it no longer makes sense,
1023 * with many more than two networks - we'd need an array to express
1024 * preference. Instead we use dynamic network properties of
1025 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001026 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001027 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001028 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001029 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001030 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001031 }
1032
Scott Mainf58b7d82011-10-06 19:02:28 -07001033 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001034 * Returns details about the currently active default data network. When
1035 * connected, this network is the default route for outgoing connections.
1036 * You should always check {@link NetworkInfo#isConnected()} before initiating
1037 * network traffic. This may return {@code null} when there is no default
1038 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001039 * Note that if the default network is a VPN, this method will return the
1040 * NetworkInfo for one of its underlying networks instead, or null if the
1041 * VPN agent did not specify any. Apps interested in learning about VPNs
1042 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001043 *
1044 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001045 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001046 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001047 */
junyulai9826e7f2018-12-13 12:47:51 +08001048 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001049 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001050 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001051 public NetworkInfo getActiveNetworkInfo() {
1052 try {
1053 return mService.getActiveNetworkInfo();
1054 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001055 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001056 }
1057 }
1058
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001059 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001060 * Returns a {@link Network} object corresponding to the currently active
1061 * default data network. In the event that the current active default data
1062 * network disconnects, the returned {@code Network} object will no longer
1063 * be usable. This will return {@code null} when there is no default
1064 * network.
1065 *
1066 * @return a {@link Network} object for the current default network or
1067 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001068 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001069 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001070 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001071 public Network getActiveNetwork() {
1072 try {
1073 return mService.getActiveNetwork();
1074 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001075 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001076 }
1077 }
1078
1079 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001080 * Returns a {@link Network} object corresponding to the currently active
1081 * default data network for a specific UID. In the event that the default data
1082 * network disconnects, the returned {@code Network} object will no longer
1083 * be usable. This will return {@code null} when there is no default
1084 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001085 *
1086 * @return a {@link Network} object for the current default network for the
1087 * given UID or {@code null} if no default network is currently active
1088 *
1089 * @hide
1090 */
paulhu8e96a752019-08-12 16:25:11 +08001091 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001092 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001093 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001094 return getActiveNetworkForUid(uid, false);
1095 }
1096
1097 /** {@hide} */
1098 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001099 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001100 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001101 } catch (RemoteException e) {
1102 throw e.rethrowFromSystemServer();
1103 }
1104 }
1105
1106 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001107 * Adds or removes a requirement for given UID ranges to use the VPN.
1108 *
1109 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1110 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1111 * otherwise have permission to bypass the VPN (e.g., because they have the
1112 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1113 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1114 * set to {@code false}, a previously-added restriction is removed.
1115 * <p>
1116 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1117 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1118 * remove a previously-added range, the exact range must be removed as is.
1119 * <p>
1120 * The changes are applied asynchronously and may not have been applied by the time the method
1121 * returns. Apps will be notified about any changes that apply to them via
1122 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1123 * effect.
1124 * <p>
1125 * This method should be called only by the VPN code.
1126 *
1127 * @param ranges the UID ranges to restrict
1128 * @param requireVpn whether the specified UID ranges must use a VPN
1129 *
1130 * TODO: expose as @SystemApi.
1131 * @hide
1132 */
1133 @RequiresPermission(anyOf = {
1134 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1135 android.Manifest.permission.NETWORK_STACK})
1136 public void setRequireVpnForUids(boolean requireVpn,
1137 @NonNull Collection<Range<Integer>> ranges) {
1138 Objects.requireNonNull(ranges);
1139 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1140 // This method is not necessarily expected to be used outside the system server, so
1141 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1142 // stack process, or by tests.
1143 UidRange[] rangesArray = new UidRange[ranges.size()];
1144 int index = 0;
1145 for (Range<Integer> range : ranges) {
1146 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1147 }
1148 try {
1149 mService.setRequireVpnForUids(requireVpn, rangesArray);
1150 } catch (RemoteException e) {
1151 throw e.rethrowFromSystemServer();
1152 }
1153 }
1154
1155 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001156 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1157 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1158 * but is still supported for backwards compatibility.
1159 * <p>
1160 * This type of VPN is assumed always to use the system default network, and must always declare
1161 * exactly one underlying network, which is the network that was the default when the VPN
1162 * connected.
1163 * <p>
1164 * Calling this method with {@code true} enables legacy behaviour, specifically:
1165 * <ul>
1166 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1167 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1168 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1169 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1170 * underlying the VPN.</li>
1171 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1172 * similarly replaced by the VPN network state.</li>
1173 * <li>Information on current network interfaces passed to NetworkStatsService will not
1174 * include any VPN interfaces.</li>
1175 * </ul>
1176 *
1177 * @param enabled whether legacy lockdown VPN is enabled or disabled
1178 *
1179 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1180 *
1181 * @hide
1182 */
1183 @RequiresPermission(anyOf = {
1184 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1185 android.Manifest.permission.NETWORK_SETTINGS})
1186 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1187 try {
1188 mService.setLegacyLockdownVpnEnabled(enabled);
1189 } catch (RemoteException e) {
1190 throw e.rethrowFromSystemServer();
1191 }
1192 }
1193
1194 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001195 * Returns details about the currently active default data network
1196 * for a given uid. This is for internal use only to avoid spying
1197 * other apps.
1198 *
1199 * @return a {@link NetworkInfo} object for the current default network
1200 * for the given uid or {@code null} if no default network is
1201 * available for the specified uid.
1202 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001203 * {@hide}
1204 */
paulhu8e96a752019-08-12 16:25:11 +08001205 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001206 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001207 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001208 return getActiveNetworkInfoForUid(uid, false);
1209 }
1210
1211 /** {@hide} */
1212 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001213 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001214 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001215 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001216 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001217 }
1218 }
1219
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001220 /**
1221 * Returns connection status information about a particular
1222 * network type.
1223 *
1224 * @param networkType integer specifying which networkType in
1225 * which you're interested.
1226 * @return a {@link NetworkInfo} object for the requested
1227 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001228 * supported by the device. If {@code networkType} is
1229 * TYPE_VPN and a VPN is active for the calling app,
1230 * then this method will try to return one of the
1231 * underlying networks for the VPN or null if the
1232 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001233 *
Paul Jensendda8e592015-03-18 12:23:02 -04001234 * @deprecated This method does not support multiple connected networks
1235 * of the same type. Use {@link #getAllNetworks} and
1236 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001237 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001238 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001239 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001240 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001241 public NetworkInfo getNetworkInfo(int networkType) {
1242 try {
1243 return mService.getNetworkInfo(networkType);
1244 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001245 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001246 }
1247 }
1248
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001249 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001250 * Returns connection status information about a particular
1251 * Network.
1252 *
1253 * @param network {@link Network} specifying which network
1254 * in which you're interested.
1255 * @return a {@link NetworkInfo} object for the requested
1256 * network or {@code null} if the {@code Network}
1257 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001258 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001259 */
junyulai9826e7f2018-12-13 12:47:51 +08001260 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001261 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001262 @Nullable
1263 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001264 return getNetworkInfoForUid(network, Process.myUid(), false);
1265 }
1266
1267 /** {@hide} */
1268 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001269 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001270 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001271 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001272 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001273 }
1274 }
1275
1276 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001277 * Returns connection status information about all network
1278 * types supported by the device.
1279 *
1280 * @return an array of {@link NetworkInfo} objects. Check each
1281 * {@link NetworkInfo#getType} for which type each applies.
1282 *
Paul Jensendda8e592015-03-18 12:23:02 -04001283 * @deprecated This method does not support multiple connected networks
1284 * of the same type. Use {@link #getAllNetworks} and
1285 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001286 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001287 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001288 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001289 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001290 public NetworkInfo[] getAllNetworkInfo() {
1291 try {
1292 return mService.getAllNetworkInfo();
1293 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001294 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001295 }
1296 }
1297
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001298 /**
junyulaiebd15162021-03-03 12:09:05 +08001299 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1300 * connected.
1301 * @hide
1302 */
1303 @SystemApi(client = MODULE_LIBRARIES)
1304 @RequiresPermission(anyOf = {
1305 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1306 android.Manifest.permission.NETWORK_STACK,
1307 android.Manifest.permission.NETWORK_SETTINGS})
1308 @NonNull
1309 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1310 try {
1311 return mService.getAllNetworkStateSnapshot();
1312 } catch (RemoteException e) {
1313 throw e.rethrowFromSystemServer();
1314 }
1315 }
1316
1317 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001318 * Returns the {@link Network} object currently serving a given type, or
1319 * null if the given type is not connected.
1320 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001321 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001322 * @deprecated This method does not support multiple connected networks
1323 * of the same type. Use {@link #getAllNetworks} and
1324 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001325 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001326 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001327 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001328 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001329 public Network getNetworkForType(int networkType) {
1330 try {
1331 return mService.getNetworkForType(networkType);
1332 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001333 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001334 }
1335 }
1336
1337 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001338 * Returns an array of all {@link Network} currently tracked by the
1339 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001340 *
1341 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001342 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001343 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001344 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001345 public Network[] getAllNetworks() {
1346 try {
1347 return mService.getAllNetworks();
1348 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001349 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001350 }
1351 }
1352
1353 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001354 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001355 * the Networks that applications run by the given user will use by default.
1356 * @hide
1357 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001358 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001359 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1360 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001361 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001362 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001363 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001364 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001365 }
1366 }
1367
1368 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001369 * Returns the IP information for the current default network.
1370 *
1371 * @return a {@link LinkProperties} object describing the IP info
1372 * for the current default network, or {@code null} if there
1373 * is no current default network.
1374 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001375 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001376 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1377 * value of {@link #getActiveNetwork()} instead. In particular,
1378 * this method will return non-null LinkProperties even if the
1379 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001380 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001381 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001382 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001383 public LinkProperties getActiveLinkProperties() {
1384 try {
1385 return mService.getActiveLinkProperties();
1386 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001387 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001388 }
1389 }
1390
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001391 /**
1392 * Returns the IP information for a given network type.
1393 *
1394 * @param networkType the network type of interest.
1395 * @return a {@link LinkProperties} object describing the IP info
1396 * for the given networkType, or {@code null} if there is
1397 * no current default network.
1398 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001399 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001400 * @deprecated This method does not support multiple connected networks
1401 * of the same type. Use {@link #getAllNetworks},
1402 * {@link #getNetworkInfo(android.net.Network)}, and
1403 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001404 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001405 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001406 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001407 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001408 public LinkProperties getLinkProperties(int networkType) {
1409 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001410 return mService.getLinkPropertiesForType(networkType);
1411 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001412 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001413 }
1414 }
1415
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001416 /**
1417 * Get the {@link LinkProperties} for the given {@link Network}. This
1418 * will return {@code null} if the network is unknown.
1419 *
1420 * @param network The {@link Network} object identifying the network in question.
1421 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001422 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001423 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001424 @Nullable
1425 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001426 try {
1427 return mService.getLinkProperties(network);
1428 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001429 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001430 }
1431 }
1432
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001433 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001434 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001435 * will return {@code null} if the network is unknown.
1436 *
Roshan Pius951c0032020-12-22 15:10:42 -08001437 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1438 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1439 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1440 * this location sensitive information (subject to app's location permissions) will be
1441 * noted by system. To include any location sensitive data in {@link TransportInfo},
1442 * use a {@link NetworkCallback} with
1443 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1444 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001445 * @param network The {@link Network} object identifying the network in question.
Roshan Pius951c0032020-12-22 15:10:42 -08001446 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001447 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001448 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001449 @Nullable
1450 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001451 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001452 return mService.getNetworkCapabilities(
1453 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001454 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001455 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001456 }
1457 }
1458
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001459 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001460 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001461 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1462 * portal is present.
1463 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1464 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1465 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001466 * The system network validation may be using different strategies to detect captive portals,
1467 * so this method does not necessarily return a URL used by the system. It only returns a URL
1468 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001469 *
Udam Sainicd645462016-01-04 12:16:14 -08001470 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001471 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1472 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001473 */
paulhu8e96a752019-08-12 16:25:11 +08001474 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001475 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001476 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001477 public String getCaptivePortalServerUrl() {
1478 try {
1479 return mService.getCaptivePortalServerUrl();
1480 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001481 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001482 }
1483 }
1484
1485 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001486 * Tells the underlying networking system that the caller wants to
1487 * begin using the named feature. The interpretation of {@code feature}
1488 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001489 *
1490 * <p>This method requires the caller to hold either the
1491 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1492 * or the ability to modify system settings as determined by
1493 * {@link android.provider.Settings.System#canWrite}.</p>
1494 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001495 * @param networkType specifies which network the request pertains to
1496 * @param feature the name of the feature to be used
1497 * @return an integer value representing the outcome of the request.
1498 * The interpretation of this value is specific to each networking
1499 * implementation+feature combination, except that the value {@code -1}
1500 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001501 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001502 * @deprecated Deprecated in favor of the cleaner
1503 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001504 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001505 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001506 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001507 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001508 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001509 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001510 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001511 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1512 if (netCap == null) {
1513 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1514 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001515 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001516 }
1517
1518 NetworkRequest request = null;
1519 synchronized (sLegacyRequests) {
1520 LegacyRequest l = sLegacyRequests.get(netCap);
1521 if (l != null) {
1522 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1523 renewRequestLocked(l);
1524 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001525 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001526 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001527 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001528 }
1529 }
1530
1531 request = requestNetworkForFeatureLocked(netCap);
1532 }
1533 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001534 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001535 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001536 } else {
1537 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001538 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001539 }
1540 }
1541
1542 /**
1543 * Tells the underlying networking system that the caller is finished
1544 * using the named feature. The interpretation of {@code feature}
1545 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001546 *
1547 * <p>This method requires the caller to hold either the
1548 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1549 * or the ability to modify system settings as determined by
1550 * {@link android.provider.Settings.System#canWrite}.</p>
1551 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001552 * @param networkType specifies which network the request pertains to
1553 * @param feature the name of the feature that is no longer needed
1554 * @return an integer value representing the outcome of the request.
1555 * The interpretation of this value is specific to each networking
1556 * implementation+feature combination, except that the value {@code -1}
1557 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001558 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001559 * @deprecated Deprecated in favor of the cleaner
1560 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001561 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001562 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001563 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001564 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001565 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001566 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001567 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001568 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1569 if (netCap == null) {
1570 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1571 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001572 return -1;
1573 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001574
Paul Jensen49f74a32014-12-17 10:39:34 -05001575 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001576 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001577 }
1578 return 1;
1579 }
1580
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001581 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001582 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1583 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001584 switch (feature) {
1585 case "enableCBS":
1586 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1587 case "enableDUN":
1588 case "enableDUNAlways":
1589 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1590 case "enableFOTA":
1591 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1592 case "enableHIPRI":
1593 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1594 case "enableIMS":
1595 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1596 case "enableMMS":
1597 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1598 case "enableSUPL":
1599 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1600 default:
1601 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001602 }
Erik Klinece55eb12017-01-26 18:08:28 +09001603 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1604 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001605 }
1606 return null;
1607 }
1608
Robert Greenwalt802c1102014-06-02 15:32:02 -07001609 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001610 if (netCap == null) return TYPE_NONE;
1611 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1612 return TYPE_MOBILE_CBS;
1613 }
1614 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1615 return TYPE_MOBILE_IMS;
1616 }
1617 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1618 return TYPE_MOBILE_FOTA;
1619 }
1620 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1621 return TYPE_MOBILE_DUN;
1622 }
1623 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1624 return TYPE_MOBILE_SUPL;
1625 }
1626 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1627 return TYPE_MOBILE_MMS;
1628 }
1629 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1630 return TYPE_MOBILE_HIPRI;
1631 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001632 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1633 return TYPE_WIFI_P2P;
1634 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001635 return TYPE_NONE;
1636 }
1637
1638 private static class LegacyRequest {
1639 NetworkCapabilities networkCapabilities;
1640 NetworkRequest networkRequest;
1641 int expireSequenceNumber;
1642 Network currentNetwork;
1643 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001644
1645 private void clearDnsBinding() {
1646 if (currentNetwork != null) {
1647 currentNetwork = null;
1648 setProcessDefaultNetworkForHostResolution(null);
1649 }
1650 }
1651
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001652 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001653 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001654 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001655 currentNetwork = network;
1656 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001657 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001658 }
1659 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001660 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001661 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001662 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1663 }
1664 };
1665 }
1666
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001667 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001668 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1669 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001670
1671 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1672 synchronized (sLegacyRequests) {
1673 LegacyRequest l = sLegacyRequests.get(netCap);
1674 if (l != null) return l.networkRequest;
1675 }
1676 return null;
1677 }
1678
1679 private void renewRequestLocked(LegacyRequest l) {
1680 l.expireSequenceNumber++;
1681 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1682 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1683 }
1684
1685 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1686 int ourSeqNum = -1;
1687 synchronized (sLegacyRequests) {
1688 LegacyRequest l = sLegacyRequests.get(netCap);
1689 if (l == null) return;
1690 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001691 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001692 }
1693 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1694 }
1695
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001696 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001697 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1698 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001699 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001700 try {
1701 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001702 } catch (RemoteException e) {
1703 throw e.rethrowFromSystemServer();
1704 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001705 LegacyRequest l = new LegacyRequest();
1706 l.networkCapabilities = netCap;
1707 l.delay = delay;
1708 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001709 l.networkRequest = sendRequestForNetwork(
1710 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001711 if (l.networkRequest == null) return null;
1712 sLegacyRequests.put(netCap, l);
1713 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1714 return l.networkRequest;
1715 }
1716
1717 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1718 if (delay >= 0) {
1719 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001720 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001721 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1722 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001723 }
1724 }
1725
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001726 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001727 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1728 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001729 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001730 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001731 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001732 if (l == null) return false;
1733 unregisterNetworkCallback(l.networkCallback);
1734 l.clearDnsBinding();
1735 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001736 }
1737
Erik Klinece55eb12017-01-26 18:08:28 +09001738 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1739 static {
1740 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1741 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1742 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1743 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1744 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1745 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1746 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1747 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1748 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1749 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1750 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1751 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1752 }
1753
1754 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1755 static {
1756 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1757 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1758 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1759 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1760 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1761 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1762 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1763 }
1764
1765 /**
1766 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1767 * instance suitable for registering a request or callback. Throws an
1768 * IllegalArgumentException if no mapping from the legacy type to
1769 * NetworkCapabilities is known.
1770 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001771 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1772 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001773 * @hide
1774 */
1775 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1776 final NetworkCapabilities nc = new NetworkCapabilities();
1777
1778 // Map from type to transports.
1779 final int NOT_FOUND = -1;
1780 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00001781 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001782 nc.addTransportType(transport);
1783
1784 // Map from type to capabilities.
1785 nc.addCapability(sLegacyTypeToCapability.get(
1786 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1787 nc.maybeMarkCapabilitiesRestricted();
1788 return nc;
1789 }
1790
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001791 /** @hide */
1792 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001793 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001794 public PacketKeepaliveCallback() {
1795 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001796 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001797 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001798 public void onStarted() {}
1799 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001800 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001801 public void onStopped() {}
1802 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001803 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001804 public void onError(int error) {}
1805 }
1806
1807 /**
1808 * Allows applications to request that the system periodically send specific packets on their
1809 * behalf, using hardware offload to save battery power.
1810 *
1811 * To request that the system send keepalives, call one of the methods that return a
1812 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1813 * passing in a non-null callback. If the callback is successfully started, the callback's
1814 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1815 * specifying one of the {@code ERROR_*} constants in this class.
1816 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001817 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1818 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1819 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001820 *
junyulai4c95b082018-12-27 17:25:29 +08001821 * @deprecated Use {@link SocketKeepalive} instead.
1822 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001823 * @hide
1824 */
1825 public class PacketKeepalive {
1826
1827 private static final String TAG = "PacketKeepalive";
1828
1829 /** @hide */
1830 public static final int SUCCESS = 0;
1831
1832 /** @hide */
1833 public static final int NO_KEEPALIVE = -1;
1834
1835 /** @hide */
1836 public static final int BINDER_DIED = -10;
1837
1838 /** The specified {@code Network} is not connected. */
1839 public static final int ERROR_INVALID_NETWORK = -20;
1840 /** The specified IP addresses are invalid. For example, the specified source IP address is
1841 * not configured on the specified {@code Network}. */
1842 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1843 /** The requested port is invalid. */
1844 public static final int ERROR_INVALID_PORT = -22;
1845 /** The packet length is invalid (e.g., too long). */
1846 public static final int ERROR_INVALID_LENGTH = -23;
1847 /** The packet transmission interval is invalid (e.g., too short). */
1848 public static final int ERROR_INVALID_INTERVAL = -24;
1849
1850 /** The hardware does not support this request. */
1851 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001852 /** The hardware returned an error. */
1853 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001854
Nathan Harold0990bc82018-02-14 13:09:45 -08001855 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001856 public static final int NATT_PORT = 4500;
1857
Nathan Harold0990bc82018-02-14 13:09:45 -08001858 /** The minimum interval in seconds between keepalive packet transmissions */
1859 public static final int MIN_INTERVAL = 10;
1860
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001861 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001862 private final ISocketKeepaliveCallback mCallback;
1863 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001864
1865 private volatile Integer mSlot;
1866
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001867 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001868 public void stop() {
1869 try {
junyulai070f9ff2019-01-16 20:23:34 +08001870 mExecutor.execute(() -> {
1871 try {
1872 if (mSlot != null) {
1873 mService.stopKeepalive(mNetwork, mSlot);
1874 }
1875 } catch (RemoteException e) {
1876 Log.e(TAG, "Error stopping packet keepalive: ", e);
1877 throw e.rethrowFromSystemServer();
1878 }
1879 });
1880 } catch (RejectedExecutionException e) {
1881 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001882 }
1883 }
1884
1885 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00001886 Preconditions.checkNotNull(network, "network cannot be null");
1887 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001888 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001889 mExecutor = Executors.newSingleThreadExecutor();
1890 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001891 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001892 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001893 final long token = Binder.clearCallingIdentity();
1894 try {
1895 mExecutor.execute(() -> {
1896 mSlot = slot;
1897 callback.onStarted();
1898 });
1899 } finally {
1900 Binder.restoreCallingIdentity(token);
1901 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001902 }
junyulai070f9ff2019-01-16 20:23:34 +08001903
1904 @Override
1905 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001906 final long token = Binder.clearCallingIdentity();
1907 try {
1908 mExecutor.execute(() -> {
1909 mSlot = null;
1910 callback.onStopped();
1911 });
1912 } finally {
1913 Binder.restoreCallingIdentity(token);
1914 }
junyulai070f9ff2019-01-16 20:23:34 +08001915 mExecutor.shutdown();
1916 }
1917
1918 @Override
1919 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001920 final long token = Binder.clearCallingIdentity();
1921 try {
1922 mExecutor.execute(() -> {
1923 mSlot = null;
1924 callback.onError(error);
1925 });
1926 } finally {
1927 Binder.restoreCallingIdentity(token);
1928 }
junyulai070f9ff2019-01-16 20:23:34 +08001929 mExecutor.shutdown();
1930 }
1931
1932 @Override
1933 public void onDataReceived() {
1934 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1935 // this callback when data is received.
1936 }
1937 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001938 }
1939 }
1940
1941 /**
1942 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1943 *
junyulai4c95b082018-12-27 17:25:29 +08001944 * @deprecated Use {@link #createSocketKeepalive} instead.
1945 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001946 * @hide
1947 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001948 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001949 public PacketKeepalive startNattKeepalive(
1950 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1951 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1952 final PacketKeepalive k = new PacketKeepalive(network, callback);
1953 try {
junyulai070f9ff2019-01-16 20:23:34 +08001954 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001955 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1956 } catch (RemoteException e) {
1957 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001958 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001959 }
1960 return k;
1961 }
1962
Chiachang Wang619319a2021-01-15 11:06:21 +08001963 // Construct an invalid fd.
1964 private ParcelFileDescriptor createInvalidFd() {
1965 final int invalidFd = -1;
1966 return ParcelFileDescriptor.adoptFd(invalidFd);
1967 }
1968
The Android Open Source Project28527d22009-03-03 19:31:44 -08001969 /**
junyulai4c95b082018-12-27 17:25:29 +08001970 * Request that keepalives be started on a IPsec NAT-T socket.
1971 *
1972 * @param network The {@link Network} the socket is on.
1973 * @param socket The socket that needs to be kept alive.
1974 * @param source The source address of the {@link UdpEncapsulationSocket}.
1975 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1976 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1977 * must run callback sequentially, otherwise the order of callbacks cannot be
1978 * guaranteed.
1979 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1980 * changes. Must be extended by applications that use this API.
1981 *
junyulai0835a1e2019-01-08 20:04:33 +08001982 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1983 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001984 **/
junyulai7e06ad42019-03-04 22:45:36 +08001985 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001986 @NonNull UdpEncapsulationSocket socket,
1987 @NonNull InetAddress source,
1988 @NonNull InetAddress destination,
1989 @NonNull @CallbackExecutor Executor executor,
1990 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001991 ParcelFileDescriptor dup;
1992 try {
junyulai828dad12019-03-27 11:00:37 +08001993 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1994 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001995 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1996 } catch (IOException ignored) {
1997 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1998 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001999 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002000 }
2001 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2002 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002003 }
2004
2005 /**
2006 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2007 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2008 *
2009 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002010 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2011 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2012 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002013 * @param source The source address of the {@link UdpEncapsulationSocket}.
2014 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2015 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2016 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2017 * must run callback sequentially, otherwise the order of callbacks cannot be
2018 * guaranteed.
2019 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2020 * changes. Must be extended by applications that use this API.
2021 *
junyulai0835a1e2019-01-08 20:04:33 +08002022 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2023 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002024 * @hide
2025 */
2026 @SystemApi
2027 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002028 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2029 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002030 @NonNull InetAddress source,
2031 @NonNull InetAddress destination,
2032 @NonNull @CallbackExecutor Executor executor,
2033 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002034 ParcelFileDescriptor dup;
2035 try {
junyulai828dad12019-03-27 11:00:37 +08002036 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002037 dup = pfd.dup();
2038 } catch (IOException ignored) {
2039 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2040 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002041 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002042 }
2043 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANce355502021-03-11 10:56:49 +00002044 -1 /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002045 }
2046
2047 /**
junyulai0835a1e2019-01-08 20:04:33 +08002048 * Request that keepalives be started on a TCP socket.
2049 * The socket must be established.
2050 *
2051 * @param network The {@link Network} the socket is on.
2052 * @param socket The socket that needs to be kept alive.
2053 * @param executor The executor on which callback will be invoked. This implementation assumes
2054 * the provided {@link Executor} runs the callbacks in sequence with no
2055 * concurrency. Failing this, no guarantee of correctness can be made. It is
2056 * the responsibility of the caller to ensure the executor provides this
2057 * guarantee. A simple way of creating such an executor is with the standard
2058 * tool {@code Executors.newSingleThreadExecutor}.
2059 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2060 * changes. Must be extended by applications that use this API.
2061 *
2062 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2063 * given socket.
2064 * @hide
2065 */
2066 @SystemApi
2067 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002068 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002069 @NonNull Socket socket,
2070 @NonNull Executor executor,
2071 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002072 ParcelFileDescriptor dup;
2073 try {
2074 dup = ParcelFileDescriptor.fromSocket(socket);
2075 } catch (UncheckedIOException ignored) {
2076 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2077 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002078 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002079 }
2080 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002081 }
2082
2083 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002084 * Ensure that a network route exists to deliver traffic to the specified
2085 * host via the specified network interface. An attempt to add a route that
2086 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002087 *
2088 * <p>This method requires the caller to hold either the
2089 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2090 * or the ability to modify system settings as determined by
2091 * {@link android.provider.Settings.System#canWrite}.</p>
2092 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002093 * @param networkType the type of the network over which traffic to the specified
2094 * host is to be routed
2095 * @param hostAddress the IP address of the host to which the route is desired
2096 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002097 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002098 * @deprecated Deprecated in favor of the
2099 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2100 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002101 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002102 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002103 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002104 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002105 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002106 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002107 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002108 }
2109
2110 /**
2111 * Ensure that a network route exists to deliver traffic to the specified
2112 * host via the specified network interface. An attempt to add a route that
2113 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002114 *
2115 * <p>This method requires the caller to hold either the
2116 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2117 * or the ability to modify system settings as determined by
2118 * {@link android.provider.Settings.System#canWrite}.</p>
2119 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002120 * @param networkType the type of the network over which traffic to the specified
2121 * host is to be routed
2122 * @param hostAddress the IP address of the host to which the route is desired
2123 * @return {@code true} on success, {@code false} on failure
2124 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002125 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002126 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002127 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002128 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002129 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002130 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002131 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002132 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002133 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2134 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002135 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002136 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 }
2138 }
2139
2140 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002141 * @return the context's attribution tag
2142 */
2143 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2144 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002145 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002146 }
2147
2148 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002149 * Returns the value of the setting for background data usage. If false,
2150 * applications should not use the network if the application is not in the
2151 * foreground. Developers should respect this setting, and check the value
2152 * of this before performing any background data operations.
2153 * <p>
2154 * All applications that have background services that use the network
2155 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002156 * <p>
Scott Main50589142011-10-06 18:32:43 -07002157 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002158 * background data depends on several combined factors, and this method will
2159 * always return {@code true}. Instead, when background data is unavailable,
2160 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002161 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002162 * @return Whether background data usage is allowed.
2163 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002164 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002165 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002166 // assume that background data is allowed; final authority is
2167 // NetworkInfo which may be blocked.
2168 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002169 }
2170
2171 /**
2172 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002173 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 * @param allowBackgroundData Whether an application should use data while
2175 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002176 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002177 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2178 * @see #getBackgroundDataSetting()
2179 * @hide
2180 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002181 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002182 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002183 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002184 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002185 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002186
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002187 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002188 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002189 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002190 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002191 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002192 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002193 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002194 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2195 if (tm != null) {
2196 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2197 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2198 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2199 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2200 + " retVal=" + retVal);
2201 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002202 }
Wink Saville689f7042014-12-05 11:10:30 -08002203 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002204 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002205 }
2206
The Android Open Source Project28527d22009-03-03 19:31:44 -08002207 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002208 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002209 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002210 */
2211 public interface OnNetworkActiveListener {
2212 /**
2213 * Called on the main thread of the process to report that the current data network
2214 * has become active, and it is now a good time to perform any pending network
2215 * operations. Note that this listener only tells you when the network becomes
2216 * active; if at any other time you want to know whether it is active (and thus okay
2217 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002218 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002219 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002220 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002221 }
2222
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002223 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002224 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002225
2226 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002227 * Start listening to reports when the system's default data network is active, meaning it is
2228 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2229 * to determine the current state of the system's default network after registering the
2230 * listener.
2231 * <p>
2232 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002233 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002234 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002235 *
2236 * @param l The listener to be told when the network is active.
2237 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002238 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002239 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2240 @Override
2241 public void onNetworkActive() throws RemoteException {
2242 l.onNetworkActive();
2243 }
2244 };
2245
2246 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002247 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002248 mNetworkActivityListeners.put(l, rl);
2249 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002250 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002251 }
2252 }
2253
2254 /**
2255 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002256 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002257 *
2258 * @param l Previously registered listener.
2259 */
Chalard Jean158702d2019-01-07 19:26:34 +09002260 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002261 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002262 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002263 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002264 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002265 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002266 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002267 }
2268 }
2269
2270 /**
2271 * Return whether the data network is currently active. An active network means that
2272 * it is currently in a high power state for performing data transmission. On some
2273 * types of networks, it may be expensive to move and stay in such a state, so it is
2274 * more power efficient to batch network traffic together when the radio is already in
2275 * this state. This method tells you whether right now is currently a good time to
2276 * initiate network traffic, as the network is already active.
2277 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002278 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002279 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002280 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002281 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002282 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002283 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002284 }
2285
2286 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002287 * {@hide}
2288 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002289 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002290 mContext = Preconditions.checkNotNull(context, "missing context");
2291 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002292 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002293 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002294 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002295
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002296 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002297 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002298 public static ConnectivityManager from(Context context) {
2299 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2300 }
2301
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002302 /** @hide */
2303 public NetworkRequest getDefaultRequest() {
2304 try {
2305 // This is not racy as the default request is final in ConnectivityService.
2306 return mService.getDefaultRequest();
2307 } catch (RemoteException e) {
2308 throw e.rethrowFromSystemServer();
2309 }
2310 }
2311
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002312 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002313 * Check if the package is a allowed to write settings. This also accounts that such an access
2314 * happened.
2315 *
2316 * @return {@code true} iff the package is allowed to write settings.
2317 */
2318 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2319 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2320 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2321 boolean throwException) {
2322 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2323 throwException);
2324 }
2325
2326 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002327 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2328 * situations where a Context pointer is unavailable.
2329 * @hide
2330 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002331 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002332 static ConnectivityManager getInstanceOrNull() {
2333 return sInstance;
2334 }
2335
2336 /**
2337 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2338 * situations where a Context pointer is unavailable.
2339 * @hide
2340 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002341 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002342 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002343 private static ConnectivityManager getInstance() {
2344 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002345 throw new IllegalStateException("No ConnectivityManager yet constructed");
2346 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002347 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002348 }
2349
2350 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002351 * Get the set of tetherable, available interfaces. This list is limited by
2352 * device configuration and current interface existence.
2353 *
2354 * @return an array of 0 or more Strings of tetherable interface names.
2355 *
markchien6ae63e52020-01-21 13:11:06 +08002356 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002357 * {@hide}
2358 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002359 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002360 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002361 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002362 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002363 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002364 }
2365
2366 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002367 * Get the set of tethered interfaces.
2368 *
2369 * @return an array of 0 or more String of currently tethered interface names.
2370 *
markchien6ae63e52020-01-21 13:11:06 +08002371 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002372 * {@hide}
2373 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002374 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002375 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002376 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002377 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002378 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002379 }
2380
2381 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002382 * Get the set of interface names which attempted to tether but
2383 * failed. Re-attempting to tether may cause them to reset to the Tethered
2384 * state. Alternatively, causing the interface to be destroyed and recreated
2385 * may cause them to reset to the available state.
2386 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2387 * information on the cause of the errors.
2388 *
2389 * @return an array of 0 or more String indicating the interface names
2390 * which failed to tether.
2391 *
markchien6ae63e52020-01-21 13:11:06 +08002392 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002393 * {@hide}
2394 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002395 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002396 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002397 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002398 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002399 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002400 }
2401
2402 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002403 * Get the set of tethered dhcp ranges.
2404 *
markchien2e6ba522020-02-14 11:55:48 +08002405 * @deprecated This method is not supported.
2406 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002407 * {@hide}
2408 */
paulhu8e96a752019-08-12 16:25:11 +08002409 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002410 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002411 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002412 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002413 }
2414
2415 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002416 * Attempt to tether the named interface. This will setup a dhcp server
2417 * on the interface, forward and NAT IP packets and forward DNS requests
2418 * to the best active upstream network interface. Note that if no upstream
2419 * IP network interface is available, dhcp will still run and traffic will be
2420 * allowed between the tethered devices and this device, though upstream net
2421 * access will of course fail until an upstream network interface becomes
2422 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002423 *
2424 * <p>This method requires the caller to hold either the
2425 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2426 * or the ability to modify system settings as determined by
2427 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002428 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002429 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2430 * and WifiStateMachine which need direct access. All other clients should use
2431 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2432 * logic.</p>
2433 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002434 * @param iface the interface name to tether.
2435 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002436 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002437 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002438 * {@hide}
2439 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002440 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002441 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002442 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002443 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002444 }
2445
2446 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002447 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002448 *
2449 * <p>This method requires the caller to hold either the
2450 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2451 * or the ability to modify system settings as determined by
2452 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002453 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002454 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2455 * and WifiStateMachine which need direct access. All other clients should use
2456 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2457 * logic.</p>
2458 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002459 * @param iface the interface name to untether.
2460 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2461 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002462 * {@hide}
2463 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002464 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002465 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002466 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002467 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002468 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002469
2470 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002471 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002472 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002473 * due to device configuration.
2474 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002475 * <p>If this app does not have permission to use this API, it will always
2476 * return false rather than throw an exception.</p>
2477 *
2478 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2479 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2480 *
2481 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2482 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2483 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002484 * @return a boolean - {@code true} indicating Tethering is supported.
2485 *
markchien6ae63e52020-01-21 13:11:06 +08002486 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002487 * {@hide}
2488 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002489 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002490 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2491 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002492 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002493 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002494 }
2495
2496 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002497 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002498 *
2499 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002500 * @hide
2501 */
2502 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002503 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002504 public static abstract class OnStartTetheringCallback {
2505 /**
2506 * Called when tethering has been successfully started.
2507 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002508 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002509
2510 /**
2511 * Called when starting tethering failed.
2512 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002513 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002514 }
2515
2516 /**
2517 * Convenient overload for
2518 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2519 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002520 *
2521 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002522 * @hide
2523 */
2524 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002525 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002526 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002527 public void startTethering(int type, boolean showProvisioningUi,
2528 final OnStartTetheringCallback callback) {
2529 startTethering(type, showProvisioningUi, callback, null);
2530 }
2531
2532 /**
2533 * Runs tether provisioning for the given type if needed and then starts tethering if
2534 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2535 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2536 * schedules tether provisioning re-checks if appropriate.
2537 *
2538 * @param type The type of tethering to start. Must be one of
2539 * {@link ConnectivityManager.TETHERING_WIFI},
2540 * {@link ConnectivityManager.TETHERING_USB}, or
2541 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2542 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2543 * is one. This should be true the first time this function is called and also any time
2544 * the user can see this UI. It gives users information from their carrier about the
2545 * check failing and how they can sign up for tethering if possible.
2546 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2547 * of the result of trying to tether.
2548 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002549 *
2550 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002551 * @hide
2552 */
2553 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002554 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002555 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002556 public void startTethering(int type, boolean showProvisioningUi,
2557 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002558 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002559
markchien91c78e52020-01-20 19:31:56 +08002560 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002561 @Override
markchien91c78e52020-01-20 19:31:56 +08002562 public void execute(Runnable command) {
2563 if (handler == null) {
2564 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002565 } else {
markchien91c78e52020-01-20 19:31:56 +08002566 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002567 }
2568 }
2569 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002570
markchien91c78e52020-01-20 19:31:56 +08002571 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2572 @Override
2573 public void onTetheringStarted() {
2574 callback.onTetheringStarted();
2575 }
2576
2577 @Override
markchienf47d8342020-03-19 13:37:43 +08002578 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002579 callback.onTetheringFailed();
2580 }
2581 };
2582
2583 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002584 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002585
Amos Bianchia9b415a2020-03-04 11:07:38 -08002586 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002587 }
2588
2589 /**
2590 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2591 * applicable.
2592 *
2593 * @param type The type of tethering to stop. Must be one of
2594 * {@link ConnectivityManager.TETHERING_WIFI},
2595 * {@link ConnectivityManager.TETHERING_USB}, or
2596 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002597 *
2598 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002599 * @hide
2600 */
2601 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002602 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002603 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002604 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002605 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002606 }
2607
2608 /**
markchien4ef53e82019-02-27 14:56:11 +08002609 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2610 * upstream status.
2611 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002612 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002613 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002614 */
2615 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002616 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002617 public abstract static class OnTetheringEventCallback {
2618
2619 /**
2620 * Called when tethering upstream changed. This can be called multiple times and can be
2621 * called any time.
2622 *
2623 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2624 * have any upstream.
2625 */
2626 public void onUpstreamChanged(@Nullable Network network) {}
2627 }
2628
markchien6ae63e52020-01-21 13:11:06 +08002629 @GuardedBy("mTetheringEventCallbacks")
2630 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2631 mTetheringEventCallbacks = new ArrayMap<>();
2632
markchien4ef53e82019-02-27 14:56:11 +08002633 /**
2634 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002635 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002636 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2637 * with a null argument. The same callback object cannot be registered twice.
2638 *
2639 * @param executor the executor on which callback will be invoked.
2640 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002641 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002642 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002643 * @hide
2644 */
2645 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002646 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002647 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2648 public void registerTetheringEventCallback(
2649 @NonNull @CallbackExecutor Executor executor,
2650 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002651 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
markchien4ef53e82019-02-27 14:56:11 +08002652
markchien6ae63e52020-01-21 13:11:06 +08002653 final TetheringEventCallback tetherCallback =
2654 new TetheringEventCallback() {
2655 @Override
2656 public void onUpstreamChanged(@Nullable Network network) {
2657 callback.onUpstreamChanged(network);
2658 }
2659 };
2660
2661 synchronized (mTetheringEventCallbacks) {
2662 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002663 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002664 }
markchien4ef53e82019-02-27 14:56:11 +08002665 }
2666
2667 /**
2668 * Remove tethering event callback previously registered with
2669 * {@link #registerTetheringEventCallback}.
2670 *
2671 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002672 *
2673 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002674 * @hide
2675 */
2676 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002677 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002678 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2679 public void unregisterTetheringEventCallback(
2680 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002681 Objects.requireNonNull(callback, "The callback must be non-null");
2682 synchronized (mTetheringEventCallbacks) {
2683 final TetheringEventCallback tetherCallback =
2684 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002685 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002686 }
markchien4ef53e82019-02-27 14:56:11 +08002687 }
2688
2689
2690 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002691 * Get the list of regular expressions that define any tetherable
2692 * USB network interfaces. If USB tethering is not supported by the
2693 * device, this list should be empty.
2694 *
2695 * @return an array of 0 or more regular expression Strings defining
2696 * what interfaces are considered tetherable usb interfaces.
2697 *
markchien6ae63e52020-01-21 13:11:06 +08002698 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002699 * {@hide}
2700 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002701 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002702 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002703 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002704 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002705 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002706 }
2707
2708 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002709 * Get the list of regular expressions that define any tetherable
2710 * Wifi network interfaces. If Wifi tethering is not supported by the
2711 * device, this list should be empty.
2712 *
2713 * @return an array of 0 or more regular expression Strings defining
2714 * what interfaces are considered tetherable wifi interfaces.
2715 *
markchien6ae63e52020-01-21 13:11:06 +08002716 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002717 * {@hide}
2718 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002719 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002720 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002721 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002722 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002723 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002724 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002725
Danica Chang96567052010-08-11 14:54:43 -07002726 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002727 * Get the list of regular expressions that define any tetherable
2728 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2729 * device, this list should be empty.
2730 *
2731 * @return an array of 0 or more regular expression Strings defining
2732 * what interfaces are considered tetherable bluetooth interfaces.
2733 *
markchien6ae63e52020-01-21 13:11:06 +08002734 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2735 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002736 * {@hide}
2737 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002738 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002739 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002740 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002741 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002742 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002743 }
2744
Mike Lockwooded4a1742011-07-19 13:04:47 -07002745 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002746 * Attempt to both alter the mode of USB and Tethering of USB. A
2747 * utility method to deal with some of the complexity of USB - will
2748 * attempt to switch to Rndis and subsequently tether the resulting
2749 * interface on {@code true} or turn off tethering and switch off
2750 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002751 *
2752 * <p>This method requires the caller to hold either the
2753 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2754 * or the ability to modify system settings as determined by
2755 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002756 *
2757 * @param enable a boolean - {@code true} to enable tethering
2758 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002759 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002760 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002761 * {@hide}
2762 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002763 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002764 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002765 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002766 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002767 }
2768
markchien6ae63e52020-01-21 13:11:06 +08002769 /**
2770 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2771 * {@hide}
2772 */
markchien0f45bb92019-01-16 17:44:13 +08002773 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002774 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002775 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002776 /**
2777 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2778 * {@hide}
2779 */
2780 @Deprecated
2781 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2782 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2783 /**
2784 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2785 * {@hide}
2786 */
2787 @Deprecated
2788 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2789 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2790 /**
2791 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2792 * {@hide}
2793 */
2794 @Deprecated
2795 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2796 /**
2797 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2798 * {@hide}
2799 */
2800 @Deprecated
2801 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2802 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2803 /**
markchienf47d8342020-03-19 13:37:43 +08002804 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002805 * {@hide}
2806 */
2807 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002808 public static final int TETHER_ERROR_MASTER_ERROR =
2809 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002810 /**
2811 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2812 * {@hide}
2813 */
2814 @Deprecated
2815 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2816 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2817 /**
2818 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2819 * {@hide}
2820 */
2821 @Deprecated
2822 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2823 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2824 /**
markchienf47d8342020-03-19 13:37:43 +08002825 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002826 * {@hide}
2827 */
2828 @Deprecated
2829 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002830 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002831 /**
markchienf47d8342020-03-19 13:37:43 +08002832 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002833 * {@hide}
2834 */
2835 @Deprecated
2836 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002837 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002838 /**
2839 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2840 * {@hide}
2841 */
2842 @Deprecated
2843 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2844 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2845 /**
markchienf47d8342020-03-19 13:37:43 +08002846 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002847 * {@hide}
2848 */
markchien0f45bb92019-01-16 17:44:13 +08002849 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002850 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002851 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002852 /**
2853 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2854 * {@hide}
2855 */
2856 @Deprecated
2857 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2858 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2859 /**
2860 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2861 * {@hide}
2862 */
markchien0f45bb92019-01-16 17:44:13 +08002863 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002864 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002865 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002866
2867 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002868 * Get a more detailed error code after a Tethering or Untethering
2869 * request asynchronously failed.
2870 *
2871 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002872 * @return error The error code of the last error tethering or untethering the named
2873 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002874 *
markchien6ae63e52020-01-21 13:11:06 +08002875 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002876 * {@hide}
2877 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002878 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002879 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002880 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002881 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002882 int error = mTetheringManager.getLastTetherError(iface);
2883 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2884 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2885 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2886 // instead.
2887 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2888 }
2889 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002890 }
2891
markchienbf5ab012019-03-06 16:25:00 +08002892 /** @hide */
2893 @Retention(RetentionPolicy.SOURCE)
2894 @IntDef(value = {
2895 TETHER_ERROR_NO_ERROR,
2896 TETHER_ERROR_PROVISION_FAILED,
2897 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2898 })
2899 public @interface EntitlementResultCode {
2900 }
2901
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002902 /**
markchienbf5ab012019-03-06 16:25:00 +08002903 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002904 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002905 *
2906 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002907 * @hide
2908 */
2909 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002910 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002911 public interface OnTetheringEntitlementResultListener {
2912 /**
2913 * Called to notify entitlement result.
2914 *
2915 * @param resultCode an int value of entitlement result. It may be one of
2916 * {@link #TETHER_ERROR_NO_ERROR},
2917 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2918 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2919 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002920 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002921 }
2922
2923 /**
markchien0f45bb92019-01-16 17:44:13 +08002924 * Get the last value of the entitlement check on this downstream. If the cached value is
2925 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2926 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2927 * guaranteed that the UI-based entitlement check will complete in any specific time period
2928 * and may in fact never complete. Any successful entitlement check the platform performs for
2929 * any reason will update the cached value.
2930 *
2931 * @param type the downstream type of tethering. Must be one of
2932 * {@link #TETHERING_WIFI},
2933 * {@link #TETHERING_USB}, or
2934 * {@link #TETHERING_BLUETOOTH}.
2935 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002936 * @param executor the executor on which callback will be invoked.
2937 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2938 * notify the caller of the result of entitlement check. The listener may be called zero
2939 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002940 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002941 * {@hide}
2942 */
2943 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002944 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002945 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002946 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2947 @NonNull @CallbackExecutor Executor executor,
2948 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00002949 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchienbf5ab012019-03-06 16:25:00 +08002950 ResultReceiver wrappedListener = new ResultReceiver(null) {
2951 @Override
2952 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08002953 final long token = Binder.clearCallingIdentity();
2954 try {
2955 executor.execute(() -> {
2956 listener.onTetheringEntitlementResult(resultCode);
2957 });
2958 } finally {
2959 Binder.restoreCallingIdentity(token);
2960 }
markchienbf5ab012019-03-06 16:25:00 +08002961 }
2962 };
2963
Amos Bianchia9b415a2020-03-04 11:07:38 -08002964 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002965 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002966 }
2967
2968 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002969 * Report network connectivity status. This is currently used only
2970 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002971 * <p>This method requires the caller to hold the permission
2972 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002973 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002974 * @param networkType The type of network you want to report on
2975 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002976 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002977 * {@hide}
2978 */
2979 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002980 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002981 try {
2982 mService.reportInetCondition(networkType, percentage);
2983 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002984 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002985 }
2986 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002987
2988 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002989 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07002990 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002991 * the framework to re-evaluate network connectivity and/or switch to another
2992 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002993 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002994 * @param network The {@link Network} the application was attempting to use
2995 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04002996 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2997 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002998 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002999 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003000 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003001 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003002 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003003 // One of these will be ignored because it matches system's current state.
3004 // The other will trigger the necessary reevaluation.
3005 mService.reportNetworkConnectivity(network, true);
3006 mService.reportNetworkConnectivity(network, false);
3007 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003008 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003009 }
3010 }
3011
3012 /**
3013 * Report to the framework whether a network has working connectivity.
3014 * This provides a hint to the system that a particular network is providing
3015 * working connectivity or not. In response the framework may re-evaluate
3016 * the network's connectivity and might take further action thereafter.
3017 *
3018 * @param network The {@link Network} the application was attempting to use
3019 * or {@code null} to indicate the current default network.
3020 * @param hasConnectivity {@code true} if the application was able to successfully access the
3021 * Internet using {@code network} or {@code false} if not.
3022 */
Chalard Jean158702d2019-01-07 19:26:34 +09003023 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003024 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003025 try {
3026 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003027 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003028 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003029 }
3030 }
3031
3032 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003033 * Set a network-independent global http proxy. This is not normally what you want
3034 * for typical HTTP proxies - they are general network dependent. However if you're
3035 * doing something unusual like general internal filtering this may be useful. On
3036 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003037 *
3038 * @param p A {@link ProxyInfo} object defining the new global
3039 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003040 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003041 */
paulhu8e96a752019-08-12 16:25:11 +08003042 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04003043 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003044 try {
3045 mService.setGlobalProxy(p);
3046 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003047 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003048 }
3049 }
3050
3051 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003052 * Retrieve any network-independent global HTTP proxy.
3053 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003054 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003055 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003056 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003057 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003058 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003059 try {
3060 return mService.getGlobalProxy();
3061 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003062 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003063 }
3064 }
3065
3066 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003067 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3068 * network-specific HTTP proxy. If {@code network} is null, the
3069 * network-specific proxy returned is the proxy of the default active
3070 * network.
3071 *
3072 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3073 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3074 * or when {@code network} is {@code null},
3075 * the {@code ProxyInfo} for the default active network. Returns
3076 * {@code null} when no proxy applies or the caller doesn't have
3077 * permission to use {@code network}.
3078 * @hide
3079 */
3080 public ProxyInfo getProxyForNetwork(Network network) {
3081 try {
3082 return mService.getProxyForNetwork(network);
3083 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003084 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003085 }
3086 }
3087
3088 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003089 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3090 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003091 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003092 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003093 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003094 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003095 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003096 */
Chalard Jean158702d2019-01-07 19:26:34 +09003097 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003098 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003099 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003100 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003101
3102 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003103 * Returns true if the hardware supports the given network type
3104 * else it returns false. This doesn't indicate we have coverage
3105 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003106 * hardware supports it. For example a GSM phone without a SIM
3107 * should still return {@code true} for mobile data, but a wifi only
3108 * tablet would return {@code false}.
3109 *
3110 * @param networkType The network type we'd like to check
3111 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003112 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003113 * @hide
3114 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003115 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003116 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003117 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003118 public boolean isNetworkSupported(int networkType) {
3119 try {
3120 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003121 } catch (RemoteException e) {
3122 throw e.rethrowFromSystemServer();
3123 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003124 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003125
3126 /**
3127 * Returns if the currently active data network is metered. A network is
3128 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003129 * that connection due to monetary costs, data limitations or
3130 * battery/performance issues. You should check this before doing large
3131 * data transfers, and warn the user or delay the operation until another
3132 * network is available.
3133 *
3134 * @return {@code true} if large transfers should be avoided, otherwise
3135 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003136 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003137 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003138 public boolean isActiveNetworkMetered() {
3139 try {
3140 return mService.isActiveNetworkMetered();
3141 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003142 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003143 }
3144 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003145
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003146 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003147 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003148 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003149 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003150 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003151 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003152 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003153 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003154 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003155 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003156 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003157 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003158 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003159 }
3160 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003161
3162 /**
3163 * Set the value for enabling/disabling airplane mode
3164 *
3165 * @param enable whether to enable airplane mode or not
3166 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003167 * @hide
3168 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003169 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003170 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003171 android.Manifest.permission.NETWORK_SETTINGS,
3172 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3173 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003174 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003175 public void setAirplaneMode(boolean enable) {
3176 try {
3177 mService.setAirplaneMode(enable);
3178 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003179 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003180 }
3181 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003182
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003183 /**
3184 * Registers the specified {@link NetworkProvider}.
3185 * Each listener must only be registered once. The listener can be unregistered with
3186 * {@link #unregisterNetworkProvider}.
3187 *
3188 * @param provider the provider to register
3189 * @return the ID of the provider. This ID must be used by the provider when registering
3190 * {@link android.net.NetworkAgent}s.
3191 * @hide
3192 */
3193 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003194 @RequiresPermission(anyOf = {
3195 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3196 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003197 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3198 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003199 throw new IllegalStateException("NetworkProviders can only be registered once");
3200 }
3201
3202 try {
3203 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3204 provider.getName());
3205 provider.setProviderId(providerId);
3206 } catch (RemoteException e) {
3207 throw e.rethrowFromSystemServer();
3208 }
3209 return provider.getProviderId();
3210 }
3211
3212 /**
3213 * Unregisters the specified NetworkProvider.
3214 *
3215 * @param provider the provider to unregister
3216 * @hide
3217 */
3218 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003219 @RequiresPermission(anyOf = {
3220 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3221 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003222 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3223 try {
3224 mService.unregisterNetworkProvider(provider.getMessenger());
3225 } catch (RemoteException e) {
3226 throw e.rethrowFromSystemServer();
3227 }
3228 provider.setProviderId(NetworkProvider.ID_NONE);
3229 }
3230
3231
3232 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003233 @RequiresPermission(anyOf = {
3234 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3235 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003236 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3237 try {
3238 mService.declareNetworkRequestUnfulfillable(request);
3239 } catch (RemoteException e) {
3240 throw e.rethrowFromSystemServer();
3241 }
3242 }
3243
Paul Jensen1f567382015-02-13 14:18:39 -05003244 /**
3245 * @hide
3246 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003247 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003248 */
paulhub6ba8e82020-03-04 09:43:41 +08003249 @RequiresPermission(anyOf = {
3250 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3251 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003252 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jean28018572020-12-21 18:36:52 +09003253 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3254 int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003255 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003256 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003257 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003258 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003259 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003260 }
3261
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003262 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003263 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3264 * changes. Should be extended by applications wanting notifications.
3265 *
3266 * A {@code NetworkCallback} is registered by calling
3267 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3268 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003269 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003270 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3271 * A {@code NetworkCallback} should be registered at most once at any time.
3272 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003273 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003274 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003275 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003276 * No flags associated with this callback.
3277 * @hide
3278 */
3279 public static final int FLAG_NONE = 0;
3280 /**
3281 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3282 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3283 * <p>
3284 * These include:
3285 * <li> Some transport info instances (retrieved via
3286 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3287 * contain location sensitive information.
3288 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3289 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3290 * </p>
3291 * <p>
3292 * Note:
3293 * <li> Retrieving this location sensitive information (subject to app's location
3294 * permissions) will be noted by system. </li>
3295 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3296 * not include location sensitive info.
3297 * </p>
3298 */
3299 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3300
3301 /** @hide */
3302 @Retention(RetentionPolicy.SOURCE)
3303 @IntDef(flag = true, prefix = "FLAG_", value = {
3304 FLAG_NONE,
3305 FLAG_INCLUDE_LOCATION_INFO
3306 })
3307 public @interface Flag { }
3308
3309 /**
3310 * All the valid flags for error checking.
3311 */
3312 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3313
3314 public NetworkCallback() {
3315 this(FLAG_NONE);
3316 }
3317
3318 public NetworkCallback(@Flag int flags) {
3319 Preconditions.checkArgument((flags & VALID_FLAGS) == flags);
3320 mFlags = flags;
3321 }
3322
3323 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003324 * Called when the framework connects to a new network to evaluate whether it satisfies this
3325 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3326 * callback. There is no guarantee that this new network will satisfy any requests, or that
3327 * the network will stay connected for longer than the time necessary to evaluate it.
3328 * <p>
3329 * Most applications <b>should not</b> act on this callback, and should instead use
3330 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3331 * the framework in properly evaluating the network &mdash; for example, an application that
3332 * can automatically log in to a captive portal without user intervention.
3333 *
3334 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003335 *
3336 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003337 */
paulhu1a407652019-03-22 16:35:06 +08003338 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003339
3340 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003341 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003342 * This callback may be called more than once if the {@link Network} that is
3343 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003344 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003345 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003346 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3347 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003348 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003349 * @hide
3350 */
paulhu1a407652019-03-22 16:35:06 +08003351 public void onAvailable(@NonNull Network network,
3352 @NonNull NetworkCapabilities networkCapabilities,
3353 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003354 // Internally only this method is called when a new network is available, and
3355 // it calls the callback in the same way and order that older versions used
3356 // to call so as not to change the behavior.
3357 onAvailable(network);
3358 if (!networkCapabilities.hasCapability(
3359 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3360 onNetworkSuspended(network);
3361 }
3362 onCapabilitiesChanged(network, networkCapabilities);
3363 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003364 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003365 }
3366
3367 /**
3368 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003369 *
3370 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3371 * be available at the same time, and onAvailable will be called for each of these as they
3372 * appear.
3373 *
3374 * <p>For callbacks registered with {@link #requestNetwork} and
3375 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3376 * is the new best network for this request and is now tracked by this callback ; this
3377 * callback will no longer receive method calls about other networks that may have been
3378 * passed to this method previously. The previously-best network may have disconnected, or
3379 * it may still be around and the newly-best network may simply be better.
3380 *
3381 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3382 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3383 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3384 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3385 *
3386 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3387 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3388 * this callback as this is prone to race conditions (there is no guarantee the objects
3389 * returned by these methods will be current). Instead, wait for a call to
3390 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3391 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3392 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003393 *
3394 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003395 */
paulhu1a407652019-03-22 16:35:06 +08003396 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003397
3398 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003399 * Called when the network is about to be lost, typically because there are no outstanding
3400 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3401 * with the new replacement network for graceful handover. This method is not guaranteed
3402 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3403 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003404 *
Chalard Jean01378b62019-08-30 16:27:28 +09003405 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3406 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3407 * this callback as this is prone to race conditions ; calling these methods while in a
3408 * callback may return an outdated or even a null object.
3409 *
3410 * @param network The {@link Network} that is about to be lost.
3411 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3412 * connected for graceful handover; note that the network may still
3413 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003414 */
paulhu1a407652019-03-22 16:35:06 +08003415 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003416
3417 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003418 * Called when a network disconnects or otherwise no longer satisfies this request or
3419 * callback.
3420 *
3421 * <p>If the callback was registered with requestNetwork() or
3422 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3423 * returned by onAvailable() when that network is lost and no other network satisfies
3424 * the criteria of the request.
3425 *
3426 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3427 * each network which no longer satisfies the criteria of the callback.
3428 *
3429 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3430 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3431 * this callback as this is prone to race conditions ; calling these methods while in a
3432 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003433 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003434 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003435 */
paulhu1a407652019-03-22 16:35:06 +08003436 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003437
3438 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003439 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003440 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3441 * requested network request cannot be fulfilled (whether or not a timeout was
3442 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003443 * {@link NetworkRequest} will have already been removed and released, as if
3444 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003445 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003446 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003447
3448 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003449 * Called when the network corresponding to this request changes capabilities but still
3450 * satisfies the requested criteria.
3451 *
3452 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3453 * to be called immediately after {@link #onAvailable}.
3454 *
3455 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3456 * ConnectivityManager methods in this callback as this is prone to race conditions :
3457 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003458 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003459 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius951c0032020-12-22 15:10:42 -08003460 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003461 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003462 */
paulhu1a407652019-03-22 16:35:06 +08003463 public void onCapabilitiesChanged(@NonNull Network network,
3464 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003465
3466 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003467 * Called when the network corresponding to this request changes {@link LinkProperties}.
3468 *
3469 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3470 * to be called immediately after {@link #onAvailable}.
3471 *
3472 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3473 * ConnectivityManager methods in this callback as this is prone to race conditions :
3474 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003475 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003476 * @param network The {@link Network} whose link properties have changed.
3477 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003478 */
paulhu1a407652019-03-22 16:35:06 +08003479 public void onLinkPropertiesChanged(@NonNull Network network,
3480 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003481
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003482 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003483 * Called when the network the framework connected to for this request suspends data
3484 * transmission temporarily.
3485 *
3486 * <p>This generally means that while the TCP connections are still live temporarily
3487 * network data fails to transfer. To give a specific example, this is used on cellular
3488 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3489 * means read operations on sockets on this network will block once the buffers are
3490 * drained, and write operations will block once the buffers are full.
3491 *
3492 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3493 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3494 * this callback as this is prone to race conditions (there is no guarantee the objects
3495 * returned by these methods will be current).
3496 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003497 * @hide
3498 */
paulhu1a407652019-03-22 16:35:06 +08003499 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003500
3501 /**
3502 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003503 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3504 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003505
3506 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3507 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3508 * this callback as this is prone to race conditions : calling these methods while in a
3509 * callback may return an outdated or even a null object.
3510 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003511 * @hide
3512 */
paulhu1a407652019-03-22 16:35:06 +08003513 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003514
junyulaif2c67e42018-08-07 19:50:45 +08003515 /**
3516 * Called when access to the specified network is blocked or unblocked.
3517 *
Chalard Jean01378b62019-08-30 16:27:28 +09003518 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3519 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3520 * this callback as this is prone to race conditions : calling these methods while in a
3521 * callback may return an outdated or even a null object.
3522 *
junyulaif2c67e42018-08-07 19:50:45 +08003523 * @param network The {@link Network} whose blocked status has changed.
3524 * @param blocked The blocked status of this {@link Network}.
3525 */
junyulai7e06ad42019-03-04 22:45:36 +08003526 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003527
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003528 private NetworkRequest networkRequest;
Roshan Pius951c0032020-12-22 15:10:42 -08003529 private final int mFlags;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003530 }
3531
Hugo Benichia590ab82017-05-11 13:16:17 +09003532 /**
3533 * Constant error codes used by ConnectivityService to communicate about failures and errors
3534 * across a Binder boundary.
3535 * @hide
3536 */
3537 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003538 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003539 }
3540
3541 /** @hide */
3542 public static class TooManyRequestsException extends RuntimeException {}
3543
3544 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3545 switch (e.errorCode) {
3546 case Errors.TOO_MANY_REQUESTS:
3547 return new TooManyRequestsException();
3548 default:
3549 Log.w(TAG, "Unknown service error code " + e.errorCode);
3550 return new RuntimeException(e);
3551 }
3552 }
3553
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003554 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003555 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003556 public static final int CALLBACK_PRECHECK = BASE + 1;
3557 /** @hide */
3558 public static final int CALLBACK_AVAILABLE = BASE + 2;
3559 /** @hide arg1 = TTL */
3560 public static final int CALLBACK_LOSING = BASE + 3;
3561 /** @hide */
3562 public static final int CALLBACK_LOST = BASE + 4;
3563 /** @hide */
3564 public static final int CALLBACK_UNAVAIL = BASE + 5;
3565 /** @hide */
3566 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3567 /** @hide */
3568 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003569 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003570 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003571 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003572 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003573 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003574 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003575 /** @hide */
3576 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003577
Erik Kline155a59a2015-11-25 12:49:38 +09003578 /** @hide */
3579 public static String getCallbackName(int whichCallback) {
3580 switch (whichCallback) {
3581 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3582 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3583 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3584 case CALLBACK_LOST: return "CALLBACK_LOST";
3585 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3586 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3587 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003588 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3589 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3590 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003591 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003592 default:
3593 return Integer.toString(whichCallback);
3594 }
3595 }
3596
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003597 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003598 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003599 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003600
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003601 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003602 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003603 }
3604
Hugo Benichifd44e912017-02-02 17:02:36 +09003605 CallbackHandler(Handler handler) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00003606 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003607 }
3608
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003609 @Override
3610 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003611 if (message.what == EXPIRE_LEGACY_REQUEST) {
3612 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3613 return;
3614 }
3615
3616 final NetworkRequest request = getObject(message, NetworkRequest.class);
3617 final Network network = getObject(message, Network.class);
3618 final NetworkCallback callback;
3619 synchronized (sCallbacks) {
3620 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003621 if (callback == null) {
3622 Log.w(TAG,
3623 "callback not found for " + getCallbackName(message.what) + " message");
3624 return;
3625 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003626 if (message.what == CALLBACK_UNAVAIL) {
3627 sCallbacks.remove(request);
3628 callback.networkRequest = ALREADY_UNREGISTERED;
3629 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003630 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003631 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003632 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003633 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003634
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003635 switch (message.what) {
3636 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003637 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003638 break;
3639 }
3640 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003641 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3642 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003643 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003644 break;
3645 }
3646 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003647 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003648 break;
3649 }
3650 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003651 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003652 break;
3653 }
3654 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003655 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003656 break;
3657 }
3658 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003659 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3660 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003661 break;
3662 }
3663 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003664 LinkProperties lp = getObject(message, LinkProperties.class);
3665 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003666 break;
3667 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003668 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003669 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003670 break;
3671 }
3672 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003673 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003674 break;
3675 }
junyulaif2c67e42018-08-07 19:50:45 +08003676 case CALLBACK_BLK_CHANGED: {
3677 boolean blocked = message.arg1 != 0;
3678 callback.onBlockedStatusChanged(network, blocked);
3679 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003680 }
3681 }
3682
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003683 private <T> T getObject(Message msg, Class<T> c) {
3684 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003685 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003686 }
3687
Hugo Benichifd44e912017-02-02 17:02:36 +09003688 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003689 synchronized (sCallbacks) {
3690 if (sCallbackHandler == null) {
3691 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003692 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003693 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003694 }
3695 }
3696
Hugo Benichibc4ac972017-02-03 14:18:44 +09003697 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3698 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003699
Hugo Benichibc4ac972017-02-03 14:18:44 +09003700 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003701 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003702 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003703 checkCallbackNotNull(callback);
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00003704 Preconditions.checkArgument(
3705 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3706 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003707 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003708 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003709 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003710 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003711 if (callback.networkRequest != null
3712 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003713 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3714 // and requests (http://b/20701525).
3715 Log.e(TAG, "NetworkCallback was already registered");
3716 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003717 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003718 Binder binder = new Binder();
Roshan Pius951c0032020-12-22 15:10:42 -08003719 final int callbackFlags = callback.mFlags;
junyulaiad010792021-01-11 16:53:38 +08003720 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003721 request = mService.listenForNetwork(
Roshan Pius951c0032020-12-22 15:10:42 -08003722 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003723 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003724 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003725 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003726 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
Roshan Pius951c0032020-12-22 15:10:42 -08003727 callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003728 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003729 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003730 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003731 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003732 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003733 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003734 } catch (RemoteException e) {
3735 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003736 } catch (ServiceSpecificException e) {
3737 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003738 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003739 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003740 }
3741
3742 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003743 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003744 *
markchienfac84a22020-03-18 21:16:15 +08003745 * This API is only for use in internal system code that requests networks with legacy type and
3746 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003747 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003748 *
markchiend6eeffd2020-01-14 00:55:21 +08003749 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003750 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3751 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3752 * be a positive value (i.e. >0).
3753 * @param legacyType to specify the network type(#TYPE_*).
3754 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003755 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3756 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003757 *
3758 * @hide
3759 */
markchiend6eeffd2020-01-14 00:55:21 +08003760 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003761 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003762 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003763 int timeoutMs, int legacyType, @NonNull Handler handler,
3764 @NonNull NetworkCallback networkCallback) {
3765 if (legacyType == TYPE_NONE) {
3766 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3767 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003768 CallbackHandler cbHandler = new CallbackHandler(handler);
3769 NetworkCapabilities nc = request.networkCapabilities;
3770 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003771 }
3772
3773 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003774 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003775 *
Chalard Jean01378b62019-08-30 16:27:28 +09003776 * <p>This method will attempt to find the best network that matches the passed
3777 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3778 * criteria. The platform will evaluate which network is the best at its own discretion.
3779 * Throughput, latency, cost per byte, policy, user preference and other considerations
3780 * may be factored in the decision of what is considered the best network.
3781 *
3782 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3783 * matching this request, while always attempting to match the request to a better network if
3784 * possible. If a better match is found, the platform will switch this request to the now-best
3785 * network and inform the app of the newly best network by invoking
3786 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3787 * will not try to maintain any other network than the best one currently matching the request:
3788 * a network not matching any network request may be disconnected at any time.
3789 *
3790 * <p>For example, an application could use this method to obtain a connected cellular network
3791 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3792 * radio to consume additional power. Or, an application could inform the system that it wants
3793 * a network supporting sending MMSes and have the system let it know about the currently best
3794 * MMS-supporting network through the provided {@link NetworkCallback}.
3795 *
3796 * <p>The status of the request can be followed by listening to the various callbacks described
3797 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3798 * used to direct traffic to the network (although accessing some networks may be subject to
3799 * holding specific permissions). Callers will learn about the specific characteristics of the
3800 * network through
3801 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3802 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3803 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3804 * matching the request at any given time; therefore when a better network matching the request
3805 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3806 * with the new network after which no further updates are given about the previously-best
3807 * network, unless it becomes the best again at some later time. All callbacks are invoked
3808 * in order on the same thread, which by default is a thread created by the framework running
3809 * in the app.
3810 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3811 * callbacks are invoked.
3812 *
3813 * <p>This{@link NetworkRequest} will live until released via
3814 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3815 * which point the system may let go of the network at any time.
3816 *
3817 * <p>A version of this method which takes a timeout is
3818 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3819 * wait for a limited amount of time for the network to become unavailable.
3820 *
Paul Jensenee52d232015-06-16 15:11:58 -04003821 * <p>It is presently unsupported to request a network with mutable
3822 * {@link NetworkCapabilities} such as
3823 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3824 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3825 * as these {@code NetworkCapabilities} represent states that a particular
3826 * network may never attain, and whether a network will attain these states
3827 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003828 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003829 *
3830 * <p>This method requires the caller to hold either the
3831 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3832 * or the ability to modify system settings as determined by
3833 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003834 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003835 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3836 * number of outstanding requests to 100 per app (identified by their UID), shared with
3837 * all variants of this method, of {@link #registerNetworkCallback} as well as
3838 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3839 * Requesting a network with this method will count toward this limit. If this limit is
3840 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3841 * make sure to unregister the callbacks with
3842 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3843 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003844 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003845 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3846 * the callback must not be shared - it uniquely specifies this request.
3847 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003848 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3849 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003850 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003851 */
Chalard Jean158702d2019-01-07 19:26:34 +09003852 public void requestNetwork(@NonNull NetworkRequest request,
3853 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003854 requestNetwork(request, networkCallback, getDefaultHandler());
3855 }
3856
3857 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003858 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichifd44e912017-02-02 17:02:36 +09003859 *
Chalard Jean01378b62019-08-30 16:27:28 +09003860 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3861 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003862 *
Chalard Jean01378b62019-08-30 16:27:28 +09003863 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003864 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3865 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003866 *
3867 * @param request {@link NetworkRequest} describing this request.
3868 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3869 * the callback must not be shared - it uniquely specifies this request.
3870 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003871 */
Chalard Jean158702d2019-01-07 19:26:34 +09003872 public void requestNetwork(@NonNull NetworkRequest request,
3873 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003874 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003875 NetworkCapabilities nc = request.networkCapabilities;
3876 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003877 }
3878
3879 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003880 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohenf67bde92017-03-01 12:47:28 -08003881 * by a timeout.
3882 *
3883 * This function behaves identically to the non-timed-out version
3884 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3885 * is not found within the given time (in milliseconds) the
3886 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3887 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3888 * not have to be released if timed-out (it is automatically released). Unregistering a
3889 * request that timed out is not an error.
3890 *
3891 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3892 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3893 * for that purpose. Calling this method will attempt to bring up the requested network.
3894 *
Chalard Jean01378b62019-08-30 16:27:28 +09003895 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003896 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3897 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003898 *
3899 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003900 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3901 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003902 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3903 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3904 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003905 */
Chalard Jean158702d2019-01-07 19:26:34 +09003906 public void requestNetwork(@NonNull NetworkRequest request,
3907 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003908 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003909 NetworkCapabilities nc = request.networkCapabilities;
3910 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3911 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003912 }
3913
Hugo Benichifd44e912017-02-02 17:02:36 +09003914 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003915 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichifd44e912017-02-02 17:02:36 +09003916 * by a timeout.
3917 *
Chalard Jean01378b62019-08-30 16:27:28 +09003918 * This method behaves identically to
3919 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3920 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003921 *
Chalard Jean01378b62019-08-30 16:27:28 +09003922 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003923 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3924 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003925 *
3926 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003927 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3928 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003929 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003930 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3931 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003932 */
Chalard Jean158702d2019-01-07 19:26:34 +09003933 public void requestNetwork(@NonNull NetworkRequest request,
3934 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003935 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003936 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003937 NetworkCapabilities nc = request.networkCapabilities;
3938 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003939 }
3940
3941 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003942 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003943 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003944 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003945 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003946 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3947 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003948 */
Erik Kline8a826212014-11-19 12:12:24 +09003949 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003950
3951 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003952 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003953 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003954 * {@link android.content.Intent#getParcelableExtra(String)}.
3955 */
Erik Kline8a826212014-11-19 12:12:24 +09003956 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003957
3958
3959 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003960 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003961 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003962 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003963 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003964 * the request may outlive the calling application and get called back when a suitable
3965 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003966 * <p>
3967 * The operation is an Intent broadcast that goes to a broadcast receiver that
3968 * you registered with {@link Context#registerReceiver} or through the
3969 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3970 * <p>
3971 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003972 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3973 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003974 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003975 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003976 * Intent to reserve the network or it will be released shortly after the Intent
3977 * is processed.
3978 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003979 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003980 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003981 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003982 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003983 * The request may be released normally by calling
3984 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003985 * <p>It is presently unsupported to request a network with either
3986 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3987 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3988 * as these {@code NetworkCapabilities} represent states that a particular
3989 * network may never attain, and whether a network will attain these states
3990 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003991 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003992 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003993 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3994 * number of outstanding requests to 100 per app (identified by their UID), shared with
3995 * all variants of this method, of {@link #registerNetworkCallback} as well as
3996 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3997 * Requesting a network with this method will count toward this limit. If this limit is
3998 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3999 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4000 * or {@link #releaseNetworkRequest(PendingIntent)}.
4001 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004002 * <p>This method requires the caller to hold either the
4003 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4004 * or the ability to modify system settings as determined by
4005 * {@link android.provider.Settings.System#canWrite}.</p>
4006 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004007 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004008 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004009 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004010 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004011 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4012 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004013 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004014 */
Chalard Jean158702d2019-01-07 19:26:34 +09004015 public void requestNetwork(@NonNull NetworkRequest request,
4016 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004017 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004018 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004019 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004020 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004021 request.networkCapabilities, operation, mContext.getOpPackageName(),
4022 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004023 } catch (RemoteException e) {
4024 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004025 } catch (ServiceSpecificException e) {
4026 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004027 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004028 }
4029
4030 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004031 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4032 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004033 * This method has the same behavior as
4034 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004035 * releasing network resources and disconnecting.
4036 *
4037 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4038 * PendingIntent passed to
4039 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4040 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4041 */
Chalard Jean158702d2019-01-07 19:26:34 +09004042 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004043 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004044 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004045 try {
4046 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004047 } catch (RemoteException e) {
4048 throw e.rethrowFromSystemServer();
4049 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004050 }
4051
Hugo Benichibc1104b2017-05-09 15:19:01 +09004052 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004053 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004054 }
4055
4056 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004057 Preconditions.checkNotNull(callback, "null NetworkCallback");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004058 }
4059
4060 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004061 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004062 }
4063
4064 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004065 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004066 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004067 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4068 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004069 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004070 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4071 * number of outstanding requests to 100 per app (identified by their UID), shared with
4072 * all variants of this method, of {@link #requestNetwork} as well as
4073 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4074 * Requesting a network with this method will count toward this limit. If this limit is
4075 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4076 * make sure to unregister the callbacks with
4077 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4078 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004079 * @param request {@link NetworkRequest} describing this request.
4080 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4081 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004082 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004083 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004084 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004085 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004086 public void registerNetworkCallback(@NonNull NetworkRequest request,
4087 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004088 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4089 }
4090
4091 /**
4092 * Registers to receive notifications about all networks which satisfy the given
4093 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004094 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4095 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004096 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004097 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4098 * number of outstanding requests to 100 per app (identified by their UID), shared with
4099 * all variants of this method, of {@link #requestNetwork} as well as
4100 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4101 * Requesting a network with this method will count toward this limit. If this limit is
4102 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4103 * make sure to unregister the callbacks with
4104 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4105 *
4106 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004107 * @param request {@link NetworkRequest} describing this request.
4108 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4109 * networks change state.
4110 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004111 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004112 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004113 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004114 public void registerNetworkCallback(@NonNull NetworkRequest request,
4115 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004116 CallbackHandler cbHandler = new CallbackHandler(handler);
4117 NetworkCapabilities nc = request.networkCapabilities;
4118 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004119 }
4120
4121 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004122 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4123 * {@link NetworkRequest}.
4124 *
4125 * This function behaves identically to the version that takes a NetworkCallback, but instead
4126 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4127 * the request may outlive the calling application and get called back when a suitable
4128 * network is found.
4129 * <p>
4130 * The operation is an Intent broadcast that goes to a broadcast receiver that
4131 * you registered with {@link Context#registerReceiver} or through the
4132 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4133 * <p>
4134 * The operation Intent is delivered with two extras, a {@link Network} typed
4135 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4136 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4137 * the original requests parameters.
4138 * <p>
4139 * If there is already a request for this Intent registered (with the equality of
4140 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4141 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4142 * <p>
4143 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004144 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004145 *
4146 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4147 * number of outstanding requests to 100 per app (identified by their UID), shared with
4148 * all variants of this method, of {@link #requestNetwork} as well as
4149 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4150 * Requesting a network with this method will count toward this limit. If this limit is
4151 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4152 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4153 * or {@link #releaseNetworkRequest(PendingIntent)}.
4154 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004155 * @param request {@link NetworkRequest} describing this request.
4156 * @param operation Action to perform when the network is available (corresponds
4157 * to the {@link NetworkCallback#onAvailable} call. Typically
4158 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004159 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004160 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004161 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004162 public void registerNetworkCallback(@NonNull NetworkRequest request,
4163 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004164 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004165 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004166 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004167 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004168 request.networkCapabilities, operation, mContext.getOpPackageName(),
4169 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004170 } catch (RemoteException e) {
4171 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004172 } catch (ServiceSpecificException e) {
4173 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004174 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004175 }
4176
4177 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004178 * Registers to receive notifications about changes in the application's default network. This
4179 * may be a physical network or a virtual network, such as a VPN that applies to the
4180 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004181 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004182 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004183 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4184 * number of outstanding requests to 100 per app (identified by their UID), shared with
4185 * all variants of this method, of {@link #requestNetwork} as well as
4186 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4187 * Requesting a network with this method will count toward this limit. If this limit is
4188 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4189 * make sure to unregister the callbacks with
4190 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4191 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004192 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004193 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004194 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004195 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004196 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004197 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004198 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004199 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4200 }
4201
4202 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004203 * Registers to receive notifications about changes in the application's default network. This
4204 * may be a physical network or a virtual network, such as a VPN that applies to the
4205 * application. The callbacks will continue to be called until either the application exits or
4206 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4207 *
4208 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4209 * number of outstanding requests to 100 per app (identified by their UID), shared with
4210 * all variants of this method, of {@link #requestNetwork} as well as
4211 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4212 * Requesting a network with this method will count toward this limit. If this limit is
4213 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4214 * make sure to unregister the callbacks with
4215 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4216 *
4217 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4218 * application's default network changes.
4219 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4220 * @throws RuntimeException if the app already has too many callbacks registered.
4221 */
4222 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4223 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4224 @NonNull Handler handler) {
4225 CallbackHandler cbHandler = new CallbackHandler(handler);
4226 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4227 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4228 }
4229
4230 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004231 * Registers to receive notifications about changes in the system default network. The callbacks
4232 * will continue to be called until either the application exits or
4233 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004234 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004235 * This method should not be used to determine networking state seen by applications, because in
4236 * many cases, most or even all application traffic may not use the default network directly,
4237 * and traffic from different applications may go on different networks by default. As an
4238 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4239 * and not onto the system default network. Applications or system components desiring to do
4240 * determine network state as seen by applications should use other methods such as
4241 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4242 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004243 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4244 * number of outstanding requests to 100 per app (identified by their UID), shared with
4245 * all variants of this method, of {@link #requestNetwork} as well as
4246 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4247 * Requesting a network with this method will count toward this limit. If this limit is
4248 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4249 * make sure to unregister the callbacks with
4250 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4251 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004252 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4253 * system default network changes.
4254 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004255 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004256 *
4257 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004258 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004259 @SystemApi(client = MODULE_LIBRARIES)
4260 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4261 @RequiresPermission(anyOf = {
4262 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4263 android.Manifest.permission.NETWORK_SETTINGS})
4264 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004265 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004266 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004267 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004268 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004269 }
4270
4271 /**
junyulai8eb13a22021-03-15 11:48:48 +08004272 * Registers to receive notifications about the best matching network which satisfy the given
4273 * {@link NetworkRequest}. The callbacks will continue to be called until
4274 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4275 * called.
4276 *
4277 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4278 * number of outstanding requests to 100 per app (identified by their UID), shared with
4279 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4280 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4281 * Requesting a network with this method will count toward this limit. If this limit is
4282 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4283 * make sure to unregister the callbacks with
4284 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4285 *
4286 *
4287 * @param request {@link NetworkRequest} describing this request.
4288 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4289 * networks change state.
4290 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4291 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai7514e312021-03-05 15:51:17 +08004292 */
junyulai7514e312021-03-05 15:51:17 +08004293 @SuppressLint("ExecutorRegistration")
4294 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4295 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4296 final NetworkCapabilities nc = request.networkCapabilities;
4297 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai1b1c8742021-03-12 20:05:08 +08004298 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai7514e312021-03-05 15:51:17 +08004299 }
4300
4301 /**
fenglub00f4882015-04-21 17:12:05 -07004302 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4303 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4304 * network connection for updated bandwidth information. The caller will be notified via
4305 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004306 * method assumes that the caller has previously called
4307 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4308 * changes.
fenglu3f357402015-03-20 11:29:56 -07004309 *
fengluea2d9282015-04-27 14:28:04 -07004310 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004311 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004312 */
Chalard Jean158702d2019-01-07 19:26:34 +09004313 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004314 try {
fenglub00f4882015-04-21 17:12:05 -07004315 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004316 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004317 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004318 }
4319 }
4320
4321 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004322 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004323 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4324 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4325 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004326 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4327 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004328 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004329 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4330 * triggering it as soon as this call returns.
4331 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004332 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004333 */
Chalard Jean158702d2019-01-07 19:26:34 +09004334 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004335 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004336 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004337 final List<NetworkRequest> reqs = new ArrayList<>();
4338 // Find all requests associated to this callback and stop callback triggers immediately.
4339 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4340 synchronized (sCallbacks) {
Remi NGUYEN VAN5086c292021-03-15 07:27:44 +00004341 Preconditions.checkArgument(networkCallback.networkRequest != null,
4342 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004343 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4344 Log.d(TAG, "NetworkCallback was already unregistered");
4345 return;
4346 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004347 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4348 if (e.getValue() == networkCallback) {
4349 reqs.add(e.getKey());
4350 }
4351 }
4352 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4353 for (NetworkRequest r : reqs) {
4354 try {
4355 mService.releaseNetworkRequest(r);
4356 } catch (RemoteException e) {
4357 throw e.rethrowFromSystemServer();
4358 }
4359 // Only remove mapping if rpc was successful.
4360 sCallbacks.remove(r);
4361 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004362 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004363 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004364 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004365
4366 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004367 * Unregisters a callback previously registered via
4368 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4369 *
4370 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4371 * PendingIntent passed to
4372 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4373 * Cannot be null.
4374 */
Chalard Jean158702d2019-01-07 19:26:34 +09004375 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004376 releaseNetworkRequest(operation);
4377 }
4378
4379 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004380 * Informs the system whether it should switch to {@code network} regardless of whether it is
4381 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4382 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4383 * the system default network regardless of any other network that's currently connected. If
4384 * {@code always} is true, then the choice is remembered, so that the next time the user
4385 * connects to this network, the system will switch to it.
4386 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004387 * @param network The network to accept.
4388 * @param accept Whether to accept the network even if unvalidated.
4389 * @param always Whether to remember this choice in the future.
4390 *
4391 * @hide
4392 */
lucaslin2240ef62019-03-12 13:08:03 +08004393 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004394 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4395 try {
4396 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004397 } catch (RemoteException e) {
4398 throw e.rethrowFromSystemServer();
4399 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004400 }
4401
4402 /**
lucaslin2240ef62019-03-12 13:08:03 +08004403 * Informs the system whether it should consider the network as validated even if it only has
4404 * partial connectivity. If {@code accept} is true, then the network will be considered as
4405 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4406 * is remembered, so that the next time the user connects to this network, the system will
4407 * switch to it.
4408 *
4409 * @param network The network to accept.
4410 * @param accept Whether to consider the network as validated even if it has partial
4411 * connectivity.
4412 * @param always Whether to remember this choice in the future.
4413 *
4414 * @hide
4415 */
4416 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4417 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4418 try {
4419 mService.setAcceptPartialConnectivity(network, accept, always);
4420 } catch (RemoteException e) {
4421 throw e.rethrowFromSystemServer();
4422 }
4423 }
4424
4425 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004426 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4427 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4428 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4429 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4430 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004431 * @param network The network to accept.
4432 *
4433 * @hide
4434 */
lucaslin2240ef62019-03-12 13:08:03 +08004435 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004436 public void setAvoidUnvalidated(Network network) {
4437 try {
4438 mService.setAvoidUnvalidated(network);
4439 } catch (RemoteException e) {
4440 throw e.rethrowFromSystemServer();
4441 }
4442 }
4443
4444 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004445 * Requests that the system open the captive portal app on the specified network.
4446 *
4447 * @param network The network to log into.
4448 *
4449 * @hide
4450 */
paulhu8e96a752019-08-12 16:25:11 +08004451 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004452 public void startCaptivePortalApp(Network network) {
4453 try {
4454 mService.startCaptivePortalApp(network);
4455 } catch (RemoteException e) {
4456 throw e.rethrowFromSystemServer();
4457 }
4458 }
4459
4460 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004461 * Requests that the system open the captive portal app with the specified extras.
4462 *
4463 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4464 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004465 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004466 * @param appExtras Extras to include in the app start intent.
4467 * @hide
4468 */
4469 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004470 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004471 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004472 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004473 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004474 } catch (RemoteException e) {
4475 throw e.rethrowFromSystemServer();
4476 }
4477 }
4478
4479 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004480 * Determine whether the device is configured to avoid bad wifi.
4481 * @hide
4482 */
4483 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004484 @RequiresPermission(anyOf = {
4485 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4486 android.Manifest.permission.NETWORK_STACK})
4487 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004488 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004489 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004490 } catch (RemoteException e) {
4491 throw e.rethrowFromSystemServer();
4492 }
4493 }
4494
4495 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004496 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4497 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004498 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4499 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004500 *
4501 * An example of such an operation might be a time-sensitive foreground activity, such as a
4502 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4503 */
4504 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4505
4506 /**
4507 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4508 * a backup channel for traffic that is primarily going over another network.
4509 *
4510 * An example might be maintaining backup connections to peers or servers for the purpose of
4511 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4512 * on backup paths should be negligible compared to the traffic on the main path.
4513 */
4514 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4515
4516 /**
4517 * It is acceptable to use metered data to improve network latency and performance.
4518 */
4519 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4520
4521 /**
4522 * Return value to use for unmetered networks. On such networks we currently set all the flags
4523 * to true.
4524 * @hide
4525 */
4526 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4527 MULTIPATH_PREFERENCE_HANDOVER |
4528 MULTIPATH_PREFERENCE_RELIABILITY |
4529 MULTIPATH_PREFERENCE_PERFORMANCE;
4530
4531 /** @hide */
4532 @Retention(RetentionPolicy.SOURCE)
4533 @IntDef(flag = true, value = {
4534 MULTIPATH_PREFERENCE_HANDOVER,
4535 MULTIPATH_PREFERENCE_RELIABILITY,
4536 MULTIPATH_PREFERENCE_PERFORMANCE,
4537 })
4538 public @interface MultipathPreference {
4539 }
4540
4541 /**
4542 * Provides a hint to the calling application on whether it is desirable to use the
4543 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4544 * for multipath data transfer on this network when it is not the system default network.
4545 * Applications desiring to use multipath network protocols should call this method before
4546 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004547 *
4548 * @param network The network on which the application desires to use multipath data.
4549 * If {@code null}, this method will return the a preference that will generally
4550 * apply to metered networks.
4551 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4552 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004553 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004554 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004555 try {
4556 return mService.getMultipathPreference(network);
4557 } catch (RemoteException e) {
4558 throw e.rethrowFromSystemServer();
4559 }
4560 }
4561
4562 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004563 * Resets all connectivity manager settings back to factory defaults.
4564 * @hide
4565 */
paulhu8e96a752019-08-12 16:25:11 +08004566 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004567 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004568 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004569 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004570 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004571 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004572 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004573 }
4574 }
4575
4576 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004577 * Binds the current process to {@code network}. All Sockets created in the future
4578 * (and not explicitly bound via a bound SocketFactory from
4579 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4580 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4581 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4582 * work and all host name resolutions will fail. This is by design so an application doesn't
4583 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4584 * To clear binding pass {@code null} for {@code network}. Using individually bound
4585 * Sockets created by Network.getSocketFactory().createSocket() and
4586 * performing network-specific host name resolutions via
4587 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004588 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004589 *
4590 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4591 * the current binding.
4592 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4593 */
Chalard Jean158702d2019-01-07 19:26:34 +09004594 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004595 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004596 // instantiated.
4597 return setProcessDefaultNetwork(network);
4598 }
4599
4600 /**
4601 * Binds the current process to {@code network}. All Sockets created in the future
4602 * (and not explicitly bound via a bound SocketFactory from
4603 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4604 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4605 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4606 * work and all host name resolutions will fail. This is by design so an application doesn't
4607 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4608 * To clear binding pass {@code null} for {@code network}. Using individually bound
4609 * Sockets created by Network.getSocketFactory().createSocket() and
4610 * performing network-specific host name resolutions via
4611 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4612 * {@code setProcessDefaultNetwork}.
4613 *
4614 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4615 * the current binding.
4616 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4617 * @deprecated This function can throw {@link IllegalStateException}. Use
4618 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4619 * is a direct replacement.
4620 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004621 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004622 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004623 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004624 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4625
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004626 if (netId != NETID_UNSET) {
4627 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004628 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004629
4630 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4631 return false;
4632 }
4633
4634 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004635 // Set HTTP proxy system properties to match network.
4636 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004637 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004638 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004639 } catch (SecurityException e) {
4640 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4641 Log.e(TAG, "Can't set proxy properties", e);
4642 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004643 // Must flush DNS cache as new network may have different DNS resolutions.
4644 InetAddress.clearDnsCache();
4645 // Must flush socket pool as idle sockets will be bound to previous network and may
4646 // cause subsequent fetches to be performed on old network.
4647 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004648 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004649
4650 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004651 }
4652
4653 /**
4654 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004655 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004656 *
4657 * @return {@code Network} to which this process is bound, or {@code null}.
4658 */
Chalard Jean158702d2019-01-07 19:26:34 +09004659 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004660 public Network getBoundNetworkForProcess() {
4661 // Forcing callers to call thru non-static function ensures ConnectivityManager
4662 // instantiated.
4663 return getProcessDefaultNetwork();
4664 }
4665
4666 /**
4667 * Returns the {@link Network} currently bound to this process via
4668 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4669 *
4670 * @return {@code Network} to which this process is bound, or {@code null}.
4671 * @deprecated Using this function can lead to other functions throwing
4672 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4673 * {@code getBoundNetworkForProcess} is a direct replacement.
4674 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004675 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004676 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004677 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004678 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004679 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004680 return new Network(netId);
4681 }
4682
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004683 private void unsupportedStartingFrom(int version) {
4684 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004685 // The getApplicationInfo() call we make below is not supported in system context. Let
4686 // the call through here, and rely on the fact that ConnectivityService will refuse to
4687 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004688 return;
4689 }
4690
4691 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4692 throw new UnsupportedOperationException(
4693 "This method is not supported in target SDK version " + version + " and above");
4694 }
4695 }
4696
4697 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4698 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004699 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004700 // remove these exemptions. Note that this check is not secure, and apps can still access these
4701 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4702 // so is unsupported and may break in the future. http://b/22728205
4703 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004704 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004705 }
4706
Paul Jensen8cdda642014-05-29 10:12:39 -04004707 /**
4708 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004709 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004710 *
4711 * @param network The {@link Network} to bind host resolutions from the current process to, or
4712 * {@code null} to clear the current binding.
4713 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4714 * @hide
4715 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4716 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004717 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004718 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004719 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004720 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004721 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004722 }
Felipe Leme30511352016-01-22 09:44:57 -08004723
4724 /**
4725 * Device is not restricting metered network activity while application is running on
4726 * background.
4727 */
4728 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4729
4730 /**
4731 * Device is restricting metered network activity while application is running on background,
4732 * but application is allowed to bypass it.
4733 * <p>
4734 * In this state, application should take action to mitigate metered network access.
4735 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4736 */
4737 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4738
4739 /**
4740 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004741 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004742 * In this state, application should not try to use the network while running on background,
4743 * because it would be denied.
4744 */
4745 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4746
Felipe Lemed34c9af2016-01-27 14:46:39 -08004747 /**
4748 * A change in the background metered network activity restriction has occurred.
4749 * <p>
4750 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4751 * applies to them.
4752 * <p>
4753 * This is only sent to registered receivers, not manifest receivers.
4754 */
4755 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4756 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4757 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4758
Felipe Leme7e4c1852016-01-25 11:48:04 -08004759 /** @hide */
4760 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004761 @IntDef(flag = false, value = {
4762 RESTRICT_BACKGROUND_STATUS_DISABLED,
4763 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4764 RESTRICT_BACKGROUND_STATUS_ENABLED,
4765 })
Felipe Leme30511352016-01-22 09:44:57 -08004766 public @interface RestrictBackgroundStatus {
4767 }
4768
4769 private INetworkPolicyManager getNetworkPolicyManager() {
4770 synchronized (this) {
4771 if (mNPManager != null) {
4772 return mNPManager;
4773 }
4774 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4775 .getService(Context.NETWORK_POLICY_SERVICE));
4776 return mNPManager;
4777 }
4778 }
4779
4780 /**
4781 * Determines if the calling application is subject to metered network restrictions while
4782 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004783 *
4784 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4785 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4786 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004787 */
4788 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4789 try {
4790 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4791 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004792 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004793 }
4794 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004795
4796 /**
4797 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004798 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4799 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004800 *
4801 * @return Hash of network watchlist config file. Null if config does not exist.
4802 */
Chalard Jean158702d2019-01-07 19:26:34 +09004803 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004804 public byte[] getNetworkWatchlistConfigHash() {
4805 try {
4806 return mService.getNetworkWatchlistConfigHash();
4807 } catch (RemoteException e) {
4808 Log.e(TAG, "Unable to get watchlist config hash");
4809 throw e.rethrowFromSystemServer();
4810 }
4811 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004812
4813 /**
4814 * Returns the {@code uid} of the owner of a network connection.
4815 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004816 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4817 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004818 * @param local The local {@link InetSocketAddress} of a connection.
4819 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004820 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004821 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4822 * android.os.Process#INVALID_UID} if the connection is not found.
4823 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4824 * user.
4825 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004826 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004827 public int getConnectionOwnerUid(
4828 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004829 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4830 try {
4831 return mService.getConnectionOwnerUid(connectionInfo);
4832 } catch (RemoteException e) {
4833 throw e.rethrowFromSystemServer();
4834 }
4835 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004836
4837 private void printStackTrace() {
4838 if (DEBUG) {
4839 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4840 final StringBuffer sb = new StringBuffer();
4841 for (int i = 3; i < callStack.length; i++) {
4842 final String stackTrace = callStack[i].toString();
4843 if (stackTrace == null || stackTrace.contains("android.os")) {
4844 break;
4845 }
4846 sb.append(" [").append(stackTrace).append("]");
4847 }
4848 Log.d(TAG, "StackLog:" + sb.toString());
4849 }
4850 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004851
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004852 /** @hide */
4853 public TestNetworkManager startOrGetTestNetworkManager() {
4854 final IBinder tnBinder;
4855 try {
4856 tnBinder = mService.startOrGetTestNetworkService();
4857 } catch (RemoteException e) {
4858 throw e.rethrowFromSystemServer();
4859 }
4860
4861 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4862 }
4863
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004864 /** @hide */
4865 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4866 return new ConnectivityDiagnosticsManager(mContext, mService);
4867 }
4868
Cody Kestingf53a0752020-04-15 12:33:28 -07004869 /**
4870 * Simulates a Data Stall for the specified Network.
4871 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004872 * <p>This method should only be used for tests.
4873 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004874 * <p>The caller must be the owner of the specified Network.
4875 *
4876 * @param detectionMethod The detection method used to identify the Data Stall.
4877 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4878 * @param network The Network for which a Data Stall is being simluated.
4879 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4880 * @throws SecurityException if the caller is not the owner of the given network.
4881 * @hide
4882 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004883 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004884 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4885 android.Manifest.permission.NETWORK_STACK})
4886 public void simulateDataStall(int detectionMethod, long timestampMillis,
4887 @NonNull Network network, @NonNull PersistableBundle extras) {
4888 try {
4889 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4890 } catch (RemoteException e) {
4891 e.rethrowFromSystemServer();
4892 }
4893 }
James Mattis356a8792020-10-28 21:48:54 -07004894
Daniel Brightf9e945b2020-06-15 16:10:01 -07004895 @NonNull
4896 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4897
4898 /**
4899 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4900 * receive available QoS events related to the {@link Network} and local ip + port
4901 * specified within socketInfo.
4902 * <p/>
4903 * The same {@link QosCallback} must be unregistered before being registered a second time,
4904 * otherwise {@link QosCallbackRegistrationException} is thrown.
4905 * <p/>
4906 * This API does not, in itself, require any permission if called with a network that is not
4907 * restricted. However, the underlying implementation currently only supports the IMS network,
4908 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4909 * useful, because they'd never be called back on networks that they would have access to.
4910 *
4911 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4912 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4913 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4914 * @throws RuntimeException if the app already has too many callbacks registered.
4915 *
4916 * Exceptions after the time of registration is passed through
4917 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4918 *
4919 * @param socketInfo the socket information used to match QoS events
4920 * @param callback receives qos events that satisfy socketInfo
4921 * @param executor The executor on which the callback will be invoked. The provided
4922 * {@link Executor} must run callback sequentially, otherwise the order of
4923 * callbacks cannot be guaranteed.
4924 *
4925 * @hide
4926 */
4927 @SystemApi
4928 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4929 @NonNull final QosCallback callback,
4930 @CallbackExecutor @NonNull final Executor executor) {
4931 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4932 Objects.requireNonNull(callback, "callback must be non-null");
4933 Objects.requireNonNull(executor, "executor must be non-null");
4934
4935 try {
4936 synchronized (mQosCallbackConnections) {
4937 if (getQosCallbackConnection(callback) == null) {
4938 final QosCallbackConnection connection =
4939 new QosCallbackConnection(this, callback, executor);
4940 mQosCallbackConnections.add(connection);
4941 mService.registerQosSocketCallback(socketInfo, connection);
4942 } else {
4943 Log.e(TAG, "registerQosCallback: Callback already registered");
4944 throw new QosCallbackRegistrationException();
4945 }
4946 }
4947 } catch (final RemoteException e) {
4948 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4949
4950 // The same unregister method method is called for consistency even though nothing
4951 // will be sent to the ConnectivityService since the callback was never successfully
4952 // registered.
4953 unregisterQosCallback(callback);
4954 e.rethrowFromSystemServer();
4955 } catch (final ServiceSpecificException e) {
4956 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4957 unregisterQosCallback(callback);
4958 throw convertServiceException(e);
4959 }
4960 }
4961
4962 /**
4963 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4964 * events once unregistered and can be registered a second time.
4965 * <p/>
4966 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4967 *
4968 * @param callback the callback being unregistered
4969 *
4970 * @hide
4971 */
4972 @SystemApi
4973 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4974 Objects.requireNonNull(callback, "The callback must be non-null");
4975 try {
4976 synchronized (mQosCallbackConnections) {
4977 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4978 if (connection != null) {
4979 connection.stopReceivingMessages();
4980 mService.unregisterQosCallback(connection);
4981 mQosCallbackConnections.remove(connection);
4982 } else {
4983 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4984 }
4985 }
4986 } catch (final RemoteException e) {
4987 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4988 e.rethrowFromSystemServer();
4989 }
4990 }
4991
4992 /**
4993 * Gets the connection related to the callback.
4994 *
4995 * @param callback the callback to look up
4996 * @return the related connection
4997 */
4998 @Nullable
4999 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5000 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5001 // Checking by reference here is intentional
5002 if (connection.getCallback() == callback) {
5003 return connection;
5004 }
5005 }
5006 return null;
5007 }
Junyu Laia62493f2021-01-19 11:10:56 +00005008
5009 /**
Roshan Pius951c0032020-12-22 15:10:42 -08005010 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Laia62493f2021-01-19 11:10:56 +00005011 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5012 * be used to request that the system provide a network without causing the network to be
5013 * in the foreground.
5014 *
5015 * <p>This method will attempt to find the best network that matches the passed
5016 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5017 * criteria. The platform will evaluate which network is the best at its own discretion.
5018 * Throughput, latency, cost per byte, policy, user preference and other considerations
5019 * may be factored in the decision of what is considered the best network.
5020 *
5021 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5022 * matching this request, while always attempting to match the request to a better network if
5023 * possible. If a better match is found, the platform will switch this request to the now-best
5024 * network and inform the app of the newly best network by invoking
5025 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5026 * will not try to maintain any other network than the best one currently matching the request:
5027 * a network not matching any network request may be disconnected at any time.
5028 *
5029 * <p>For example, an application could use this method to obtain a connected cellular network
5030 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5031 * radio to consume additional power. Or, an application could inform the system that it wants
5032 * a network supporting sending MMSes and have the system let it know about the currently best
5033 * MMS-supporting network through the provided {@link NetworkCallback}.
5034 *
5035 * <p>The status of the request can be followed by listening to the various callbacks described
5036 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5037 * used to direct traffic to the network (although accessing some networks may be subject to
5038 * holding specific permissions). Callers will learn about the specific characteristics of the
5039 * network through
5040 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5041 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5042 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5043 * matching the request at any given time; therefore when a better network matching the request
5044 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5045 * with the new network after which no further updates are given about the previously-best
5046 * network, unless it becomes the best again at some later time. All callbacks are invoked
5047 * in order on the same thread, which by default is a thread created by the framework running
5048 * in the app.
5049 *
5050 * <p>This{@link NetworkRequest} will live until released via
5051 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5052 * which point the system may let go of the network at any time.
5053 *
5054 * <p>It is presently unsupported to request a network with mutable
5055 * {@link NetworkCapabilities} such as
5056 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5057 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5058 * as these {@code NetworkCapabilities} represent states that a particular
5059 * network may never attain, and whether a network will attain these states
5060 * is unknown prior to bringing up the network so the framework does not
5061 * know how to go about satisfying a request with these capabilities.
5062 *
5063 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5064 * number of outstanding requests to 100 per app (identified by their UID), shared with
5065 * all variants of this method, of {@link #registerNetworkCallback} as well as
5066 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5067 * Requesting a network with this method will count toward this limit. If this limit is
5068 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5069 * make sure to unregister the callbacks with
5070 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5071 *
5072 * @param request {@link NetworkRequest} describing this request.
5073 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5074 * If null, the callback is invoked on the default internal Handler.
5075 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5076 * the callback must not be shared - it uniquely specifies this request.
5077 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5078 * @throws SecurityException if missing the appropriate permissions.
5079 * @throws RuntimeException if the app already has too many callbacks registered.
5080 *
5081 * @hide
5082 */
5083 @SystemApi(client = MODULE_LIBRARIES)
5084 @SuppressLint("ExecutorRegistration")
5085 @RequiresPermission(anyOf = {
5086 android.Manifest.permission.NETWORK_SETTINGS,
5087 android.Manifest.permission.NETWORK_STACK,
5088 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5089 })
5090 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai962bdb82021-03-09 20:49:48 +08005091 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Laia62493f2021-01-19 11:10:56 +00005092 final NetworkCapabilities nc = request.networkCapabilities;
5093 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulai962bdb82021-03-09 20:49:48 +08005094 TYPE_NONE, new CallbackHandler(handler));
Junyu Laia62493f2021-01-19 11:10:56 +00005095 }
James Mattis45d81842021-01-10 14:24:24 -08005096
5097 /**
James Mattis45d81842021-01-10 14:24:24 -08005098 * Used by automotive devices to set the network preferences used to direct traffic at an
5099 * application level as per the given OemNetworkPreferences. An example use-case would be an
5100 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5101 * vehicle via a particular network.
5102 *
5103 * Calling this will overwrite the existing preference.
5104 *
5105 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5106 * @param executor the executor on which listener will be invoked.
5107 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5108 * communicate completion of setOemNetworkPreference(). This will only be
5109 * called once upon successful completion of setOemNetworkPreference().
5110 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5111 * @throws SecurityException if missing the appropriate permissions.
5112 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005113 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005114 */
James Mattisda32cfe2021-01-26 16:23:52 -08005115 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005116 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005117 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005118 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean6010c002021-03-03 16:37:13 +09005119 @Nullable final Runnable listener) {
James Mattis45d81842021-01-10 14:24:24 -08005120 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5121 if (null != listener) {
5122 Objects.requireNonNull(executor, "Executor must be non-null");
5123 }
Chalard Jean6010c002021-03-03 16:37:13 +09005124 final IOnCompleteListener listenerInternal = listener == null ? null :
5125 new IOnCompleteListener.Stub() {
James Mattis45d81842021-01-10 14:24:24 -08005126 @Override
5127 public void onComplete() {
Chalard Jean6010c002021-03-03 16:37:13 +09005128 executor.execute(listener::run);
James Mattis45d81842021-01-10 14:24:24 -08005129 }
5130 };
5131
5132 try {
5133 mService.setOemNetworkPreference(preference, listenerInternal);
5134 } catch (RemoteException e) {
5135 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5136 throw e.rethrowFromSystemServer();
5137 }
5138 }
lucaslin30e70a82021-03-12 00:46:33 +08005139
Chalard Jeanfa45a682021-02-25 17:23:40 +09005140 /**
5141 * Request that a user profile is put by default on a network matching a given preference.
5142 *
5143 * See the documentation for the individual preferences for a description of the supported
5144 * behaviors.
5145 *
5146 * @param profile the profile concerned.
5147 * @param preference the preference for this profile.
5148 * @param executor an executor to execute the listener on. Optional if listener is null.
5149 * @param listener an optional listener to listen for completion of the operation.
5150 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5151 * @throws SecurityException if missing the appropriate permissions.
5152 * @hide
5153 */
Chalard Jean6010c002021-03-03 16:37:13 +09005154 // This function is for establishing per-profile default networking and can only be called by
5155 // the device policy manager, running as the system server. It would make no sense to call it
5156 // on a context for a user because it does not establish a setting on behalf of a user, rather
5157 // it establishes a setting for a user on behalf of the DPM.
5158 @SuppressLint({"UserHandle"})
5159 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09005160 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5161 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5162 @ProfileNetworkPreference final int preference,
5163 @Nullable @CallbackExecutor final Executor executor,
5164 @Nullable final Runnable listener) {
5165 if (null != listener) {
5166 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5167 }
5168 final IOnCompleteListener proxy;
5169 if (null == listener) {
5170 proxy = null;
5171 } else {
5172 proxy = new IOnCompleteListener.Stub() {
5173 @Override
5174 public void onComplete() {
5175 executor.execute(listener::run);
5176 }
5177 };
5178 }
5179 try {
5180 mService.setProfileNetworkPreference(profile, preference, proxy);
5181 } catch (RemoteException e) {
5182 throw e.rethrowFromSystemServer();
5183 }
5184 }
5185
lucaslin30e70a82021-03-12 00:46:33 +08005186 // The first network ID of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005187 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin30e70a82021-03-12 00:46:33 +08005188 // The network ID range of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005189 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin30e70a82021-03-12 00:46:33 +08005190
5191 /**
5192 * Get the network ID range reserved for IPSec tunnel interfaces.
5193 *
5194 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5195 * @hide
5196 */
5197 @SystemApi(client = MODULE_LIBRARIES)
5198 @NonNull
5199 public static Range<Integer> getIpSecNetIdRange() {
5200 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5201 }
lucaslin705c3332021-03-12 17:56:09 +08005202
5203 /**
5204 * Get private DNS mode from settings.
5205 *
5206 * @param cr The ContentResolver to query private DNS mode from settings.
5207 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5208 *
5209 * @hide
5210 */
5211 @SystemApi(client = MODULE_LIBRARIES)
5212 @NonNull
5213 @PrivateDnsMode
5214 public static String getPrivateDnsMode(@NonNull ContentResolver cr) {
5215 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5216 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5217 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5218 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5219 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5220 return mode;
5221 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005222}