blob: c7bb2a75dba0af95786334d34765a4694f195699 [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;
junyulaid05a1922019-01-15 11:32:44 +080019import static android.net.IpSecManager.INVALID_RESOURCE_ID;
Junyu Laia62493f2021-01-19 11:10:56 +000020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaiad010792021-01-11 16:53:38 +080021import static android.net.NetworkRequest.Type.LISTEN;
22import 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;
junyulaid05a1922019-01-15 11:32:44 +080026
junyulai4c95b082018-12-27 17:25:29 +080027import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080028import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090029import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000030import android.annotation.Nullable;
Jeff Sharkey656584a2017-04-24 11:18:03 -060031import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080032import android.annotation.SdkConstant;
33import android.annotation.SdkConstant.SdkConstantType;
Junyu Laia62493f2021-01-19 11:10:56 +000034import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080035import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060036import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070037import android.app.PendingIntent;
Artur Satayev9c2add62019-12-10 17:47:52 +000038import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070039import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070040import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080041import android.net.IpSecManager.UdpEncapsulationSocket;
42import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080043import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080044import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080045import android.net.TetheringManager.TetheringRequest;
Robert Greenwalt2034b912009-08-12 16:08:25 -070046import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000047import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070048import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080049import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070050import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080051import android.os.IBinder;
52import android.os.INetworkActivityListener;
53import android.os.INetworkManagementService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070054import android.os.Looper;
55import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070056import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080057import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070058import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090059import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080060import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080061import android.os.ResultReceiver;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080062import android.os.ServiceManager;
Hugo Benichia590ab82017-05-11 13:16:17 +090063import android.os.ServiceSpecificException;
Jeff Sharkey971cd162011-08-29 16:02:57 -070064import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080065import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080066import android.telephony.TelephonyManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080067import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070068import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090069import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090070import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080071
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090072import com.android.connectivity.aidl.INetworkAgent;
markchien6ae63e52020-01-21 13:11:06 +080073import com.android.internal.annotations.GuardedBy;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090074import com.android.internal.util.Preconditions;
75import com.android.internal.util.Protocol;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070076
Paul Jensen3e2917c2014-08-27 12:38:45 -040077import libcore.net.event.NetworkEventDispatcher;
78
junyulai7e06ad42019-03-04 22:45:36 +080079import java.io.IOException;
80import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080081import java.lang.annotation.Retention;
82import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090083import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080084import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070085import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080086import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090087import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090088import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080089import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090090import java.util.List;
91import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080092import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080093import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080094import java.util.concurrent.ExecutorService;
95import java.util.concurrent.Executors;
96import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -080097
The Android Open Source Project28527d22009-03-03 19:31:44 -080098/**
99 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600100 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101 * <p>
102 * The primary responsibilities of this class are to:
103 * <ol>
104 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
105 * <li>Send broadcast intents when network connectivity changes</li>
106 * <li>Attempt to "fail over" to another network when connectivity to a network
107 * is lost</li>
108 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
109 * state of the available networks</li>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700110 * <li>Provide an API that allows applications to request and select networks for their data
111 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800112 * </ol>
113 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600114@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700115public class ConnectivityManager {
116 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900117 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700118
The Android Open Source Project28527d22009-03-03 19:31:44 -0800119 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700120 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121 * been established or lost. The NetworkInfo for the affected network is
122 * sent as an extra; it should be consulted to see what kind of
123 * connectivity event occurred.
124 * <p/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800125 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
126 * broadcast if they declare the broadcast receiver in their manifest. Apps
127 * will still receive broadcasts if they register their
128 * {@link android.content.BroadcastReceiver} with
129 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
130 * and that context is still valid.
131 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132 * If this is a connection that was the result of failing over from a
133 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
134 * set to true.
135 * <p/>
136 * For a loss of connectivity, if the connectivity manager is attempting
137 * to connect (or has already connected) to another network, the
138 * NetworkInfo for the new network is also passed as an extra. This lets
139 * any receivers of the broadcast know that they should not necessarily
140 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800141 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800142 * the failover attempt succeeded (and so there is still overall data
143 * connectivity), or that the failover attempt failed, meaning that all
144 * connectivity has been lost.
145 * <p/>
146 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
147 * is set to {@code true} if there are no connected networks at all.
Chalard Jean52e23962018-02-10 05:33:50 +0900148 *
149 * @deprecated apps should use the more versatile {@link #requestNetwork},
150 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
151 * functions instead for faster and more detailed updates about the network
152 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800153 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800154 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900155 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700157
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500159 * The device has connected to a network that has presented a captive
160 * portal, which is blocking Internet connectivity. The user was presented
161 * with a notification that network sign in is required,
162 * and the user invoked the notification's action indicating they
Paul Jensen75e0adb2015-05-22 10:50:39 -0400163 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500164 * facilitate signing in to the network. This action includes a
165 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
166 * the network presenting the captive portal; all communication with the
167 * captive portal must be done using this {@code Network} object.
168 * <p/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400169 * This activity includes a {@link CaptivePortal} extra named
170 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
171 * outcomes of the captive portal sign in to the system:
172 * <ul>
173 * <li> When the app handling this action believes the user has signed in to
174 * the network and the captive portal has been dismissed, the app should
175 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
176 * reevaluate the network. If reevaluation finds the network no longer
177 * subject to a captive portal, the network may become the default active
Chalard Jean9dd11612018-06-04 16:52:49 +0900178 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400179 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500180 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400181 * {@link CaptivePortal#ignoreNetwork}. </li>
182 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500183 */
184 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
185 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
186
187 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800188 * The lookup key for a {@link NetworkInfo} object. Retrieve with
189 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700190 *
Chalard Jean97021a12019-01-11 16:47:53 +0900191 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
192 * can't accurately represent modern network characteristics.
193 * Please obtain information about networks from the {@link NetworkCapabilities}
194 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800195 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700196 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800197 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700198
The Android Open Source Project28527d22009-03-03 19:31:44 -0800199 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700200 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700201 *
202 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900203 * @deprecated The network type is not rich enough to represent the characteristics
204 * of modern networks. Please use {@link NetworkCapabilities} instead,
205 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700206 */
Chalard Jean97021a12019-01-11 16:47:53 +0900207 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700208 public static final String EXTRA_NETWORK_TYPE = "networkType";
209
210 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800211 * The lookup key for a boolean that indicates whether a connect event
212 * is for a network to which the connectivity manager was failing over
213 * following a disconnect on another network.
214 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai9826e7f2018-12-13 12:47:51 +0800215 *
216 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800217 */
junyulai9826e7f2018-12-13 12:47:51 +0800218 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800219 public static final String EXTRA_IS_FAILOVER = "isFailover";
220 /**
221 * The lookup key for a {@link NetworkInfo} object. This is supplied when
222 * there is another network that it may be possible to connect to. Retrieve with
223 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800224 *
225 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800226 */
junyulai9826e7f2018-12-13 12:47:51 +0800227 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800228 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
229 /**
230 * The lookup key for a boolean that indicates whether there is a
231 * complete lack of connectivity, i.e., no network is available.
232 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
233 */
234 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
235 /**
236 * The lookup key for a string that indicates why an attempt to connect
237 * to a network failed. The string has no particular structure. It is
238 * intended to be used in notifications presented to users. Retrieve
239 * it with {@link android.content.Intent#getStringExtra(String)}.
240 */
241 public static final String EXTRA_REASON = "reason";
242 /**
243 * The lookup key for a string that provides optionally supplied
244 * extra information about the network state. The information
245 * may be passed up from the lower networking layers, and its
246 * meaning may be specific to a particular network type. Retrieve
247 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800248 *
249 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800250 */
junyulai9826e7f2018-12-13 12:47:51 +0800251 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800252 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700253 /**
254 * The lookup key for an int that provides information about
255 * our connection to the internet at large. 0 indicates no connection,
256 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700257 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700258 * {@hide}
259 */
260 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800261 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400262 * The lookup key for a {@link CaptivePortal} object included with the
263 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
264 * object can be used to either indicate to the system that the captive
265 * portal has been dismissed or that the user does not want to pursue
266 * signing in to captive portal. Retrieve it with
267 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500268 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400269 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700270
271 /**
272 * Key for passing a URL to the captive portal login activity.
273 */
274 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
275
Paul Jensen60df4aa2015-02-27 22:55:47 -0500276 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900277 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
278 * portal login activity.
279 * {@hide}
280 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900281 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900282 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
283 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
284
285 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900286 * Key for passing a user agent string to the captive portal login activity.
287 * {@hide}
288 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900289 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900290 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
291 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
292
293 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700294 * Broadcast action to indicate the change of data activity status
295 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800296 * The network becomes active when data transmission is started, or
297 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700298 * {@hide}
299 */
300 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900301 public static final String ACTION_DATA_ACTIVITY_CHANGE =
302 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700303 /**
304 * The lookup key for an enum that indicates the network device type on which this data activity
305 * change happens.
306 * {@hide}
307 */
308 public static final String EXTRA_DEVICE_TYPE = "deviceType";
309 /**
310 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
311 * it is actively sending or receiving data and {@code false} means it is idle.
312 * {@hide}
313 */
314 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700315 /**
316 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
317 * {@hide}
318 */
319 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700320
321 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800322 * Broadcast Action: The setting for background data usage has changed
323 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
324 * <p>
325 * If an application uses the network in the background, it should listen
326 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700327 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800328 * <p>
329 *
330 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
331 * of background data depends on several combined factors, and
332 * this broadcast is no longer sent. Instead, when background
333 * data is unavailable, {@link #getActiveNetworkInfo()} will now
334 * appear disconnected. During first boot after a platform
335 * upgrade, this broadcast will be sent once if
336 * {@link #getBackgroundDataSetting()} was {@code false} before
337 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800338 */
339 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800340 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800341 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
342 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
343
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700344 /**
345 * Broadcast Action: The network connection may not be good
346 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
347 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
348 * the network and it's condition.
349 * @hide
350 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800351 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100352 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700353 public static final String INET_CONDITION_ACTION =
354 "android.net.conn.INET_CONDITION_ACTION";
355
Robert Greenwalt2034b912009-08-12 16:08:25 -0700356 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800357 * Broadcast Action: A tetherable connection has come or gone.
358 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900359 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
360 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800361 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
362 * the current state of tethering. Each include a list of
363 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800364 * @hide
365 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800366 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000367 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800368 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800369 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800370
371 /**
372 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800373 * gives a String[] listing all the interfaces configured for
374 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800375 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000376 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800377 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800378
379 /**
380 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900381 * gives a String[] listing all the interfaces currently in local-only
382 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800383 */
markchiena0f8fd92019-12-25 19:40:32 +0800384 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900385
386 /**
387 * @hide
388 * gives a String[] listing all the interfaces currently tethered
389 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
390 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000391 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800392 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800393
394 /**
395 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800396 * gives a String[] listing all the interfaces we tried to tether and
397 * failed. Use {@link #getLastTetherError} to find the error code
398 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800399 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000400 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800401 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800402
403 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800404 * Broadcast Action: The captive portal tracker has finished its test.
405 * Sent only while running Setup Wizard, in lieu of showing a user
406 * notification.
407 * @hide
408 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800409 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800410 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
411 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
412 /**
413 * The lookup key for a boolean that indicates whether a captive portal was detected.
414 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
415 * @hide
416 */
417 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
418
419 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900420 * Action used to display a dialog that asks the user whether to connect to a network that is
421 * not validated. This intent is used to start the dialog in settings via startActivity.
422 *
423 * @hide
424 */
425 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
426
427 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900428 * Action used to display a dialog that asks the user whether to avoid a network that is no
429 * longer validated. This intent is used to start the dialog in settings via startActivity.
430 *
431 * @hide
432 */
433 public static final String ACTION_PROMPT_LOST_VALIDATION =
434 "android.net.conn.PROMPT_LOST_VALIDATION";
435
436 /**
lucaslin2240ef62019-03-12 13:08:03 +0800437 * Action used to display a dialog that asks the user whether to stay connected to a network
438 * that has not validated. This intent is used to start the dialog in settings via
439 * startActivity.
440 *
441 * @hide
442 */
443 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
444 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
445
446 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800447 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900448 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800449 * @hide
450 */
markchiena0f8fd92019-12-25 19:40:32 +0800451 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800452
453 /**
454 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900455 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800456 * @hide
457 */
458 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900459 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800460
461 /**
462 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900463 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800464 * @hide
465 */
466 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900467 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800468
469 /**
470 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900471 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800472 * @hide
473 */
474 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900475 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800476
477 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800478 * Wifi P2p tethering type.
479 * Wifi P2p tethering is set through events automatically, and don't
480 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
481 * @hide
482 */
markchiena0f8fd92019-12-25 19:40:32 +0800483 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800484
485 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800486 * Extra used for communicating with the TetherService. Includes the type of tethering to
487 * enable if any.
488 * @hide
489 */
markchien6ae63e52020-01-21 13:11:06 +0800490 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800491
492 /**
493 * Extra used for communicating with the TetherService. Includes the type of tethering for
494 * which to cancel provisioning.
495 * @hide
496 */
markchien6ae63e52020-01-21 13:11:06 +0800497 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800498
499 /**
500 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
501 * provisioning.
502 * @hide
503 */
markchien6ae63e52020-01-21 13:11:06 +0800504 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800505
506 /**
507 * Tells the TetherService to run a provision check now.
508 * @hide
509 */
markchien6ae63e52020-01-21 13:11:06 +0800510 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800511
512 /**
513 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
514 * which will receive provisioning results. Can be left empty.
515 * @hide
516 */
markchien6ae63e52020-01-21 13:11:06 +0800517 public static final String EXTRA_PROVISION_CALLBACK =
518 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800519
520 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800521 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700522 * @hide
523 */
paulhu74357e72020-01-13 16:46:45 +0800524 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700525 public static final int TYPE_NONE = -1;
526
527 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900528 * A Mobile data connection. Devices may support more than one.
529 *
530 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
531 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
532 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700533 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900534 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700535 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900536
Robert Greenwalt2034b912009-08-12 16:08:25 -0700537 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900538 * A WIFI data connection. Devices may support more than one.
539 *
540 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
541 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
542 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700543 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900544 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700545 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900546
Robert Greenwalt2034b912009-08-12 16:08:25 -0700547 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800548 * An MMS-specific Mobile data connection. This network type may use the
549 * same network interface as {@link #TYPE_MOBILE} or it may use a different
550 * one. This is used by applications needing to talk to the carrier's
551 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900552 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900553 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900554 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900555 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700556 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700557 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700558 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900559
Robert Greenwalt2034b912009-08-12 16:08:25 -0700560 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800561 * A SUPL-specific Mobile data connection. This network type may use the
562 * same network interface as {@link #TYPE_MOBILE} or it may use a different
563 * one. This is used by applications needing to talk to the carrier's
564 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900565 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900566 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900567 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900568 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700569 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700570 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900572
Robert Greenwalt2034b912009-08-12 16:08:25 -0700573 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800574 * A DUN-specific Mobile data connection. This network type may use the
575 * same network interface as {@link #TYPE_MOBILE} or it may use a different
576 * one. This is sometimes by the system when setting up an upstream connection
577 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900578 *
579 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
580 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
581 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700582 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900583 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900585
Robert Greenwalt2034b912009-08-12 16:08:25 -0700586 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800587 * A High Priority Mobile data connection. This network type uses the
588 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900589 * is different.
590 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900591 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
592 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
593 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700594 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700595 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700596 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900597
jshbfa81722010-03-11 15:04:43 -0800598 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900599 * A WiMAX data connection.
600 *
601 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
602 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
603 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800604 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900605 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800606 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800607
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800608 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900609 * A Bluetooth data connection.
610 *
611 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
612 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
613 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800614 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900615 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800616 public static final int TYPE_BLUETOOTH = 7;
617
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700618 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800619 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900620 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700621 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900622 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800623 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800624
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700625 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900626 * An Ethernet data connection.
627 *
628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
630 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700631 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900632 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800633 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700634
Wink Savilleb7c92c72011-03-12 14:52:01 -0800635 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800636 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900637 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800638 * {@hide}
639 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900640 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900641 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800642 public static final int TYPE_MOBILE_FOTA = 10;
643
644 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800645 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900646 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800647 * {@hide}
648 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900649 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100650 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800651 public static final int TYPE_MOBILE_IMS = 11;
652
653 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800654 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900655 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800656 * {@hide}
657 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900658 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900659 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800660 public static final int TYPE_MOBILE_CBS = 12;
661
repo syncf5de5572011-07-29 23:55:49 -0700662 /**
663 * A Wi-Fi p2p connection. Only requesting processes will have access to
664 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900665 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700666 * {@hide}
667 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900668 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800669 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700670 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800671
Wink Saville512c2202013-07-29 15:00:57 -0700672 /**
673 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900674 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700675 * {@hide}
676 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900677 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100678 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700679 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700680
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900681 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700682 * Emergency PDN connection for emergency services. This
683 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900684 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700685 * {@hide}
686 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900687 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900688 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700689 public static final int TYPE_MOBILE_EMERGENCY = 15;
690
Hui Lu865b70d2014-01-15 11:05:36 -0500691 /**
692 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900693 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500694 * {@hide}
695 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900696 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900697 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500698 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700699
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700700 /**
701 * A virtual network using one or more native bearers.
702 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900703 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700704 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900705 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700706 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500707
Benedict Wongbdfaa482018-11-14 17:40:55 -0800708 /**
709 * A network that is exclusively meant to be used for testing
710 *
711 * @deprecated Use {@link NetworkCapabilities} instead.
712 * @hide
713 */
714 @Deprecated
715 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700716
Chalard Jeanaea539a2020-03-25 01:24:04 +0900717 /**
718 * @deprecated Use {@link NetworkCapabilities} instead.
719 * @hide
720 */
721 @Deprecated
722 @Retention(RetentionPolicy.SOURCE)
723 @IntDef(prefix = { "TYPE_" }, value = {
724 TYPE_NONE,
725 TYPE_MOBILE,
726 TYPE_WIFI,
727 TYPE_MOBILE_MMS,
728 TYPE_MOBILE_SUPL,
729 TYPE_MOBILE_DUN,
730 TYPE_MOBILE_HIPRI,
731 TYPE_WIMAX,
732 TYPE_BLUETOOTH,
733 TYPE_DUMMY,
734 TYPE_ETHERNET,
735 TYPE_MOBILE_FOTA,
736 TYPE_MOBILE_IMS,
737 TYPE_MOBILE_CBS,
738 TYPE_WIFI_P2P,
739 TYPE_MOBILE_IA,
740 TYPE_MOBILE_EMERGENCY,
741 TYPE_PROXY,
742 TYPE_VPN,
743 TYPE_TEST
744 })
745 public @interface LegacyNetworkType {}
746
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900747 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
748 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
749 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
750 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
751 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
752
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700753 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800754 public static final int MAX_RADIO_TYPE = TYPE_TEST;
755
756 /** {@hide} */
757 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800758
Hugo Benichiad353f42017-06-20 14:07:59 +0900759 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
760
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800761 /**
762 * If you want to set the default network preference,you can directly
763 * change the networkAttributes array in framework's config.xml.
764 *
765 * @deprecated Since we support so many more networks now, the single
766 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800767 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800768 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800769 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800770 * from an App.
771 */
772 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800773 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
774
Jeff Sharkey8c870452012-09-26 22:03:49 -0700775 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700776 * @hide
777 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900778 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700779
Paul Jensen5dea4352014-07-11 12:28:19 -0400780 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900781 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
782 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900783 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900784 * @hide
785 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900786 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900787 new NetworkRequest.Builder().clearCapabilities().build();
788
789 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400790 * A NetID indicating no Network is selected.
791 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
792 * @hide
793 */
794 public static final int NETID_UNSET = 0;
795
Erik Klineb0be3e62017-10-30 15:29:44 +0900796 /**
797 * Private DNS Mode values.
798 *
799 * The "private_dns_mode" global setting stores a String value which is
800 * expected to be one of the following.
801 */
802
803 /**
804 * @hide
805 */
806 public static final String PRIVATE_DNS_MODE_OFF = "off";
807 /**
808 * @hide
809 */
810 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
811 /**
812 * @hide
813 */
814 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
815 /**
816 * The default Private DNS mode.
817 *
818 * This may change from release to release or may become dependent upon
819 * the capabilities of the underlying platform.
820 *
821 * @hide
822 */
Erik Klinea7edf6f2018-05-16 16:41:57 +0900823 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Klineb0be3e62017-10-30 15:29:44 +0900824
Chalard Jeana3b77512019-04-09 15:46:21 +0900825 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700826 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900827
Paul Jensenc0618a62014-12-10 15:12:18 -0500828 /**
829 * A kludge to facilitate static access where a Context pointer isn't available, like in the
830 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
831 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
832 * methods that take a Context argument.
833 */
834 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800835
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900836 private final Context mContext;
837
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800838 private INetworkManagementService mNMService;
Felipe Leme30511352016-01-22 09:44:57 -0800839 private INetworkPolicyManager mNPManager;
Amos Bianchia9b415a2020-03-04 11:07:38 -0800840 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800841
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800842 /**
843 * Tests if a given integer represents a valid network type.
844 * @param networkType the type to be tested
845 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400846 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
847 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800848 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700849 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700850 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900851 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800852 }
853
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800854 /**
855 * Returns a non-localized string representing a given network type.
856 * ONLY used for debugging output.
857 * @param type the type needing naming
858 * @return a String for the given type, or a string version of the type ("87")
859 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900860 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800861 * {@hide}
862 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900863 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000864 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700865 public static String getNetworkTypeName(int type) {
866 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900867 case TYPE_NONE:
868 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700869 case TYPE_MOBILE:
870 return "MOBILE";
871 case TYPE_WIFI:
872 return "WIFI";
873 case TYPE_MOBILE_MMS:
874 return "MOBILE_MMS";
875 case TYPE_MOBILE_SUPL:
876 return "MOBILE_SUPL";
877 case TYPE_MOBILE_DUN:
878 return "MOBILE_DUN";
879 case TYPE_MOBILE_HIPRI:
880 return "MOBILE_HIPRI";
881 case TYPE_WIMAX:
882 return "WIMAX";
883 case TYPE_BLUETOOTH:
884 return "BLUETOOTH";
885 case TYPE_DUMMY:
886 return "DUMMY";
887 case TYPE_ETHERNET:
888 return "ETHERNET";
889 case TYPE_MOBILE_FOTA:
890 return "MOBILE_FOTA";
891 case TYPE_MOBILE_IMS:
892 return "MOBILE_IMS";
893 case TYPE_MOBILE_CBS:
894 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700895 case TYPE_WIFI_P2P:
896 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700897 case TYPE_MOBILE_IA:
898 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700899 case TYPE_MOBILE_EMERGENCY:
900 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500901 case TYPE_PROXY:
902 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900903 case TYPE_VPN:
904 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700905 default:
906 return Integer.toString(type);
907 }
908 }
909
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800910 /**
Aaron Huang96011892020-06-27 07:18:23 +0800911 * @hide
912 * TODO: Expose for SystemServer when becomes a module.
913 */
914 public void systemReady() {
915 try {
916 mService.systemReady();
917 } catch (RemoteException e) {
918 throw e.rethrowFromSystemServer();
919 }
920 }
921
922 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800923 * Checks if a given type uses the cellular data connection.
924 * This should be replaced in the future by a network property.
925 * @param networkType the type to check
926 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900927 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800928 * {@hide}
929 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900930 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900931 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700932 public static boolean isNetworkTypeMobile(int networkType) {
933 switch (networkType) {
934 case TYPE_MOBILE:
935 case TYPE_MOBILE_MMS:
936 case TYPE_MOBILE_SUPL:
937 case TYPE_MOBILE_DUN:
938 case TYPE_MOBILE_HIPRI:
939 case TYPE_MOBILE_FOTA:
940 case TYPE_MOBILE_IMS:
941 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -0700942 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -0700943 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700944 return true;
945 default:
946 return false;
947 }
948 }
949
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800950 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700951 * Checks if the given network type is backed by a Wi-Fi radio.
952 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900953 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700954 * @hide
955 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900956 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700957 public static boolean isNetworkTypeWifi(int networkType) {
958 switch (networkType) {
959 case TYPE_WIFI:
960 case TYPE_WIFI_P2P:
961 return true;
962 default:
963 return false;
964 }
965 }
966
967 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800968 * Specifies the preferred network type. When the device has more
969 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800970 *
971 * @param preference the network type to prefer over all others. It is
972 * unspecified what happens to the old preferred network in the
973 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700974 * @deprecated Functionality has been removed as it no longer makes sense,
975 * with many more than two networks - we'd need an array to express
976 * preference. Instead we use dynamic network properties of
977 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800978 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700979 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800980 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800981 }
982
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800983 /**
984 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800985 *
986 * @return an integer representing the preferred network type
987 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700988 * @deprecated Functionality has been removed as it no longer makes sense,
989 * with many more than two networks - we'd need an array to express
990 * preference. Instead we use dynamic network properties of
991 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800992 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700993 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -0600994 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -0800995 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700996 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800997 }
998
Scott Mainf58b7d82011-10-06 19:02:28 -0700999 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001000 * Returns details about the currently active default data network. When
1001 * connected, this network is the default route for outgoing connections.
1002 * You should always check {@link NetworkInfo#isConnected()} before initiating
1003 * network traffic. This may return {@code null} when there is no default
1004 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001005 * Note that if the default network is a VPN, this method will return the
1006 * NetworkInfo for one of its underlying networks instead, or null if the
1007 * VPN agent did not specify any. Apps interested in learning about VPNs
1008 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001009 *
1010 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001011 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001012 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001013 */
junyulai9826e7f2018-12-13 12:47:51 +08001014 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001015 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001016 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001017 public NetworkInfo getActiveNetworkInfo() {
1018 try {
1019 return mService.getActiveNetworkInfo();
1020 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001021 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001022 }
1023 }
1024
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001025 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001026 * Returns a {@link Network} object corresponding to the currently active
1027 * default data network. In the event that the current active default data
1028 * network disconnects, the returned {@code Network} object will no longer
1029 * be usable. This will return {@code null} when there is no default
1030 * network.
1031 *
1032 * @return a {@link Network} object for the current default network or
1033 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001034 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001035 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001036 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001037 public Network getActiveNetwork() {
1038 try {
1039 return mService.getActiveNetwork();
1040 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001041 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001042 }
1043 }
1044
1045 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001046 * Returns a {@link Network} object corresponding to the currently active
1047 * default data network for a specific UID. In the event that the default data
1048 * network disconnects, the returned {@code Network} object will no longer
1049 * be usable. This will return {@code null} when there is no default
1050 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001051 *
1052 * @return a {@link Network} object for the current default network for the
1053 * given UID or {@code null} if no default network is currently active
1054 *
1055 * @hide
1056 */
paulhu8e96a752019-08-12 16:25:11 +08001057 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001058 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001059 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001060 return getActiveNetworkForUid(uid, false);
1061 }
1062
1063 /** {@hide} */
1064 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001065 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001066 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001067 } catch (RemoteException e) {
1068 throw e.rethrowFromSystemServer();
1069 }
1070 }
1071
1072 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001073 * Calls VpnManager#isAlwaysOnVpnPackageSupportedForUser.
1074 * @deprecated TODO: remove when callers have migrated to VpnManager.
Charles He9369e612017-05-15 17:07:18 +01001075 * @hide
1076 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09001077 @Deprecated
Charles He9369e612017-05-15 17:07:18 +01001078 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001079 return getVpnManager().isAlwaysOnVpnPackageSupportedForUser(userId, vpnPackage);
Charles He9369e612017-05-15 17:07:18 +01001080 }
1081
1082 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001083 * Calls VpnManager#setAlwaysOnVpnPackageForUser.
1084 * @deprecated TODO: remove when callers have migrated to VpnManager.
Robin Leee5d5ed52016-01-05 18:03:46 +00001085 * @hide
1086 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09001087 @Deprecated
Robin Lee94e69be2016-05-03 13:23:03 +01001088 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001089 boolean lockdownEnabled, @Nullable List<String> lockdownAllowlist) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001090 return getVpnManager().setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdownEnabled,
1091 lockdownAllowlist);
Robin Leee5d5ed52016-01-05 18:03:46 +00001092 }
1093
Lorenzo Colitticd675292021-02-04 17:32:07 +09001094 /**
1095 * Calls VpnManager#getAlwaysOnVpnPackageForUser.
1096 * @deprecated TODO: remove when callers have migrated to VpnManager.
Robin Leee5d5ed52016-01-05 18:03:46 +00001097 * @hide
1098 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09001099 @Deprecated
Robin Leee5d5ed52016-01-05 18:03:46 +00001100 public String getAlwaysOnVpnPackageForUser(int userId) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001101 return getVpnManager().getAlwaysOnVpnPackageForUser(userId);
Robin Leee5d5ed52016-01-05 18:03:46 +00001102 }
1103
1104 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001105 * Calls VpnManager#isVpnLockdownEnabled.
1106 * @deprecated TODO: remove when callers have migrated to VpnManager.
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001107 * @hide
Lorenzo Colitticd675292021-02-04 17:32:07 +09001108 */
1109 @Deprecated
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001110 public boolean isVpnLockdownEnabled(int userId) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001111 return getVpnManager().isVpnLockdownEnabled(userId);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001112 }
1113
1114 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001115 * Calls VpnManager#getVpnLockdownAllowlist.
1116 * @deprecated TODO: remove when callers have migrated to VpnManager.
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001117 * @hide
Lorenzo Colitticd675292021-02-04 17:32:07 +09001118 */
1119 @Deprecated
Lorenzo Colittie7743b72021-02-08 16:25:42 +09001120 public List<String> getVpnLockdownAllowlist(int userId) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001121 return getVpnManager().getVpnLockdownAllowlist(userId);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001122 }
1123
1124 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001125 * Adds or removes a requirement for given UID ranges to use the VPN.
1126 *
1127 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1128 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1129 * otherwise have permission to bypass the VPN (e.g., because they have the
1130 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1131 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1132 * set to {@code false}, a previously-added restriction is removed.
1133 * <p>
1134 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1135 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1136 * remove a previously-added range, the exact range must be removed as is.
1137 * <p>
1138 * The changes are applied asynchronously and may not have been applied by the time the method
1139 * returns. Apps will be notified about any changes that apply to them via
1140 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1141 * effect.
1142 * <p>
1143 * This method should be called only by the VPN code.
1144 *
1145 * @param ranges the UID ranges to restrict
1146 * @param requireVpn whether the specified UID ranges must use a VPN
1147 *
1148 * TODO: expose as @SystemApi.
1149 * @hide
1150 */
1151 @RequiresPermission(anyOf = {
1152 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1153 android.Manifest.permission.NETWORK_STACK})
1154 public void setRequireVpnForUids(boolean requireVpn,
1155 @NonNull Collection<Range<Integer>> ranges) {
1156 Objects.requireNonNull(ranges);
1157 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1158 // This method is not necessarily expected to be used outside the system server, so
1159 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1160 // stack process, or by tests.
1161 UidRange[] rangesArray = new UidRange[ranges.size()];
1162 int index = 0;
1163 for (Range<Integer> range : ranges) {
1164 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1165 }
1166 try {
1167 mService.setRequireVpnForUids(requireVpn, rangesArray);
1168 } catch (RemoteException e) {
1169 throw e.rethrowFromSystemServer();
1170 }
1171 }
1172
1173 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001174 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1175 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1176 * but is still supported for backwards compatibility.
1177 * <p>
1178 * This type of VPN is assumed always to use the system default network, and must always declare
1179 * exactly one underlying network, which is the network that was the default when the VPN
1180 * connected.
1181 * <p>
1182 * Calling this method with {@code true} enables legacy behaviour, specifically:
1183 * <ul>
1184 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1185 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1186 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1187 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1188 * underlying the VPN.</li>
1189 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1190 * similarly replaced by the VPN network state.</li>
1191 * <li>Information on current network interfaces passed to NetworkStatsService will not
1192 * include any VPN interfaces.</li>
1193 * </ul>
1194 *
1195 * @param enabled whether legacy lockdown VPN is enabled or disabled
1196 *
1197 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1198 *
1199 * @hide
1200 */
1201 @RequiresPermission(anyOf = {
1202 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1203 android.Manifest.permission.NETWORK_SETTINGS})
1204 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1205 try {
1206 mService.setLegacyLockdownVpnEnabled(enabled);
1207 } catch (RemoteException e) {
1208 throw e.rethrowFromSystemServer();
1209 }
1210 }
1211
1212 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001213 * Returns details about the currently active default data network
1214 * for a given uid. This is for internal use only to avoid spying
1215 * other apps.
1216 *
1217 * @return a {@link NetworkInfo} object for the current default network
1218 * for the given uid or {@code null} if no default network is
1219 * available for the specified uid.
1220 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001221 * {@hide}
1222 */
paulhu8e96a752019-08-12 16:25:11 +08001223 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001224 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001225 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001226 return getActiveNetworkInfoForUid(uid, false);
1227 }
1228
1229 /** {@hide} */
1230 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001231 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001232 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001233 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001234 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001235 }
1236 }
1237
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001238 /**
1239 * Returns connection status information about a particular
1240 * network type.
1241 *
1242 * @param networkType integer specifying which networkType in
1243 * which you're interested.
1244 * @return a {@link NetworkInfo} object for the requested
1245 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001246 * supported by the device. If {@code networkType} is
1247 * TYPE_VPN and a VPN is active for the calling app,
1248 * then this method will try to return one of the
1249 * underlying networks for the VPN or null if the
1250 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001251 *
Paul Jensendda8e592015-03-18 12:23:02 -04001252 * @deprecated This method does not support multiple connected networks
1253 * of the same type. Use {@link #getAllNetworks} and
1254 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001255 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001256 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001257 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001258 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001259 public NetworkInfo getNetworkInfo(int networkType) {
1260 try {
1261 return mService.getNetworkInfo(networkType);
1262 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001263 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001264 }
1265 }
1266
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001267 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001268 * Returns connection status information about a particular
1269 * Network.
1270 *
1271 * @param network {@link Network} specifying which network
1272 * in which you're interested.
1273 * @return a {@link NetworkInfo} object for the requested
1274 * network or {@code null} if the {@code Network}
1275 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001276 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001277 */
junyulai9826e7f2018-12-13 12:47:51 +08001278 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001279 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001280 @Nullable
1281 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001282 return getNetworkInfoForUid(network, Process.myUid(), false);
1283 }
1284
1285 /** {@hide} */
1286 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001287 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001288 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001289 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001290 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001291 }
1292 }
1293
1294 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001295 * Returns connection status information about all network
1296 * types supported by the device.
1297 *
1298 * @return an array of {@link NetworkInfo} objects. Check each
1299 * {@link NetworkInfo#getType} for which type each applies.
1300 *
Paul Jensendda8e592015-03-18 12:23:02 -04001301 * @deprecated This method does not support multiple connected networks
1302 * of the same type. Use {@link #getAllNetworks} and
1303 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001304 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001305 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001306 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001307 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001308 public NetworkInfo[] getAllNetworkInfo() {
1309 try {
1310 return mService.getAllNetworkInfo();
1311 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001312 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001313 }
1314 }
1315
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001316 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001317 * Returns the {@link Network} object currently serving a given type, or
1318 * null if the given type is not connected.
1319 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001320 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001321 * @deprecated This method does not support multiple connected networks
1322 * of the same type. Use {@link #getAllNetworks} and
1323 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001324 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001325 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001326 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001327 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001328 public Network getNetworkForType(int networkType) {
1329 try {
1330 return mService.getNetworkForType(networkType);
1331 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001332 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001333 }
1334 }
1335
1336 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001337 * Returns an array of all {@link Network} currently tracked by the
1338 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001339 *
1340 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001341 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001342 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001343 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001344 public Network[] getAllNetworks() {
1345 try {
1346 return mService.getAllNetworks();
1347 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001348 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001349 }
1350 }
1351
1352 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001353 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001354 * the Networks that applications run by the given user will use by default.
1355 * @hide
1356 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001357 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001358 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1359 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001360 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001361 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001362 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001363 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001364 }
1365 }
1366
1367 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001368 * Returns the IP information for the current default network.
1369 *
1370 * @return a {@link LinkProperties} object describing the IP info
1371 * for the current default network, or {@code null} if there
1372 * is no current default network.
1373 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001374 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001375 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1376 * value of {@link #getActiveNetwork()} instead. In particular,
1377 * this method will return non-null LinkProperties even if the
1378 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001379 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001380 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001381 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001382 public LinkProperties getActiveLinkProperties() {
1383 try {
1384 return mService.getActiveLinkProperties();
1385 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001386 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001387 }
1388 }
1389
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001390 /**
1391 * Returns the IP information for a given network type.
1392 *
1393 * @param networkType the network type of interest.
1394 * @return a {@link LinkProperties} object describing the IP info
1395 * for the given networkType, or {@code null} if there is
1396 * no current default network.
1397 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001398 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001399 * @deprecated This method does not support multiple connected networks
1400 * of the same type. Use {@link #getAllNetworks},
1401 * {@link #getNetworkInfo(android.net.Network)}, and
1402 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001403 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001404 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001405 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001406 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001407 public LinkProperties getLinkProperties(int networkType) {
1408 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001409 return mService.getLinkPropertiesForType(networkType);
1410 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001411 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001412 }
1413 }
1414
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001415 /**
1416 * Get the {@link LinkProperties} for the given {@link Network}. This
1417 * will return {@code null} if the network is unknown.
1418 *
1419 * @param network The {@link Network} object identifying the network in question.
1420 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001421 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001422 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001423 @Nullable
1424 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001425 try {
1426 return mService.getLinkProperties(network);
1427 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001428 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001429 }
1430 }
1431
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001432 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001433 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001434 * will return {@code null} if the network is unknown.
1435 *
1436 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001437 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001438 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001439 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001440 @Nullable
1441 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001442 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001443 return mService.getNetworkCapabilities(
1444 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001445 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001446 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001447 }
1448 }
1449
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001450 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001451 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001452 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1453 * portal is present.
1454 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1455 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1456 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001457 * The system network validation may be using different strategies to detect captive portals,
1458 * so this method does not necessarily return a URL used by the system. It only returns a URL
1459 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001460 *
Udam Sainicd645462016-01-04 12:16:14 -08001461 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001462 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1463 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001464 */
paulhu8e96a752019-08-12 16:25:11 +08001465 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001466 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001467 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001468 public String getCaptivePortalServerUrl() {
1469 try {
1470 return mService.getCaptivePortalServerUrl();
1471 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001472 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001473 }
1474 }
1475
1476 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001477 * Tells the underlying networking system that the caller wants to
1478 * begin using the named feature. The interpretation of {@code feature}
1479 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001480 *
1481 * <p>This method requires the caller to hold either the
1482 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1483 * or the ability to modify system settings as determined by
1484 * {@link android.provider.Settings.System#canWrite}.</p>
1485 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001486 * @param networkType specifies which network the request pertains to
1487 * @param feature the name of the feature to be used
1488 * @return an integer value representing the outcome of the request.
1489 * The interpretation of this value is specific to each networking
1490 * implementation+feature combination, except that the value {@code -1}
1491 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001492 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001493 * @deprecated Deprecated in favor of the cleaner
1494 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001495 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001496 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001497 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001498 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001499 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001500 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001501 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001502 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1503 if (netCap == null) {
1504 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1505 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001506 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001507 }
1508
1509 NetworkRequest request = null;
1510 synchronized (sLegacyRequests) {
1511 LegacyRequest l = sLegacyRequests.get(netCap);
1512 if (l != null) {
1513 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1514 renewRequestLocked(l);
1515 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001516 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001517 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001518 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001519 }
1520 }
1521
1522 request = requestNetworkForFeatureLocked(netCap);
1523 }
1524 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001525 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001526 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001527 } else {
1528 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001529 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001530 }
1531 }
1532
1533 /**
1534 * Tells the underlying networking system that the caller is finished
1535 * using the named feature. The interpretation of {@code feature}
1536 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001537 *
1538 * <p>This method requires the caller to hold either the
1539 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1540 * or the ability to modify system settings as determined by
1541 * {@link android.provider.Settings.System#canWrite}.</p>
1542 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001543 * @param networkType specifies which network the request pertains to
1544 * @param feature the name of the feature that is no longer needed
1545 * @return an integer value representing the outcome of the request.
1546 * The interpretation of this value is specific to each networking
1547 * implementation+feature combination, except that the value {@code -1}
1548 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001549 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001550 * @deprecated Deprecated in favor of the cleaner
1551 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001552 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001553 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001554 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001555 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001556 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001557 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001558 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001559 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1560 if (netCap == null) {
1561 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1562 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001563 return -1;
1564 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001565
Paul Jensen49f74a32014-12-17 10:39:34 -05001566 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001567 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001568 }
1569 return 1;
1570 }
1571
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001572 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001573 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1574 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001575 switch (feature) {
1576 case "enableCBS":
1577 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1578 case "enableDUN":
1579 case "enableDUNAlways":
1580 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1581 case "enableFOTA":
1582 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1583 case "enableHIPRI":
1584 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1585 case "enableIMS":
1586 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1587 case "enableMMS":
1588 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1589 case "enableSUPL":
1590 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1591 default:
1592 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001593 }
Erik Klinece55eb12017-01-26 18:08:28 +09001594 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1595 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001596 }
1597 return null;
1598 }
1599
Robert Greenwalt802c1102014-06-02 15:32:02 -07001600 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001601 if (netCap == null) return TYPE_NONE;
1602 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1603 return TYPE_MOBILE_CBS;
1604 }
1605 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1606 return TYPE_MOBILE_IMS;
1607 }
1608 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1609 return TYPE_MOBILE_FOTA;
1610 }
1611 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1612 return TYPE_MOBILE_DUN;
1613 }
1614 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1615 return TYPE_MOBILE_SUPL;
1616 }
1617 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1618 return TYPE_MOBILE_MMS;
1619 }
1620 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1621 return TYPE_MOBILE_HIPRI;
1622 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001623 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1624 return TYPE_WIFI_P2P;
1625 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001626 return TYPE_NONE;
1627 }
1628
1629 private static class LegacyRequest {
1630 NetworkCapabilities networkCapabilities;
1631 NetworkRequest networkRequest;
1632 int expireSequenceNumber;
1633 Network currentNetwork;
1634 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001635
1636 private void clearDnsBinding() {
1637 if (currentNetwork != null) {
1638 currentNetwork = null;
1639 setProcessDefaultNetworkForHostResolution(null);
1640 }
1641 }
1642
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001643 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001644 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001645 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001646 currentNetwork = network;
1647 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001648 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001649 }
1650 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001651 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001652 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001653 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1654 }
1655 };
1656 }
1657
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001658 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001659 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1660 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001661
1662 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1663 synchronized (sLegacyRequests) {
1664 LegacyRequest l = sLegacyRequests.get(netCap);
1665 if (l != null) return l.networkRequest;
1666 }
1667 return null;
1668 }
1669
1670 private void renewRequestLocked(LegacyRequest l) {
1671 l.expireSequenceNumber++;
1672 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1673 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1674 }
1675
1676 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1677 int ourSeqNum = -1;
1678 synchronized (sLegacyRequests) {
1679 LegacyRequest l = sLegacyRequests.get(netCap);
1680 if (l == null) return;
1681 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001682 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001683 }
1684 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1685 }
1686
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001687 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001688 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1689 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001690 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001691 try {
1692 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001693 } catch (RemoteException e) {
1694 throw e.rethrowFromSystemServer();
1695 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001696 LegacyRequest l = new LegacyRequest();
1697 l.networkCapabilities = netCap;
1698 l.delay = delay;
1699 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001700 l.networkRequest = sendRequestForNetwork(
1701 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001702 if (l.networkRequest == null) return null;
1703 sLegacyRequests.put(netCap, l);
1704 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1705 return l.networkRequest;
1706 }
1707
1708 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1709 if (delay >= 0) {
1710 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001711 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001712 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1713 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001714 }
1715 }
1716
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001717 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001718 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1719 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001720 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001721 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001722 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001723 if (l == null) return false;
1724 unregisterNetworkCallback(l.networkCallback);
1725 l.clearDnsBinding();
1726 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001727 }
1728
Erik Klinece55eb12017-01-26 18:08:28 +09001729 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1730 static {
1731 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1732 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1733 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1734 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1735 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1736 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1737 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1738 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1739 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1740 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1741 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1742 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1743 }
1744
1745 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1746 static {
1747 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1748 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1749 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1750 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1751 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1752 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1753 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1754 }
1755
1756 /**
1757 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1758 * instance suitable for registering a request or callback. Throws an
1759 * IllegalArgumentException if no mapping from the legacy type to
1760 * NetworkCapabilities is known.
1761 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001762 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1763 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001764 * @hide
1765 */
1766 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1767 final NetworkCapabilities nc = new NetworkCapabilities();
1768
1769 // Map from type to transports.
1770 final int NOT_FOUND = -1;
1771 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichibc1104b2017-05-09 15:19:01 +09001772 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001773 nc.addTransportType(transport);
1774
1775 // Map from type to capabilities.
1776 nc.addCapability(sLegacyTypeToCapability.get(
1777 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1778 nc.maybeMarkCapabilitiesRestricted();
1779 return nc;
1780 }
1781
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001782 /** @hide */
1783 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001784 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001785 public PacketKeepaliveCallback() {
1786 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001787 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001788 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001789 public void onStarted() {}
1790 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001791 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001792 public void onStopped() {}
1793 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001794 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001795 public void onError(int error) {}
1796 }
1797
1798 /**
1799 * Allows applications to request that the system periodically send specific packets on their
1800 * behalf, using hardware offload to save battery power.
1801 *
1802 * To request that the system send keepalives, call one of the methods that return a
1803 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1804 * passing in a non-null callback. If the callback is successfully started, the callback's
1805 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1806 * specifying one of the {@code ERROR_*} constants in this class.
1807 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001808 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1809 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1810 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001811 *
junyulai4c95b082018-12-27 17:25:29 +08001812 * @deprecated Use {@link SocketKeepalive} instead.
1813 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001814 * @hide
1815 */
1816 public class PacketKeepalive {
1817
1818 private static final String TAG = "PacketKeepalive";
1819
1820 /** @hide */
1821 public static final int SUCCESS = 0;
1822
1823 /** @hide */
1824 public static final int NO_KEEPALIVE = -1;
1825
1826 /** @hide */
1827 public static final int BINDER_DIED = -10;
1828
1829 /** The specified {@code Network} is not connected. */
1830 public static final int ERROR_INVALID_NETWORK = -20;
1831 /** The specified IP addresses are invalid. For example, the specified source IP address is
1832 * not configured on the specified {@code Network}. */
1833 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1834 /** The requested port is invalid. */
1835 public static final int ERROR_INVALID_PORT = -22;
1836 /** The packet length is invalid (e.g., too long). */
1837 public static final int ERROR_INVALID_LENGTH = -23;
1838 /** The packet transmission interval is invalid (e.g., too short). */
1839 public static final int ERROR_INVALID_INTERVAL = -24;
1840
1841 /** The hardware does not support this request. */
1842 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001843 /** The hardware returned an error. */
1844 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001845
Nathan Harold0990bc82018-02-14 13:09:45 -08001846 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001847 public static final int NATT_PORT = 4500;
1848
Nathan Harold0990bc82018-02-14 13:09:45 -08001849 /** The minimum interval in seconds between keepalive packet transmissions */
1850 public static final int MIN_INTERVAL = 10;
1851
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001852 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001853 private final ISocketKeepaliveCallback mCallback;
1854 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001855
1856 private volatile Integer mSlot;
1857
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001858 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001859 public void stop() {
1860 try {
junyulai070f9ff2019-01-16 20:23:34 +08001861 mExecutor.execute(() -> {
1862 try {
1863 if (mSlot != null) {
1864 mService.stopKeepalive(mNetwork, mSlot);
1865 }
1866 } catch (RemoteException e) {
1867 Log.e(TAG, "Error stopping packet keepalive: ", e);
1868 throw e.rethrowFromSystemServer();
1869 }
1870 });
1871 } catch (RejectedExecutionException e) {
1872 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001873 }
1874 }
1875
1876 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09001877 Preconditions.checkNotNull(network, "network cannot be null");
1878 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001879 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001880 mExecutor = Executors.newSingleThreadExecutor();
1881 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001882 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001883 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001884 final long token = Binder.clearCallingIdentity();
1885 try {
1886 mExecutor.execute(() -> {
1887 mSlot = slot;
1888 callback.onStarted();
1889 });
1890 } finally {
1891 Binder.restoreCallingIdentity(token);
1892 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001893 }
junyulai070f9ff2019-01-16 20:23:34 +08001894
1895 @Override
1896 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001897 final long token = Binder.clearCallingIdentity();
1898 try {
1899 mExecutor.execute(() -> {
1900 mSlot = null;
1901 callback.onStopped();
1902 });
1903 } finally {
1904 Binder.restoreCallingIdentity(token);
1905 }
junyulai070f9ff2019-01-16 20:23:34 +08001906 mExecutor.shutdown();
1907 }
1908
1909 @Override
1910 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001911 final long token = Binder.clearCallingIdentity();
1912 try {
1913 mExecutor.execute(() -> {
1914 mSlot = null;
1915 callback.onError(error);
1916 });
1917 } finally {
1918 Binder.restoreCallingIdentity(token);
1919 }
junyulai070f9ff2019-01-16 20:23:34 +08001920 mExecutor.shutdown();
1921 }
1922
1923 @Override
1924 public void onDataReceived() {
1925 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1926 // this callback when data is received.
1927 }
1928 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001929 }
1930 }
1931
1932 /**
1933 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1934 *
junyulai4c95b082018-12-27 17:25:29 +08001935 * @deprecated Use {@link #createSocketKeepalive} instead.
1936 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001937 * @hide
1938 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001939 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001940 public PacketKeepalive startNattKeepalive(
1941 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1942 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1943 final PacketKeepalive k = new PacketKeepalive(network, callback);
1944 try {
junyulai070f9ff2019-01-16 20:23:34 +08001945 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001946 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1947 } catch (RemoteException e) {
1948 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001949 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001950 }
1951 return k;
1952 }
1953
Chiachang Wang619319a2021-01-15 11:06:21 +08001954 // Construct an invalid fd.
1955 private ParcelFileDescriptor createInvalidFd() {
1956 final int invalidFd = -1;
1957 return ParcelFileDescriptor.adoptFd(invalidFd);
1958 }
1959
The Android Open Source Project28527d22009-03-03 19:31:44 -08001960 /**
junyulai4c95b082018-12-27 17:25:29 +08001961 * Request that keepalives be started on a IPsec NAT-T socket.
1962 *
1963 * @param network The {@link Network} the socket is on.
1964 * @param socket The socket that needs to be kept alive.
1965 * @param source The source address of the {@link UdpEncapsulationSocket}.
1966 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1967 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1968 * must run callback sequentially, otherwise the order of callbacks cannot be
1969 * guaranteed.
1970 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1971 * changes. Must be extended by applications that use this API.
1972 *
junyulai0835a1e2019-01-08 20:04:33 +08001973 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1974 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001975 **/
junyulai7e06ad42019-03-04 22:45:36 +08001976 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001977 @NonNull UdpEncapsulationSocket socket,
1978 @NonNull InetAddress source,
1979 @NonNull InetAddress destination,
1980 @NonNull @CallbackExecutor Executor executor,
1981 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001982 ParcelFileDescriptor dup;
1983 try {
junyulai828dad12019-03-27 11:00:37 +08001984 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1985 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001986 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1987 } catch (IOException ignored) {
1988 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1989 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001990 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001991 }
1992 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1993 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08001994 }
1995
1996 /**
1997 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1998 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1999 *
2000 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002001 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2002 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2003 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002004 * @param source The source address of the {@link UdpEncapsulationSocket}.
2005 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2006 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2007 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2008 * must run callback sequentially, otherwise the order of callbacks cannot be
2009 * guaranteed.
2010 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2011 * changes. Must be extended by applications that use this API.
2012 *
junyulai0835a1e2019-01-08 20:04:33 +08002013 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2014 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002015 * @hide
2016 */
2017 @SystemApi
2018 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002019 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2020 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002021 @NonNull InetAddress source,
2022 @NonNull InetAddress destination,
2023 @NonNull @CallbackExecutor Executor executor,
2024 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002025 ParcelFileDescriptor dup;
2026 try {
junyulai828dad12019-03-27 11:00:37 +08002027 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002028 dup = pfd.dup();
2029 } catch (IOException ignored) {
2030 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2031 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002032 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002033 }
2034 return new NattSocketKeepalive(mService, network, dup,
2035 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002036 }
2037
2038 /**
junyulai0835a1e2019-01-08 20:04:33 +08002039 * Request that keepalives be started on a TCP socket.
2040 * The socket must be established.
2041 *
2042 * @param network The {@link Network} the socket is on.
2043 * @param socket The socket that needs to be kept alive.
2044 * @param executor The executor on which callback will be invoked. This implementation assumes
2045 * the provided {@link Executor} runs the callbacks in sequence with no
2046 * concurrency. Failing this, no guarantee of correctness can be made. It is
2047 * the responsibility of the caller to ensure the executor provides this
2048 * guarantee. A simple way of creating such an executor is with the standard
2049 * tool {@code Executors.newSingleThreadExecutor}.
2050 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2051 * changes. Must be extended by applications that use this API.
2052 *
2053 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2054 * given socket.
2055 * @hide
2056 */
2057 @SystemApi
2058 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002059 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002060 @NonNull Socket socket,
2061 @NonNull Executor executor,
2062 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002063 ParcelFileDescriptor dup;
2064 try {
2065 dup = ParcelFileDescriptor.fromSocket(socket);
2066 } catch (UncheckedIOException ignored) {
2067 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2068 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002069 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002070 }
2071 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002072 }
2073
2074 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002075 * Ensure that a network route exists to deliver traffic to the specified
2076 * host via the specified network interface. An attempt to add a route that
2077 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002078 *
2079 * <p>This method requires the caller to hold either the
2080 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2081 * or the ability to modify system settings as determined by
2082 * {@link android.provider.Settings.System#canWrite}.</p>
2083 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002084 * @param networkType the type of the network over which traffic to the specified
2085 * host is to be routed
2086 * @param hostAddress the IP address of the host to which the route is desired
2087 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002088 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002089 * @deprecated Deprecated in favor of the
2090 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2091 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002092 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002093 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002094 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002095 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002096 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002097 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002098 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002099 }
2100
2101 /**
2102 * Ensure that a network route exists to deliver traffic to the specified
2103 * host via the specified network interface. An attempt to add a route that
2104 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002105 *
2106 * <p>This method requires the caller to hold either the
2107 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2108 * or the ability to modify system settings as determined by
2109 * {@link android.provider.Settings.System#canWrite}.</p>
2110 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002111 * @param networkType the type of the network over which traffic to the specified
2112 * host is to be routed
2113 * @param hostAddress the IP address of the host to which the route is desired
2114 * @return {@code true} on success, {@code false} on failure
2115 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002116 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002117 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002118 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002119 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002120 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002121 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002122 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002123 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002124 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2125 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002126 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002127 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002128 }
2129 }
2130
2131 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002132 * @return the context's attribution tag
2133 */
2134 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2135 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002136 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002137 }
2138
2139 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002140 * Returns the value of the setting for background data usage. If false,
2141 * applications should not use the network if the application is not in the
2142 * foreground. Developers should respect this setting, and check the value
2143 * of this before performing any background data operations.
2144 * <p>
2145 * All applications that have background services that use the network
2146 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002147 * <p>
Scott Main50589142011-10-06 18:32:43 -07002148 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002149 * background data depends on several combined factors, and this method will
2150 * always return {@code true}. Instead, when background data is unavailable,
2151 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002152 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002153 * @return Whether background data usage is allowed.
2154 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002155 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002156 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002157 // assume that background data is allowed; final authority is
2158 // NetworkInfo which may be blocked.
2159 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002160 }
2161
2162 /**
2163 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002164 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002165 * @param allowBackgroundData Whether an application should use data while
2166 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002167 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002168 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2169 * @see #getBackgroundDataSetting()
2170 * @hide
2171 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002172 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002173 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002175 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002176 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002177
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002178 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002179 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002180 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002181 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002182 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002183 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002184 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002185 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2186 if (tm != null) {
2187 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2188 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2189 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2190 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2191 + " retVal=" + retVal);
2192 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002193 }
Wink Saville689f7042014-12-05 11:10:30 -08002194 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002195 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002196 }
2197
The Android Open Source Project28527d22009-03-03 19:31:44 -08002198 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002199 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002200 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002201 */
2202 public interface OnNetworkActiveListener {
2203 /**
2204 * Called on the main thread of the process to report that the current data network
2205 * has become active, and it is now a good time to perform any pending network
2206 * operations. Note that this listener only tells you when the network becomes
2207 * active; if at any other time you want to know whether it is active (and thus okay
2208 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002209 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002210 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002211 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002212 }
2213
2214 private INetworkManagementService getNetworkManagementService() {
2215 synchronized (this) {
2216 if (mNMService != null) {
2217 return mNMService;
2218 }
2219 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2220 mNMService = INetworkManagementService.Stub.asInterface(b);
2221 return mNMService;
2222 }
2223 }
2224
2225 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002226 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002227
2228 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002229 * Start listening to reports when the system's default data network is active, meaning it is
2230 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2231 * to determine the current state of the system's default network after registering the
2232 * listener.
2233 * <p>
2234 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002235 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002236 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002237 *
2238 * @param l The listener to be told when the network is active.
2239 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002240 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002241 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2242 @Override
2243 public void onNetworkActive() throws RemoteException {
2244 l.onNetworkActive();
2245 }
2246 };
2247
2248 try {
2249 getNetworkManagementService().registerNetworkActivityListener(rl);
2250 mNetworkActivityListeners.put(l, rl);
2251 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002252 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002253 }
2254 }
2255
2256 /**
2257 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002258 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002259 *
2260 * @param l Previously registered listener.
2261 */
Chalard Jean158702d2019-01-07 19:26:34 +09002262 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002263 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichibc1104b2017-05-09 15:19:01 +09002264 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002265 try {
2266 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2267 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002268 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002269 }
2270 }
2271
2272 /**
2273 * Return whether the data network is currently active. An active network means that
2274 * it is currently in a high power state for performing data transmission. On some
2275 * types of networks, it may be expensive to move and stay in such a state, so it is
2276 * more power efficient to batch network traffic together when the radio is already in
2277 * this state. This method tells you whether right now is currently a good time to
2278 * initiate network traffic, as the network is already active.
2279 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002280 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002281 try {
2282 return getNetworkManagementService().isNetworkActive();
2283 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002284 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002285 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002286 }
2287
2288 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002289 * {@hide}
2290 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002291 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002292 mContext = Preconditions.checkNotNull(context, "missing context");
2293 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002294 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002295 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002296 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002297
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002298 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002299 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002300 public static ConnectivityManager from(Context context) {
2301 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2302 }
2303
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002304 /** @hide */
2305 public NetworkRequest getDefaultRequest() {
2306 try {
2307 // This is not racy as the default request is final in ConnectivityService.
2308 return mService.getDefaultRequest();
2309 } catch (RemoteException e) {
2310 throw e.rethrowFromSystemServer();
2311 }
2312 }
2313
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09002314 /* TODO: These permissions checks don't belong in client-side code. Move them to
2315 * services.jar, possibly in com.android.server.net. */
2316
2317 /** {@hide} */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002318 public static final void enforceChangePermission(Context context,
2319 String callingPkg, String callingAttributionTag) {
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002320 int uid = Binder.getCallingUid();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002321 checkAndNoteChangeNetworkStateOperation(context, uid, callingPkg,
2322 callingAttributionTag, true /* throwException */);
2323 }
2324
2325 /**
2326 * Check if the package is a allowed to change the network state. This also accounts that such
2327 * an access happened.
2328 *
2329 * @return {@code true} iff the package is allowed to change the network state.
2330 */
2331 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2332 private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context,
2333 int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag,
2334 boolean throwException) {
2335 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, callingPackage,
2336 throwException);
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002337 }
2338
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002339 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002340 * Check if the package is a allowed to write settings. This also accounts that such an access
2341 * happened.
2342 *
2343 * @return {@code true} iff the package is allowed to write settings.
2344 */
2345 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2346 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2347 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2348 boolean throwException) {
2349 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2350 throwException);
2351 }
2352
2353 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002354 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2355 * situations where a Context pointer is unavailable.
2356 * @hide
2357 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002358 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002359 static ConnectivityManager getInstanceOrNull() {
2360 return sInstance;
2361 }
2362
2363 /**
2364 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2365 * situations where a Context pointer is unavailable.
2366 * @hide
2367 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002368 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002369 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002370 private static ConnectivityManager getInstance() {
2371 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002372 throw new IllegalStateException("No ConnectivityManager yet constructed");
2373 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002374 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002375 }
2376
2377 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002378 * Get the set of tetherable, available interfaces. This list is limited by
2379 * device configuration and current interface existence.
2380 *
2381 * @return an array of 0 or more Strings of tetherable interface names.
2382 *
markchien6ae63e52020-01-21 13:11:06 +08002383 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002384 * {@hide}
2385 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002386 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002387 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002388 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002389 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002390 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002391 }
2392
2393 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002394 * Get the set of tethered interfaces.
2395 *
2396 * @return an array of 0 or more String of currently tethered interface names.
2397 *
markchien6ae63e52020-01-21 13:11:06 +08002398 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002399 * {@hide}
2400 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002401 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002402 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002403 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002404 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002405 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002406 }
2407
2408 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002409 * Get the set of interface names which attempted to tether but
2410 * failed. Re-attempting to tether may cause them to reset to the Tethered
2411 * state. Alternatively, causing the interface to be destroyed and recreated
2412 * may cause them to reset to the available state.
2413 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2414 * information on the cause of the errors.
2415 *
2416 * @return an array of 0 or more String indicating the interface names
2417 * which failed to tether.
2418 *
markchien6ae63e52020-01-21 13:11:06 +08002419 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002420 * {@hide}
2421 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002422 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002423 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002424 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002425 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002426 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002427 }
2428
2429 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002430 * Get the set of tethered dhcp ranges.
2431 *
markchien2e6ba522020-02-14 11:55:48 +08002432 * @deprecated This method is not supported.
2433 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002434 * {@hide}
2435 */
paulhu8e96a752019-08-12 16:25:11 +08002436 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002437 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002438 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002439 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002440 }
2441
2442 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002443 * Attempt to tether the named interface. This will setup a dhcp server
2444 * on the interface, forward and NAT IP packets and forward DNS requests
2445 * to the best active upstream network interface. Note that if no upstream
2446 * IP network interface is available, dhcp will still run and traffic will be
2447 * allowed between the tethered devices and this device, though upstream net
2448 * access will of course fail until an upstream network interface becomes
2449 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002450 *
2451 * <p>This method requires the caller to hold either the
2452 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2453 * or the ability to modify system settings as determined by
2454 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002455 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002456 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2457 * and WifiStateMachine which need direct access. All other clients should use
2458 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2459 * logic.</p>
2460 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002461 * @param iface the interface name to tether.
2462 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002463 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002464 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002465 * {@hide}
2466 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002467 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002468 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002469 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002470 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002471 }
2472
2473 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002474 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002475 *
2476 * <p>This method requires the caller to hold either the
2477 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2478 * or the ability to modify system settings as determined by
2479 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002480 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002481 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2482 * and WifiStateMachine which need direct access. All other clients should use
2483 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2484 * logic.</p>
2485 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002486 * @param iface the interface name to untether.
2487 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2488 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002489 * {@hide}
2490 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002491 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002492 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002493 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002494 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002495 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002496
2497 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002498 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002499 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002500 * due to device configuration.
2501 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002502 * <p>If this app does not have permission to use this API, it will always
2503 * return false rather than throw an exception.</p>
2504 *
2505 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2506 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2507 *
2508 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2509 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2510 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002511 * @return a boolean - {@code true} indicating Tethering is supported.
2512 *
markchien6ae63e52020-01-21 13:11:06 +08002513 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002514 * {@hide}
2515 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002516 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002517 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2518 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002519 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002520 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002521 }
2522
2523 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002524 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002525 *
2526 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002527 * @hide
2528 */
2529 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002530 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002531 public static abstract class OnStartTetheringCallback {
2532 /**
2533 * Called when tethering has been successfully started.
2534 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002535 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002536
2537 /**
2538 * Called when starting tethering failed.
2539 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002540 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002541 }
2542
2543 /**
2544 * Convenient overload for
2545 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2546 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002547 *
2548 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002549 * @hide
2550 */
2551 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002552 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002553 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002554 public void startTethering(int type, boolean showProvisioningUi,
2555 final OnStartTetheringCallback callback) {
2556 startTethering(type, showProvisioningUi, callback, null);
2557 }
2558
2559 /**
2560 * Runs tether provisioning for the given type if needed and then starts tethering if
2561 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2562 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2563 * schedules tether provisioning re-checks if appropriate.
2564 *
2565 * @param type The type of tethering to start. Must be one of
2566 * {@link ConnectivityManager.TETHERING_WIFI},
2567 * {@link ConnectivityManager.TETHERING_USB}, or
2568 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2569 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2570 * is one. This should be true the first time this function is called and also any time
2571 * the user can see this UI. It gives users information from their carrier about the
2572 * check failing and how they can sign up for tethering if possible.
2573 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2574 * of the result of trying to tether.
2575 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002576 *
2577 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002578 * @hide
2579 */
2580 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002581 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002582 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002583 public void startTethering(int type, boolean showProvisioningUi,
2584 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002585 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002586
markchien91c78e52020-01-20 19:31:56 +08002587 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002588 @Override
markchien91c78e52020-01-20 19:31:56 +08002589 public void execute(Runnable command) {
2590 if (handler == null) {
2591 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002592 } else {
markchien91c78e52020-01-20 19:31:56 +08002593 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002594 }
2595 }
2596 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002597
markchien91c78e52020-01-20 19:31:56 +08002598 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2599 @Override
2600 public void onTetheringStarted() {
2601 callback.onTetheringStarted();
2602 }
2603
2604 @Override
markchienf47d8342020-03-19 13:37:43 +08002605 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002606 callback.onTetheringFailed();
2607 }
2608 };
2609
2610 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002611 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002612
Amos Bianchia9b415a2020-03-04 11:07:38 -08002613 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002614 }
2615
2616 /**
2617 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2618 * applicable.
2619 *
2620 * @param type The type of tethering to stop. Must be one of
2621 * {@link ConnectivityManager.TETHERING_WIFI},
2622 * {@link ConnectivityManager.TETHERING_USB}, or
2623 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002624 *
2625 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002626 * @hide
2627 */
2628 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002629 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002630 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002631 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002632 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002633 }
2634
2635 /**
markchien4ef53e82019-02-27 14:56:11 +08002636 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2637 * upstream status.
2638 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002639 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002640 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002641 */
2642 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002643 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002644 public abstract static class OnTetheringEventCallback {
2645
2646 /**
2647 * Called when tethering upstream changed. This can be called multiple times and can be
2648 * called any time.
2649 *
2650 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2651 * have any upstream.
2652 */
2653 public void onUpstreamChanged(@Nullable Network network) {}
2654 }
2655
markchien6ae63e52020-01-21 13:11:06 +08002656 @GuardedBy("mTetheringEventCallbacks")
2657 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2658 mTetheringEventCallbacks = new ArrayMap<>();
2659
markchien4ef53e82019-02-27 14:56:11 +08002660 /**
2661 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002662 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002663 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2664 * with a null argument. The same callback object cannot be registered twice.
2665 *
2666 * @param executor the executor on which callback will be invoked.
2667 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002668 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002669 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002670 * @hide
2671 */
2672 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002673 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002674 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2675 public void registerTetheringEventCallback(
2676 @NonNull @CallbackExecutor Executor executor,
2677 @NonNull final OnTetheringEventCallback callback) {
2678 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2679
markchien6ae63e52020-01-21 13:11:06 +08002680 final TetheringEventCallback tetherCallback =
2681 new TetheringEventCallback() {
2682 @Override
2683 public void onUpstreamChanged(@Nullable Network network) {
2684 callback.onUpstreamChanged(network);
2685 }
2686 };
2687
2688 synchronized (mTetheringEventCallbacks) {
2689 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002690 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002691 }
markchien4ef53e82019-02-27 14:56:11 +08002692 }
2693
2694 /**
2695 * Remove tethering event callback previously registered with
2696 * {@link #registerTetheringEventCallback}.
2697 *
2698 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002699 *
2700 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002701 * @hide
2702 */
2703 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002704 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002705 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2706 public void unregisterTetheringEventCallback(
2707 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002708 Objects.requireNonNull(callback, "The callback must be non-null");
2709 synchronized (mTetheringEventCallbacks) {
2710 final TetheringEventCallback tetherCallback =
2711 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002712 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002713 }
markchien4ef53e82019-02-27 14:56:11 +08002714 }
2715
2716
2717 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002718 * Get the list of regular expressions that define any tetherable
2719 * USB network interfaces. If USB tethering is not supported by the
2720 * device, this list should be empty.
2721 *
2722 * @return an array of 0 or more regular expression Strings defining
2723 * what interfaces are considered tetherable usb interfaces.
2724 *
markchien6ae63e52020-01-21 13:11:06 +08002725 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002726 * {@hide}
2727 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002728 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002729 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002730 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002731 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002732 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002733 }
2734
2735 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002736 * Get the list of regular expressions that define any tetherable
2737 * Wifi network interfaces. If Wifi tethering is not supported by the
2738 * device, this list should be empty.
2739 *
2740 * @return an array of 0 or more regular expression Strings defining
2741 * what interfaces are considered tetherable wifi interfaces.
2742 *
markchien6ae63e52020-01-21 13:11:06 +08002743 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002744 * {@hide}
2745 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002746 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002747 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002748 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002749 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002750 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002751 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002752
Danica Chang96567052010-08-11 14:54:43 -07002753 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002754 * Get the list of regular expressions that define any tetherable
2755 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2756 * device, this list should be empty.
2757 *
2758 * @return an array of 0 or more regular expression Strings defining
2759 * what interfaces are considered tetherable bluetooth interfaces.
2760 *
markchien6ae63e52020-01-21 13:11:06 +08002761 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2762 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002763 * {@hide}
2764 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002765 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002766 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002767 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002768 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002769 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002770 }
2771
Mike Lockwooded4a1742011-07-19 13:04:47 -07002772 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002773 * Attempt to both alter the mode of USB and Tethering of USB. A
2774 * utility method to deal with some of the complexity of USB - will
2775 * attempt to switch to Rndis and subsequently tether the resulting
2776 * interface on {@code true} or turn off tethering and switch off
2777 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002778 *
2779 * <p>This method requires the caller to hold either the
2780 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2781 * or the ability to modify system settings as determined by
2782 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002783 *
2784 * @param enable a boolean - {@code true} to enable tethering
2785 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002786 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002787 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002788 * {@hide}
2789 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002790 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002791 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002792 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002793 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002794 }
2795
markchien6ae63e52020-01-21 13:11:06 +08002796 /**
2797 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2798 * {@hide}
2799 */
markchien0f45bb92019-01-16 17:44:13 +08002800 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002801 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002802 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002803 /**
2804 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2805 * {@hide}
2806 */
2807 @Deprecated
2808 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2809 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2810 /**
2811 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2812 * {@hide}
2813 */
2814 @Deprecated
2815 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2816 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2817 /**
2818 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2819 * {@hide}
2820 */
2821 @Deprecated
2822 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2823 /**
2824 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2825 * {@hide}
2826 */
2827 @Deprecated
2828 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2829 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2830 /**
markchienf47d8342020-03-19 13:37:43 +08002831 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002832 * {@hide}
2833 */
2834 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002835 public static final int TETHER_ERROR_MASTER_ERROR =
2836 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002837 /**
2838 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2839 * {@hide}
2840 */
2841 @Deprecated
2842 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2843 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2844 /**
2845 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2846 * {@hide}
2847 */
2848 @Deprecated
2849 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2850 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2851 /**
markchienf47d8342020-03-19 13:37:43 +08002852 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002853 * {@hide}
2854 */
2855 @Deprecated
2856 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002857 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002858 /**
markchienf47d8342020-03-19 13:37:43 +08002859 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002860 * {@hide}
2861 */
2862 @Deprecated
2863 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002864 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002865 /**
2866 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2867 * {@hide}
2868 */
2869 @Deprecated
2870 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2871 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2872 /**
markchienf47d8342020-03-19 13:37:43 +08002873 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002874 * {@hide}
2875 */
markchien0f45bb92019-01-16 17:44:13 +08002876 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002877 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002878 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002879 /**
2880 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2881 * {@hide}
2882 */
2883 @Deprecated
2884 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2885 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2886 /**
2887 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2888 * {@hide}
2889 */
markchien0f45bb92019-01-16 17:44:13 +08002890 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002891 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002892 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002893
2894 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002895 * Get a more detailed error code after a Tethering or Untethering
2896 * request asynchronously failed.
2897 *
2898 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002899 * @return error The error code of the last error tethering or untethering the named
2900 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002901 *
markchien6ae63e52020-01-21 13:11:06 +08002902 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002903 * {@hide}
2904 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002905 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002906 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002907 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002908 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002909 int error = mTetheringManager.getLastTetherError(iface);
2910 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2911 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2912 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2913 // instead.
2914 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2915 }
2916 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002917 }
2918
markchienbf5ab012019-03-06 16:25:00 +08002919 /** @hide */
2920 @Retention(RetentionPolicy.SOURCE)
2921 @IntDef(value = {
2922 TETHER_ERROR_NO_ERROR,
2923 TETHER_ERROR_PROVISION_FAILED,
2924 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2925 })
2926 public @interface EntitlementResultCode {
2927 }
2928
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002929 /**
markchienbf5ab012019-03-06 16:25:00 +08002930 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002931 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002932 *
2933 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002934 * @hide
2935 */
2936 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002937 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002938 public interface OnTetheringEntitlementResultListener {
2939 /**
2940 * Called to notify entitlement result.
2941 *
2942 * @param resultCode an int value of entitlement result. It may be one of
2943 * {@link #TETHER_ERROR_NO_ERROR},
2944 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2945 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2946 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002947 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002948 }
2949
2950 /**
markchien0f45bb92019-01-16 17:44:13 +08002951 * Get the last value of the entitlement check on this downstream. If the cached value is
2952 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2953 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2954 * guaranteed that the UI-based entitlement check will complete in any specific time period
2955 * and may in fact never complete. Any successful entitlement check the platform performs for
2956 * any reason will update the cached value.
2957 *
2958 * @param type the downstream type of tethering. Must be one of
2959 * {@link #TETHERING_WIFI},
2960 * {@link #TETHERING_USB}, or
2961 * {@link #TETHERING_BLUETOOTH}.
2962 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002963 * @param executor the executor on which callback will be invoked.
2964 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2965 * notify the caller of the result of entitlement check. The listener may be called zero
2966 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002967 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002968 * {@hide}
2969 */
2970 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002971 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002972 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002973 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2974 @NonNull @CallbackExecutor Executor executor,
2975 @NonNull final OnTetheringEntitlementResultListener listener) {
2976 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2977 ResultReceiver wrappedListener = new ResultReceiver(null) {
2978 @Override
2979 protected void onReceiveResult(int resultCode, Bundle resultData) {
2980 Binder.withCleanCallingIdentity(() ->
2981 executor.execute(() -> {
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002982 listener.onTetheringEntitlementResult(resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002983 }));
2984 }
2985 };
2986
Amos Bianchia9b415a2020-03-04 11:07:38 -08002987 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002988 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002989 }
2990
2991 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002992 * Report network connectivity status. This is currently used only
2993 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002994 * <p>This method requires the caller to hold the permission
2995 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002996 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002997 * @param networkType The type of network you want to report on
2998 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002999 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003000 * {@hide}
3001 */
3002 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003003 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003004 try {
3005 mService.reportInetCondition(networkType, percentage);
3006 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003007 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003008 }
3009 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003010
3011 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003012 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003013 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003014 * the framework to re-evaluate network connectivity and/or switch to another
3015 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003016 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003017 * @param network The {@link Network} the application was attempting to use
3018 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003019 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3020 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003021 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003022 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003023 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003024 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003025 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003026 // One of these will be ignored because it matches system's current state.
3027 // The other will trigger the necessary reevaluation.
3028 mService.reportNetworkConnectivity(network, true);
3029 mService.reportNetworkConnectivity(network, false);
3030 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003031 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003032 }
3033 }
3034
3035 /**
3036 * Report to the framework whether a network has working connectivity.
3037 * This provides a hint to the system that a particular network is providing
3038 * working connectivity or not. In response the framework may re-evaluate
3039 * the network's connectivity and might take further action thereafter.
3040 *
3041 * @param network The {@link Network} the application was attempting to use
3042 * or {@code null} to indicate the current default network.
3043 * @param hasConnectivity {@code true} if the application was able to successfully access the
3044 * Internet using {@code network} or {@code false} if not.
3045 */
Chalard Jean158702d2019-01-07 19:26:34 +09003046 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003047 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003048 try {
3049 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003050 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003051 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003052 }
3053 }
3054
3055 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003056 * Set a network-independent global http proxy. This is not normally what you want
3057 * for typical HTTP proxies - they are general network dependent. However if you're
3058 * doing something unusual like general internal filtering this may be useful. On
3059 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003060 *
3061 * @param p A {@link ProxyInfo} object defining the new global
3062 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003063 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003064 */
paulhu8e96a752019-08-12 16:25:11 +08003065 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04003066 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003067 try {
3068 mService.setGlobalProxy(p);
3069 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003070 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003071 }
3072 }
3073
3074 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003075 * Retrieve any network-independent global HTTP proxy.
3076 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003077 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003078 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003079 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003080 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003081 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003082 try {
3083 return mService.getGlobalProxy();
3084 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003085 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003086 }
3087 }
3088
3089 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003090 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3091 * network-specific HTTP proxy. If {@code network} is null, the
3092 * network-specific proxy returned is the proxy of the default active
3093 * network.
3094 *
3095 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3096 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3097 * or when {@code network} is {@code null},
3098 * the {@code ProxyInfo} for the default active network. Returns
3099 * {@code null} when no proxy applies or the caller doesn't have
3100 * permission to use {@code network}.
3101 * @hide
3102 */
3103 public ProxyInfo getProxyForNetwork(Network network) {
3104 try {
3105 return mService.getProxyForNetwork(network);
3106 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003107 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003108 }
3109 }
3110
3111 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003112 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3113 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003114 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003115 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003116 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003117 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003118 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003119 */
Chalard Jean158702d2019-01-07 19:26:34 +09003120 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003121 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003122 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003123 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003124
3125 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003126 * Returns true if the hardware supports the given network type
3127 * else it returns false. This doesn't indicate we have coverage
3128 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003129 * hardware supports it. For example a GSM phone without a SIM
3130 * should still return {@code true} for mobile data, but a wifi only
3131 * tablet would return {@code false}.
3132 *
3133 * @param networkType The network type we'd like to check
3134 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003135 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003136 * @hide
3137 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003138 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003139 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003140 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003141 public boolean isNetworkSupported(int networkType) {
3142 try {
3143 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003144 } catch (RemoteException e) {
3145 throw e.rethrowFromSystemServer();
3146 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003147 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003148
3149 /**
3150 * Returns if the currently active data network is metered. A network is
3151 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003152 * that connection due to monetary costs, data limitations or
3153 * battery/performance issues. You should check this before doing large
3154 * data transfers, and warn the user or delay the operation until another
3155 * network is available.
3156 *
3157 * @return {@code true} if large transfers should be avoided, otherwise
3158 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003159 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003160 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003161 public boolean isActiveNetworkMetered() {
3162 try {
3163 return mService.isActiveNetworkMetered();
3164 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003165 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003166 }
3167 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003168
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003169 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09003170 * Calls VpnManager#updateLockdownVpn.
3171 * @deprecated TODO: remove when callers have migrated to VpnManager.
3172 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003173 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09003174 @Deprecated
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003175 public boolean updateLockdownVpn() {
Lorenzo Colitticd675292021-02-04 17:32:07 +09003176 return getVpnManager().updateLockdownVpn();
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003177 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07003178
3179 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003180 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003181 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003182 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003183 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003184 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003185 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003186 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003187 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003188 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003189 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003190 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003191 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003192 }
3193 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003194
3195 /**
3196 * Set the value for enabling/disabling airplane mode
3197 *
3198 * @param enable whether to enable airplane mode or not
3199 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003200 * @hide
3201 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003202 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003203 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003204 android.Manifest.permission.NETWORK_SETTINGS,
3205 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3206 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003207 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003208 public void setAirplaneMode(boolean enable) {
3209 try {
3210 mService.setAirplaneMode(enable);
3211 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003212 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003213 }
3214 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003215
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003216 /**
3217 * Registers the specified {@link NetworkProvider}.
3218 * Each listener must only be registered once. The listener can be unregistered with
3219 * {@link #unregisterNetworkProvider}.
3220 *
3221 * @param provider the provider to register
3222 * @return the ID of the provider. This ID must be used by the provider when registering
3223 * {@link android.net.NetworkAgent}s.
3224 * @hide
3225 */
3226 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003227 @RequiresPermission(anyOf = {
3228 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3229 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003230 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3231 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003232 throw new IllegalStateException("NetworkProviders can only be registered once");
3233 }
3234
3235 try {
3236 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3237 provider.getName());
3238 provider.setProviderId(providerId);
3239 } catch (RemoteException e) {
3240 throw e.rethrowFromSystemServer();
3241 }
3242 return provider.getProviderId();
3243 }
3244
3245 /**
3246 * Unregisters the specified NetworkProvider.
3247 *
3248 * @param provider the provider to unregister
3249 * @hide
3250 */
3251 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003252 @RequiresPermission(anyOf = {
3253 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3254 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003255 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3256 try {
3257 mService.unregisterNetworkProvider(provider.getMessenger());
3258 } catch (RemoteException e) {
3259 throw e.rethrowFromSystemServer();
3260 }
3261 provider.setProviderId(NetworkProvider.ID_NONE);
3262 }
3263
3264
3265 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003266 @RequiresPermission(anyOf = {
3267 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3268 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003269 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3270 try {
3271 mService.declareNetworkRequestUnfulfillable(request);
3272 } catch (RemoteException e) {
3273 throw e.rethrowFromSystemServer();
3274 }
3275 }
3276
Chalard Jean29d06db2018-05-02 21:14:54 +09003277 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3278 // of dependent changes that would conflict throughout the automerger graph. Having this
3279 // temporarily helps with the process of going through with all these dependent changes across
3280 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003281 /**
3282 * @hide
3283 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003284 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003285 */
paulhub6ba8e82020-03-04 09:43:41 +08003286 @RequiresPermission(anyOf = {
3287 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3288 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003289 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003290 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003291 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003292 }
3293
3294 /**
3295 * @hide
3296 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003297 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003298 */
paulhub6ba8e82020-03-04 09:43:41 +08003299 @RequiresPermission(anyOf = {
3300 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3301 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003302 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003303 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003304 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003305 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003306 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003307 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003308 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003309 }
3310
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003311 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003312 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3313 * changes. Should be extended by applications wanting notifications.
3314 *
3315 * A {@code NetworkCallback} is registered by calling
3316 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3317 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003318 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003319 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3320 * A {@code NetworkCallback} should be registered at most once at any time.
3321 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003322 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003323 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003324 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003325 * Called when the framework connects to a new network to evaluate whether it satisfies this
3326 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3327 * callback. There is no guarantee that this new network will satisfy any requests, or that
3328 * the network will stay connected for longer than the time necessary to evaluate it.
3329 * <p>
3330 * Most applications <b>should not</b> act on this callback, and should instead use
3331 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3332 * the framework in properly evaluating the network &mdash; for example, an application that
3333 * can automatically log in to a captive portal without user intervention.
3334 *
3335 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003336 *
3337 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003338 */
paulhu1a407652019-03-22 16:35:06 +08003339 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003340
3341 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003342 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003343 * This callback may be called more than once if the {@link Network} that is
3344 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003345 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003346 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003347 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3348 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003349 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003350 * @hide
3351 */
paulhu1a407652019-03-22 16:35:06 +08003352 public void onAvailable(@NonNull Network network,
3353 @NonNull NetworkCapabilities networkCapabilities,
3354 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003355 // Internally only this method is called when a new network is available, and
3356 // it calls the callback in the same way and order that older versions used
3357 // to call so as not to change the behavior.
3358 onAvailable(network);
3359 if (!networkCapabilities.hasCapability(
3360 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3361 onNetworkSuspended(network);
3362 }
3363 onCapabilitiesChanged(network, networkCapabilities);
3364 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003365 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003366 }
3367
3368 /**
3369 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003370 *
3371 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3372 * be available at the same time, and onAvailable will be called for each of these as they
3373 * appear.
3374 *
3375 * <p>For callbacks registered with {@link #requestNetwork} and
3376 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3377 * is the new best network for this request and is now tracked by this callback ; this
3378 * callback will no longer receive method calls about other networks that may have been
3379 * passed to this method previously. The previously-best network may have disconnected, or
3380 * it may still be around and the newly-best network may simply be better.
3381 *
3382 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3383 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3384 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3385 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3386 *
3387 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3388 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3389 * this callback as this is prone to race conditions (there is no guarantee the objects
3390 * returned by these methods will be current). Instead, wait for a call to
3391 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3392 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3393 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003394 *
3395 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003396 */
paulhu1a407652019-03-22 16:35:06 +08003397 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003398
3399 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003400 * Called when the network is about to be lost, typically because there are no outstanding
3401 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3402 * with the new replacement network for graceful handover. This method is not guaranteed
3403 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3404 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003405 *
Chalard Jean01378b62019-08-30 16:27:28 +09003406 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3407 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3408 * this callback as this is prone to race conditions ; calling these methods while in a
3409 * callback may return an outdated or even a null object.
3410 *
3411 * @param network The {@link Network} that is about to be lost.
3412 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3413 * connected for graceful handover; note that the network may still
3414 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003415 */
paulhu1a407652019-03-22 16:35:06 +08003416 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003417
3418 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003419 * Called when a network disconnects or otherwise no longer satisfies this request or
3420 * callback.
3421 *
3422 * <p>If the callback was registered with requestNetwork() or
3423 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3424 * returned by onAvailable() when that network is lost and no other network satisfies
3425 * the criteria of the request.
3426 *
3427 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3428 * each network which no longer satisfies the criteria of the callback.
3429 *
3430 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3431 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3432 * this callback as this is prone to race conditions ; calling these methods while in a
3433 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003434 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003435 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003436 */
paulhu1a407652019-03-22 16:35:06 +08003437 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003438
3439 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003440 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003441 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3442 * requested network request cannot be fulfilled (whether or not a timeout was
3443 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003444 * {@link NetworkRequest} will have already been removed and released, as if
3445 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003446 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003447 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003448
3449 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003450 * Called when the network corresponding to this request changes capabilities but still
3451 * satisfies the requested criteria.
3452 *
3453 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3454 * to be called immediately after {@link #onAvailable}.
3455 *
3456 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3457 * ConnectivityManager methods in this callback as this is prone to race conditions :
3458 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003459 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003460 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003461 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3462 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003463 */
paulhu1a407652019-03-22 16:35:06 +08003464 public void onCapabilitiesChanged(@NonNull Network network,
3465 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003466
3467 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003468 * Called when the network corresponding to this request changes {@link LinkProperties}.
3469 *
3470 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3471 * to be called immediately after {@link #onAvailable}.
3472 *
3473 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3474 * ConnectivityManager methods in this callback as this is prone to race conditions :
3475 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003476 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003477 * @param network The {@link Network} whose link properties have changed.
3478 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003479 */
paulhu1a407652019-03-22 16:35:06 +08003480 public void onLinkPropertiesChanged(@NonNull Network network,
3481 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003482
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003483 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003484 * Called when the network the framework connected to for this request suspends data
3485 * transmission temporarily.
3486 *
3487 * <p>This generally means that while the TCP connections are still live temporarily
3488 * network data fails to transfer. To give a specific example, this is used on cellular
3489 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3490 * means read operations on sockets on this network will block once the buffers are
3491 * drained, and write operations will block once the buffers are full.
3492 *
3493 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3494 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3495 * this callback as this is prone to race conditions (there is no guarantee the objects
3496 * returned by these methods will be current).
3497 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003498 * @hide
3499 */
paulhu1a407652019-03-22 16:35:06 +08003500 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003501
3502 /**
3503 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003504 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3505 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003506
3507 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3508 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3509 * this callback as this is prone to race conditions : calling these methods while in a
3510 * callback may return an outdated or even a null object.
3511 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003512 * @hide
3513 */
paulhu1a407652019-03-22 16:35:06 +08003514 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003515
junyulaif2c67e42018-08-07 19:50:45 +08003516 /**
3517 * Called when access to the specified network is blocked or unblocked.
3518 *
Chalard Jean01378b62019-08-30 16:27:28 +09003519 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3520 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3521 * this callback as this is prone to race conditions : calling these methods while in a
3522 * callback may return an outdated or even a null object.
3523 *
junyulaif2c67e42018-08-07 19:50:45 +08003524 * @param network The {@link Network} whose blocked status has changed.
3525 * @param blocked The blocked status of this {@link Network}.
3526 */
junyulai7e06ad42019-03-04 22:45:36 +08003527 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003528
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003529 private NetworkRequest networkRequest;
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) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003606 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);
junyulaiad010792021-01-11 16:53:38 +08003704 Preconditions.checkArgument(
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09003705 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();
junyulaiad010792021-01-11 16:53:38 +08003719 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003720 request = mService.listenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003721 need, messenger, binder, callingPackageName,
3722 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003723 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003724 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003725 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3726 callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003727 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003728 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003729 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003730 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003731 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003732 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003733 } catch (RemoteException e) {
3734 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003735 } catch (ServiceSpecificException e) {
3736 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003737 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003738 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003739 }
3740
3741 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003742 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003743 *
markchienfac84a22020-03-18 21:16:15 +08003744 * This API is only for use in internal system code that requests networks with legacy type and
3745 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003746 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003747 *
markchiend6eeffd2020-01-14 00:55:21 +08003748 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003749 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3750 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3751 * be a positive value (i.e. >0).
3752 * @param legacyType to specify the network type(#TYPE_*).
3753 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003754 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3755 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003756 *
3757 * @hide
3758 */
markchiend6eeffd2020-01-14 00:55:21 +08003759 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003760 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003761 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003762 int timeoutMs, int legacyType, @NonNull Handler handler,
3763 @NonNull NetworkCallback networkCallback) {
3764 if (legacyType == TYPE_NONE) {
3765 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3766 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003767 CallbackHandler cbHandler = new CallbackHandler(handler);
3768 NetworkCapabilities nc = request.networkCapabilities;
3769 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003770 }
3771
3772 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003773 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003774 *
Chalard Jean01378b62019-08-30 16:27:28 +09003775 * <p>This method will attempt to find the best network that matches the passed
3776 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3777 * criteria. The platform will evaluate which network is the best at its own discretion.
3778 * Throughput, latency, cost per byte, policy, user preference and other considerations
3779 * may be factored in the decision of what is considered the best network.
3780 *
3781 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3782 * matching this request, while always attempting to match the request to a better network if
3783 * possible. If a better match is found, the platform will switch this request to the now-best
3784 * network and inform the app of the newly best network by invoking
3785 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3786 * will not try to maintain any other network than the best one currently matching the request:
3787 * a network not matching any network request may be disconnected at any time.
3788 *
3789 * <p>For example, an application could use this method to obtain a connected cellular network
3790 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3791 * radio to consume additional power. Or, an application could inform the system that it wants
3792 * a network supporting sending MMSes and have the system let it know about the currently best
3793 * MMS-supporting network through the provided {@link NetworkCallback}.
3794 *
3795 * <p>The status of the request can be followed by listening to the various callbacks described
3796 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3797 * used to direct traffic to the network (although accessing some networks may be subject to
3798 * holding specific permissions). Callers will learn about the specific characteristics of the
3799 * network through
3800 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3801 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3802 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3803 * matching the request at any given time; therefore when a better network matching the request
3804 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3805 * with the new network after which no further updates are given about the previously-best
3806 * network, unless it becomes the best again at some later time. All callbacks are invoked
3807 * in order on the same thread, which by default is a thread created by the framework running
3808 * in the app.
3809 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3810 * callbacks are invoked.
3811 *
3812 * <p>This{@link NetworkRequest} will live until released via
3813 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3814 * which point the system may let go of the network at any time.
3815 *
3816 * <p>A version of this method which takes a timeout is
3817 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3818 * wait for a limited amount of time for the network to become unavailable.
3819 *
Paul Jensenee52d232015-06-16 15:11:58 -04003820 * <p>It is presently unsupported to request a network with mutable
3821 * {@link NetworkCapabilities} such as
3822 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3823 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3824 * as these {@code NetworkCapabilities} represent states that a particular
3825 * network may never attain, and whether a network will attain these states
3826 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003827 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003828 *
3829 * <p>This method requires the caller to hold either the
3830 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3831 * or the ability to modify system settings as determined by
3832 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003833 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003834 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3835 * number of outstanding requests to 100 per app (identified by their UID), shared with
3836 * all variants of this method, of {@link #registerNetworkCallback} as well as
3837 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3838 * Requesting a network with this method will count toward this limit. If this limit is
3839 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3840 * make sure to unregister the callbacks with
3841 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3842 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003843 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003844 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3845 * the callback must not be shared - it uniquely specifies this request.
3846 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003847 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3848 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003849 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003850 */
Chalard Jean158702d2019-01-07 19:26:34 +09003851 public void requestNetwork(@NonNull NetworkRequest request,
3852 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003853 requestNetwork(request, networkCallback, getDefaultHandler());
3854 }
3855
3856 /**
3857 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3858 *
Chalard Jean01378b62019-08-30 16:27:28 +09003859 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3860 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003861 *
Chalard Jean01378b62019-08-30 16:27:28 +09003862 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003863 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3864 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003865 *
3866 * @param request {@link NetworkRequest} describing this request.
3867 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3868 * the callback must not be shared - it uniquely specifies this request.
3869 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003870 */
Chalard Jean158702d2019-01-07 19:26:34 +09003871 public void requestNetwork(@NonNull NetworkRequest request,
3872 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003873 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003874 NetworkCapabilities nc = request.networkCapabilities;
3875 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003876 }
3877
3878 /**
Etan Cohenf67bde92017-03-01 12:47:28 -08003879 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3880 * by a timeout.
3881 *
3882 * This function behaves identically to the non-timed-out version
3883 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3884 * is not found within the given time (in milliseconds) the
3885 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3886 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3887 * not have to be released if timed-out (it is automatically released). Unregistering a
3888 * request that timed out is not an error.
3889 *
3890 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3891 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3892 * for that purpose. Calling this method will attempt to bring up the requested network.
3893 *
Chalard Jean01378b62019-08-30 16:27:28 +09003894 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003895 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3896 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003897 *
3898 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003899 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3900 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003901 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3902 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3903 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003904 */
Chalard Jean158702d2019-01-07 19:26:34 +09003905 public void requestNetwork(@NonNull NetworkRequest request,
3906 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003907 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003908 NetworkCapabilities nc = request.networkCapabilities;
3909 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3910 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003911 }
3912
Hugo Benichifd44e912017-02-02 17:02:36 +09003913 /**
3914 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3915 * by a timeout.
3916 *
Chalard Jean01378b62019-08-30 16:27:28 +09003917 * This method behaves identically to
3918 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3919 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003920 *
Chalard Jean01378b62019-08-30 16:27:28 +09003921 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003922 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3923 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003924 *
3925 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003926 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3927 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003928 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003929 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3930 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003931 */
Chalard Jean158702d2019-01-07 19:26:34 +09003932 public void requestNetwork(@NonNull NetworkRequest request,
3933 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003934 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003935 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003936 NetworkCapabilities nc = request.networkCapabilities;
3937 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003938 }
3939
3940 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003941 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003942 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003943 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003944 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003945 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3946 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003947 */
Erik Kline8a826212014-11-19 12:12:24 +09003948 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003949
3950 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003951 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003952 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003953 * {@link android.content.Intent#getParcelableExtra(String)}.
3954 */
Erik Kline8a826212014-11-19 12:12:24 +09003955 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003956
3957
3958 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003959 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003960 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003961 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003962 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003963 * the request may outlive the calling application and get called back when a suitable
3964 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003965 * <p>
3966 * The operation is an Intent broadcast that goes to a broadcast receiver that
3967 * you registered with {@link Context#registerReceiver} or through the
3968 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3969 * <p>
3970 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003971 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3972 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003973 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003974 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003975 * Intent to reserve the network or it will be released shortly after the Intent
3976 * is processed.
3977 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003978 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003979 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003980 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003981 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003982 * The request may be released normally by calling
3983 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003984 * <p>It is presently unsupported to request a network with either
3985 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3986 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3987 * as these {@code NetworkCapabilities} represent states that a particular
3988 * network may never attain, and whether a network will attain these states
3989 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003990 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003991 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003992 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3993 * number of outstanding requests to 100 per app (identified by their UID), shared with
3994 * all variants of this method, of {@link #registerNetworkCallback} as well as
3995 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3996 * Requesting a network with this method will count toward this limit. If this limit is
3997 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3998 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3999 * or {@link #releaseNetworkRequest(PendingIntent)}.
4000 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004001 * <p>This method requires the caller to hold either the
4002 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4003 * or the ability to modify system settings as determined by
4004 * {@link android.provider.Settings.System#canWrite}.</p>
4005 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004006 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004007 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004008 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004009 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004010 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4011 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004012 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004013 */
Chalard Jean158702d2019-01-07 19:26:34 +09004014 public void requestNetwork(@NonNull NetworkRequest request,
4015 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004016 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004017 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004018 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004019 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004020 request.networkCapabilities, operation, mContext.getOpPackageName(),
4021 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004022 } catch (RemoteException e) {
4023 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004024 } catch (ServiceSpecificException e) {
4025 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004026 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004027 }
4028
4029 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004030 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4031 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004032 * This method has the same behavior as
4033 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004034 * releasing network resources and disconnecting.
4035 *
4036 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4037 * PendingIntent passed to
4038 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4039 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4040 */
Chalard Jean158702d2019-01-07 19:26:34 +09004041 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004042 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004043 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004044 try {
4045 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004046 } catch (RemoteException e) {
4047 throw e.rethrowFromSystemServer();
4048 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004049 }
4050
Hugo Benichibc1104b2017-05-09 15:19:01 +09004051 private static void checkPendingIntentNotNull(PendingIntent intent) {
4052 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4053 }
4054
4055 private static void checkCallbackNotNull(NetworkCallback callback) {
4056 Preconditions.checkNotNull(callback, "null NetworkCallback");
4057 }
4058
4059 private static void checkTimeout(int timeoutMs) {
4060 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004061 }
4062
4063 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004064 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004065 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004066 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4067 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004068 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004069 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4070 * number of outstanding requests to 100 per app (identified by their UID), shared with
4071 * all variants of this method, of {@link #requestNetwork} as well as
4072 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4073 * Requesting a network with this method will count toward this limit. If this limit is
4074 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4075 * make sure to unregister the callbacks with
4076 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4077 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004078 * @param request {@link NetworkRequest} describing this request.
4079 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4080 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004081 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004082 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004083 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004084 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004085 public void registerNetworkCallback(@NonNull NetworkRequest request,
4086 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004087 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4088 }
4089
4090 /**
4091 * Registers to receive notifications about all networks which satisfy the given
4092 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004093 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4094 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004095 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004096 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4097 * number of outstanding requests to 100 per app (identified by their UID), shared with
4098 * all variants of this method, of {@link #requestNetwork} as well as
4099 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4100 * Requesting a network with this method will count toward this limit. If this limit is
4101 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4102 * make sure to unregister the callbacks with
4103 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4104 *
4105 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004106 * @param request {@link NetworkRequest} describing this request.
4107 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4108 * networks change state.
4109 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004110 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004111 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004112 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004113 public void registerNetworkCallback(@NonNull NetworkRequest request,
4114 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004115 CallbackHandler cbHandler = new CallbackHandler(handler);
4116 NetworkCapabilities nc = request.networkCapabilities;
4117 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004118 }
4119
4120 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004121 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4122 * {@link NetworkRequest}.
4123 *
4124 * This function behaves identically to the version that takes a NetworkCallback, but instead
4125 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4126 * the request may outlive the calling application and get called back when a suitable
4127 * network is found.
4128 * <p>
4129 * The operation is an Intent broadcast that goes to a broadcast receiver that
4130 * you registered with {@link Context#registerReceiver} or through the
4131 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4132 * <p>
4133 * The operation Intent is delivered with two extras, a {@link Network} typed
4134 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4135 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4136 * the original requests parameters.
4137 * <p>
4138 * If there is already a request for this Intent registered (with the equality of
4139 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4140 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4141 * <p>
4142 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004143 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004144 *
4145 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4146 * number of outstanding requests to 100 per app (identified by their UID), shared with
4147 * all variants of this method, of {@link #requestNetwork} as well as
4148 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4149 * Requesting a network with this method will count toward this limit. If this limit is
4150 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4151 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4152 * or {@link #releaseNetworkRequest(PendingIntent)}.
4153 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004154 * @param request {@link NetworkRequest} describing this request.
4155 * @param operation Action to perform when the network is available (corresponds
4156 * to the {@link NetworkCallback#onAvailable} call. Typically
4157 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004158 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004159 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004160 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004161 public void registerNetworkCallback(@NonNull NetworkRequest request,
4162 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004163 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004164 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004165 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004166 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004167 request.networkCapabilities, operation, mContext.getOpPackageName(),
4168 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004169 } catch (RemoteException e) {
4170 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004171 } catch (ServiceSpecificException e) {
4172 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004173 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004174 }
4175
4176 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004177 * Registers to receive notifications about changes in the application's default network. This
4178 * may be a physical network or a virtual network, such as a VPN that applies to the
4179 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004180 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004181 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004182 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4183 * number of outstanding requests to 100 per app (identified by their UID), shared with
4184 * all variants of this method, of {@link #requestNetwork} as well as
4185 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4186 * Requesting a network with this method will count toward this limit. If this limit is
4187 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4188 * make sure to unregister the callbacks with
4189 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4190 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004191 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004192 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004193 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004194 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004195 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004196 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004197 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004198 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4199 }
4200
4201 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004202 * Registers to receive notifications about changes in the application's default network. This
4203 * may be a physical network or a virtual network, such as a VPN that applies to the
4204 * application. The callbacks will continue to be called until either the application exits or
4205 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4206 *
4207 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4208 * number of outstanding requests to 100 per app (identified by their UID), shared with
4209 * all variants of this method, of {@link #requestNetwork} as well as
4210 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4211 * Requesting a network with this method will count toward this limit. If this limit is
4212 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4213 * make sure to unregister the callbacks with
4214 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4215 *
4216 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4217 * application's default network changes.
4218 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4219 * @throws RuntimeException if the app already has too many callbacks registered.
4220 */
4221 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4222 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4223 @NonNull Handler handler) {
4224 CallbackHandler cbHandler = new CallbackHandler(handler);
4225 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4226 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4227 }
4228
4229 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004230 * Registers to receive notifications about changes in the system default network. The callbacks
4231 * will continue to be called until either the application exits or
4232 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004233 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004234 * This method should not be used to determine networking state seen by applications, because in
4235 * many cases, most or even all application traffic may not use the default network directly,
4236 * and traffic from different applications may go on different networks by default. As an
4237 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4238 * and not onto the system default network. Applications or system components desiring to do
4239 * determine network state as seen by applications should use other methods such as
4240 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4241 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004242 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4243 * number of outstanding requests to 100 per app (identified by their UID), shared with
4244 * all variants of this method, of {@link #requestNetwork} as well as
4245 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4246 * Requesting a network with this method will count toward this limit. If this limit is
4247 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4248 * make sure to unregister the callbacks with
4249 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4250 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004251 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4252 * system default network changes.
4253 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004254 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004255 *
4256 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004257 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004258 @SystemApi(client = MODULE_LIBRARIES)
4259 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4260 @RequiresPermission(anyOf = {
4261 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4262 android.Manifest.permission.NETWORK_SETTINGS})
4263 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004264 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004265 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004266 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004267 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004268 }
4269
4270 /**
fenglub00f4882015-04-21 17:12:05 -07004271 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4272 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4273 * network connection for updated bandwidth information. The caller will be notified via
4274 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004275 * method assumes that the caller has previously called
4276 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4277 * changes.
fenglu3f357402015-03-20 11:29:56 -07004278 *
fengluea2d9282015-04-27 14:28:04 -07004279 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004280 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004281 */
Chalard Jean158702d2019-01-07 19:26:34 +09004282 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004283 try {
fenglub00f4882015-04-21 17:12:05 -07004284 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004285 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004286 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004287 }
4288 }
4289
4290 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004291 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004292 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4293 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4294 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004295 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4296 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004297 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004298 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4299 * triggering it as soon as this call returns.
4300 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004301 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004302 */
Chalard Jean158702d2019-01-07 19:26:34 +09004303 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004304 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004305 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004306 final List<NetworkRequest> reqs = new ArrayList<>();
4307 // Find all requests associated to this callback and stop callback triggers immediately.
4308 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4309 synchronized (sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09004310 Preconditions.checkArgument(networkCallback.networkRequest != null,
4311 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004312 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4313 Log.d(TAG, "NetworkCallback was already unregistered");
4314 return;
4315 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004316 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4317 if (e.getValue() == networkCallback) {
4318 reqs.add(e.getKey());
4319 }
4320 }
4321 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4322 for (NetworkRequest r : reqs) {
4323 try {
4324 mService.releaseNetworkRequest(r);
4325 } catch (RemoteException e) {
4326 throw e.rethrowFromSystemServer();
4327 }
4328 // Only remove mapping if rpc was successful.
4329 sCallbacks.remove(r);
4330 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004331 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004332 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004333 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004334
4335 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004336 * Unregisters a callback previously registered via
4337 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4338 *
4339 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4340 * PendingIntent passed to
4341 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4342 * Cannot be null.
4343 */
Chalard Jean158702d2019-01-07 19:26:34 +09004344 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004345 releaseNetworkRequest(operation);
4346 }
4347
4348 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004349 * Informs the system whether it should switch to {@code network} regardless of whether it is
4350 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4351 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4352 * the system default network regardless of any other network that's currently connected. If
4353 * {@code always} is true, then the choice is remembered, so that the next time the user
4354 * connects to this network, the system will switch to it.
4355 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004356 * @param network The network to accept.
4357 * @param accept Whether to accept the network even if unvalidated.
4358 * @param always Whether to remember this choice in the future.
4359 *
4360 * @hide
4361 */
lucaslin2240ef62019-03-12 13:08:03 +08004362 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004363 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4364 try {
4365 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004366 } catch (RemoteException e) {
4367 throw e.rethrowFromSystemServer();
4368 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004369 }
4370
4371 /**
lucaslin2240ef62019-03-12 13:08:03 +08004372 * Informs the system whether it should consider the network as validated even if it only has
4373 * partial connectivity. If {@code accept} is true, then the network will be considered as
4374 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4375 * is remembered, so that the next time the user connects to this network, the system will
4376 * switch to it.
4377 *
4378 * @param network The network to accept.
4379 * @param accept Whether to consider the network as validated even if it has partial
4380 * connectivity.
4381 * @param always Whether to remember this choice in the future.
4382 *
4383 * @hide
4384 */
4385 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4386 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4387 try {
4388 mService.setAcceptPartialConnectivity(network, accept, always);
4389 } catch (RemoteException e) {
4390 throw e.rethrowFromSystemServer();
4391 }
4392 }
4393
4394 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004395 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4396 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4397 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4398 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4399 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004400 * @param network The network to accept.
4401 *
4402 * @hide
4403 */
lucaslin2240ef62019-03-12 13:08:03 +08004404 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004405 public void setAvoidUnvalidated(Network network) {
4406 try {
4407 mService.setAvoidUnvalidated(network);
4408 } catch (RemoteException e) {
4409 throw e.rethrowFromSystemServer();
4410 }
4411 }
4412
4413 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004414 * Requests that the system open the captive portal app on the specified network.
4415 *
4416 * @param network The network to log into.
4417 *
4418 * @hide
4419 */
paulhu8e96a752019-08-12 16:25:11 +08004420 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004421 public void startCaptivePortalApp(Network network) {
4422 try {
4423 mService.startCaptivePortalApp(network);
4424 } catch (RemoteException e) {
4425 throw e.rethrowFromSystemServer();
4426 }
4427 }
4428
4429 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004430 * Requests that the system open the captive portal app with the specified extras.
4431 *
4432 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4433 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004434 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004435 * @param appExtras Extras to include in the app start intent.
4436 * @hide
4437 */
4438 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004439 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004440 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004441 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004442 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004443 } catch (RemoteException e) {
4444 throw e.rethrowFromSystemServer();
4445 }
4446 }
4447
4448 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004449 * Determine whether the device is configured to avoid bad wifi.
4450 * @hide
4451 */
4452 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004453 @RequiresPermission(anyOf = {
4454 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4455 android.Manifest.permission.NETWORK_STACK})
4456 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004457 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004458 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004459 } catch (RemoteException e) {
4460 throw e.rethrowFromSystemServer();
4461 }
4462 }
4463
4464 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004465 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4466 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004467 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4468 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004469 *
4470 * An example of such an operation might be a time-sensitive foreground activity, such as a
4471 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4472 */
4473 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4474
4475 /**
4476 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4477 * a backup channel for traffic that is primarily going over another network.
4478 *
4479 * An example might be maintaining backup connections to peers or servers for the purpose of
4480 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4481 * on backup paths should be negligible compared to the traffic on the main path.
4482 */
4483 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4484
4485 /**
4486 * It is acceptable to use metered data to improve network latency and performance.
4487 */
4488 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4489
4490 /**
4491 * Return value to use for unmetered networks. On such networks we currently set all the flags
4492 * to true.
4493 * @hide
4494 */
4495 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4496 MULTIPATH_PREFERENCE_HANDOVER |
4497 MULTIPATH_PREFERENCE_RELIABILITY |
4498 MULTIPATH_PREFERENCE_PERFORMANCE;
4499
4500 /** @hide */
4501 @Retention(RetentionPolicy.SOURCE)
4502 @IntDef(flag = true, value = {
4503 MULTIPATH_PREFERENCE_HANDOVER,
4504 MULTIPATH_PREFERENCE_RELIABILITY,
4505 MULTIPATH_PREFERENCE_PERFORMANCE,
4506 })
4507 public @interface MultipathPreference {
4508 }
4509
4510 /**
4511 * Provides a hint to the calling application on whether it is desirable to use the
4512 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4513 * for multipath data transfer on this network when it is not the system default network.
4514 * Applications desiring to use multipath network protocols should call this method before
4515 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004516 *
4517 * @param network The network on which the application desires to use multipath data.
4518 * If {@code null}, this method will return the a preference that will generally
4519 * apply to metered networks.
4520 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4521 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004522 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004523 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004524 try {
4525 return mService.getMultipathPreference(network);
4526 } catch (RemoteException e) {
4527 throw e.rethrowFromSystemServer();
4528 }
4529 }
4530
4531 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004532 * Resets all connectivity manager settings back to factory defaults.
4533 * @hide
4534 */
paulhu8e96a752019-08-12 16:25:11 +08004535 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004536 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004537 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004538 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004539 mTetheringManager.stopAllTethering();
Lorenzo Colitticd675292021-02-04 17:32:07 +09004540 // TODO: Migrate callers to VpnManager#factoryReset.
4541 getVpnManager().factoryReset();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004542 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004543 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004544 }
4545 }
4546
4547 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004548 * Binds the current process to {@code network}. All Sockets created in the future
4549 * (and not explicitly bound via a bound SocketFactory from
4550 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4551 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4552 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4553 * work and all host name resolutions will fail. This is by design so an application doesn't
4554 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4555 * To clear binding pass {@code null} for {@code network}. Using individually bound
4556 * Sockets created by Network.getSocketFactory().createSocket() and
4557 * performing network-specific host name resolutions via
4558 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004559 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004560 *
4561 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4562 * the current binding.
4563 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4564 */
Chalard Jean158702d2019-01-07 19:26:34 +09004565 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004566 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004567 // instantiated.
4568 return setProcessDefaultNetwork(network);
4569 }
4570
4571 /**
4572 * Binds the current process to {@code network}. All Sockets created in the future
4573 * (and not explicitly bound via a bound SocketFactory from
4574 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4575 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4576 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4577 * work and all host name resolutions will fail. This is by design so an application doesn't
4578 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4579 * To clear binding pass {@code null} for {@code network}. Using individually bound
4580 * Sockets created by Network.getSocketFactory().createSocket() and
4581 * performing network-specific host name resolutions via
4582 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4583 * {@code setProcessDefaultNetwork}.
4584 *
4585 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4586 * the current binding.
4587 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4588 * @deprecated This function can throw {@link IllegalStateException}. Use
4589 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4590 * is a direct replacement.
4591 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004592 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004593 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004594 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004595 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4596
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004597 if (netId != NETID_UNSET) {
4598 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004599 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004600
4601 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4602 return false;
4603 }
4604
4605 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004606 // Set HTTP proxy system properties to match network.
4607 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004608 try {
4609 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4610 } catch (SecurityException e) {
4611 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4612 Log.e(TAG, "Can't set proxy properties", e);
4613 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004614 // Must flush DNS cache as new network may have different DNS resolutions.
4615 InetAddress.clearDnsCache();
4616 // Must flush socket pool as idle sockets will be bound to previous network and may
4617 // cause subsequent fetches to be performed on old network.
4618 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004619 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004620
4621 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004622 }
4623
4624 /**
4625 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004626 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004627 *
4628 * @return {@code Network} to which this process is bound, or {@code null}.
4629 */
Chalard Jean158702d2019-01-07 19:26:34 +09004630 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004631 public Network getBoundNetworkForProcess() {
4632 // Forcing callers to call thru non-static function ensures ConnectivityManager
4633 // instantiated.
4634 return getProcessDefaultNetwork();
4635 }
4636
4637 /**
4638 * Returns the {@link Network} currently bound to this process via
4639 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4640 *
4641 * @return {@code Network} to which this process is bound, or {@code null}.
4642 * @deprecated Using this function can lead to other functions throwing
4643 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4644 * {@code getBoundNetworkForProcess} is a direct replacement.
4645 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004646 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004647 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004648 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004649 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004650 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004651 return new Network(netId);
4652 }
4653
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004654 private void unsupportedStartingFrom(int version) {
4655 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004656 // The getApplicationInfo() call we make below is not supported in system context. Let
4657 // the call through here, and rely on the fact that ConnectivityService will refuse to
4658 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004659 return;
4660 }
4661
4662 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4663 throw new UnsupportedOperationException(
4664 "This method is not supported in target SDK version " + version + " and above");
4665 }
4666 }
4667
4668 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4669 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004670 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004671 // remove these exemptions. Note that this check is not secure, and apps can still access these
4672 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4673 // so is unsupported and may break in the future. http://b/22728205
4674 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004675 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004676 }
4677
Paul Jensen8cdda642014-05-29 10:12:39 -04004678 /**
4679 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004680 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004681 *
4682 * @param network The {@link Network} to bind host resolutions from the current process to, or
4683 * {@code null} to clear the current binding.
4684 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4685 * @hide
4686 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4687 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004688 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004689 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004690 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004691 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004692 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004693 }
Felipe Leme30511352016-01-22 09:44:57 -08004694
4695 /**
4696 * Device is not restricting metered network activity while application is running on
4697 * background.
4698 */
4699 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4700
4701 /**
4702 * Device is restricting metered network activity while application is running on background,
4703 * but application is allowed to bypass it.
4704 * <p>
4705 * In this state, application should take action to mitigate metered network access.
4706 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4707 */
4708 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4709
4710 /**
4711 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004712 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004713 * In this state, application should not try to use the network while running on background,
4714 * because it would be denied.
4715 */
4716 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4717
Felipe Lemed34c9af2016-01-27 14:46:39 -08004718 /**
4719 * A change in the background metered network activity restriction has occurred.
4720 * <p>
4721 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4722 * applies to them.
4723 * <p>
4724 * This is only sent to registered receivers, not manifest receivers.
4725 */
4726 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4727 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4728 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4729
Felipe Leme7e4c1852016-01-25 11:48:04 -08004730 /** @hide */
4731 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004732 @IntDef(flag = false, value = {
4733 RESTRICT_BACKGROUND_STATUS_DISABLED,
4734 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4735 RESTRICT_BACKGROUND_STATUS_ENABLED,
4736 })
Felipe Leme30511352016-01-22 09:44:57 -08004737 public @interface RestrictBackgroundStatus {
4738 }
4739
4740 private INetworkPolicyManager getNetworkPolicyManager() {
4741 synchronized (this) {
4742 if (mNPManager != null) {
4743 return mNPManager;
4744 }
4745 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4746 .getService(Context.NETWORK_POLICY_SERVICE));
4747 return mNPManager;
4748 }
4749 }
4750
4751 /**
4752 * Determines if the calling application is subject to metered network restrictions while
4753 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004754 *
4755 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4756 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4757 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004758 */
4759 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4760 try {
4761 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4762 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004763 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004764 }
4765 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004766
4767 /**
4768 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004769 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4770 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004771 *
4772 * @return Hash of network watchlist config file. Null if config does not exist.
4773 */
Chalard Jean158702d2019-01-07 19:26:34 +09004774 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004775 public byte[] getNetworkWatchlistConfigHash() {
4776 try {
4777 return mService.getNetworkWatchlistConfigHash();
4778 } catch (RemoteException e) {
4779 Log.e(TAG, "Unable to get watchlist config hash");
4780 throw e.rethrowFromSystemServer();
4781 }
4782 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004783
4784 /**
4785 * Returns the {@code uid} of the owner of a network connection.
4786 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004787 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4788 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004789 * @param local The local {@link InetSocketAddress} of a connection.
4790 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004791 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004792 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4793 * android.os.Process#INVALID_UID} if the connection is not found.
4794 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4795 * user.
4796 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004797 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004798 public int getConnectionOwnerUid(
4799 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004800 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4801 try {
4802 return mService.getConnectionOwnerUid(connectionInfo);
4803 } catch (RemoteException e) {
4804 throw e.rethrowFromSystemServer();
4805 }
4806 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004807
4808 private void printStackTrace() {
4809 if (DEBUG) {
4810 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4811 final StringBuffer sb = new StringBuffer();
4812 for (int i = 3; i < callStack.length; i++) {
4813 final String stackTrace = callStack[i].toString();
4814 if (stackTrace == null || stackTrace.contains("android.os")) {
4815 break;
4816 }
4817 sb.append(" [").append(stackTrace).append("]");
4818 }
4819 Log.d(TAG, "StackLog:" + sb.toString());
4820 }
4821 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004822
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004823 /** @hide */
4824 public TestNetworkManager startOrGetTestNetworkManager() {
4825 final IBinder tnBinder;
4826 try {
4827 tnBinder = mService.startOrGetTestNetworkService();
4828 } catch (RemoteException e) {
4829 throw e.rethrowFromSystemServer();
4830 }
4831
4832 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4833 }
4834
Lorenzo Colitticd675292021-02-04 17:32:07 +09004835 /**
4836 * Temporary hack to shim calls from ConnectivityManager to VpnManager. We cannot store a
4837 * private final mVpnManager because ConnectivityManager is initialized before VpnManager.
4838 * @hide TODO: remove.
4839 */
4840 public VpnManager getVpnManager() {
4841 return mContext.getSystemService(VpnManager.class);
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004842 }
4843
4844 /** @hide */
4845 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4846 return new ConnectivityDiagnosticsManager(mContext, mService);
4847 }
4848
Cody Kestingf53a0752020-04-15 12:33:28 -07004849 /**
4850 * Simulates a Data Stall for the specified Network.
4851 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004852 * <p>This method should only be used for tests.
4853 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004854 * <p>The caller must be the owner of the specified Network.
4855 *
4856 * @param detectionMethod The detection method used to identify the Data Stall.
4857 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4858 * @param network The Network for which a Data Stall is being simluated.
4859 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4860 * @throws SecurityException if the caller is not the owner of the given network.
4861 * @hide
4862 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004863 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004864 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4865 android.Manifest.permission.NETWORK_STACK})
4866 public void simulateDataStall(int detectionMethod, long timestampMillis,
4867 @NonNull Network network, @NonNull PersistableBundle extras) {
4868 try {
4869 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4870 } catch (RemoteException e) {
4871 e.rethrowFromSystemServer();
4872 }
4873 }
James Mattis356a8792020-10-28 21:48:54 -07004874
Daniel Brightf9e945b2020-06-15 16:10:01 -07004875 @NonNull
4876 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4877
4878 /**
4879 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4880 * receive available QoS events related to the {@link Network} and local ip + port
4881 * specified within socketInfo.
4882 * <p/>
4883 * The same {@link QosCallback} must be unregistered before being registered a second time,
4884 * otherwise {@link QosCallbackRegistrationException} is thrown.
4885 * <p/>
4886 * This API does not, in itself, require any permission if called with a network that is not
4887 * restricted. However, the underlying implementation currently only supports the IMS network,
4888 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4889 * useful, because they'd never be called back on networks that they would have access to.
4890 *
4891 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4892 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4893 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4894 * @throws RuntimeException if the app already has too many callbacks registered.
4895 *
4896 * Exceptions after the time of registration is passed through
4897 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4898 *
4899 * @param socketInfo the socket information used to match QoS events
4900 * @param callback receives qos events that satisfy socketInfo
4901 * @param executor The executor on which the callback will be invoked. The provided
4902 * {@link Executor} must run callback sequentially, otherwise the order of
4903 * callbacks cannot be guaranteed.
4904 *
4905 * @hide
4906 */
4907 @SystemApi
4908 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4909 @NonNull final QosCallback callback,
4910 @CallbackExecutor @NonNull final Executor executor) {
4911 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4912 Objects.requireNonNull(callback, "callback must be non-null");
4913 Objects.requireNonNull(executor, "executor must be non-null");
4914
4915 try {
4916 synchronized (mQosCallbackConnections) {
4917 if (getQosCallbackConnection(callback) == null) {
4918 final QosCallbackConnection connection =
4919 new QosCallbackConnection(this, callback, executor);
4920 mQosCallbackConnections.add(connection);
4921 mService.registerQosSocketCallback(socketInfo, connection);
4922 } else {
4923 Log.e(TAG, "registerQosCallback: Callback already registered");
4924 throw new QosCallbackRegistrationException();
4925 }
4926 }
4927 } catch (final RemoteException e) {
4928 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4929
4930 // The same unregister method method is called for consistency even though nothing
4931 // will be sent to the ConnectivityService since the callback was never successfully
4932 // registered.
4933 unregisterQosCallback(callback);
4934 e.rethrowFromSystemServer();
4935 } catch (final ServiceSpecificException e) {
4936 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4937 unregisterQosCallback(callback);
4938 throw convertServiceException(e);
4939 }
4940 }
4941
4942 /**
4943 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4944 * events once unregistered and can be registered a second time.
4945 * <p/>
4946 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4947 *
4948 * @param callback the callback being unregistered
4949 *
4950 * @hide
4951 */
4952 @SystemApi
4953 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4954 Objects.requireNonNull(callback, "The callback must be non-null");
4955 try {
4956 synchronized (mQosCallbackConnections) {
4957 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4958 if (connection != null) {
4959 connection.stopReceivingMessages();
4960 mService.unregisterQosCallback(connection);
4961 mQosCallbackConnections.remove(connection);
4962 } else {
4963 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4964 }
4965 }
4966 } catch (final RemoteException e) {
4967 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4968 e.rethrowFromSystemServer();
4969 }
4970 }
4971
4972 /**
4973 * Gets the connection related to the callback.
4974 *
4975 * @param callback the callback to look up
4976 * @return the related connection
4977 */
4978 @Nullable
4979 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4980 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4981 // Checking by reference here is intentional
4982 if (connection.getCallback() == callback) {
4983 return connection;
4984 }
4985 }
4986 return null;
4987 }
Junyu Laia62493f2021-01-19 11:10:56 +00004988
4989 /**
4990 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4991 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4992 * be used to request that the system provide a network without causing the network to be
4993 * in the foreground.
4994 *
4995 * <p>This method will attempt to find the best network that matches the passed
4996 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4997 * criteria. The platform will evaluate which network is the best at its own discretion.
4998 * Throughput, latency, cost per byte, policy, user preference and other considerations
4999 * may be factored in the decision of what is considered the best network.
5000 *
5001 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5002 * matching this request, while always attempting to match the request to a better network if
5003 * possible. If a better match is found, the platform will switch this request to the now-best
5004 * network and inform the app of the newly best network by invoking
5005 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5006 * will not try to maintain any other network than the best one currently matching the request:
5007 * a network not matching any network request may be disconnected at any time.
5008 *
5009 * <p>For example, an application could use this method to obtain a connected cellular network
5010 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5011 * radio to consume additional power. Or, an application could inform the system that it wants
5012 * a network supporting sending MMSes and have the system let it know about the currently best
5013 * MMS-supporting network through the provided {@link NetworkCallback}.
5014 *
5015 * <p>The status of the request can be followed by listening to the various callbacks described
5016 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5017 * used to direct traffic to the network (although accessing some networks may be subject to
5018 * holding specific permissions). Callers will learn about the specific characteristics of the
5019 * network through
5020 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5021 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5022 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5023 * matching the request at any given time; therefore when a better network matching the request
5024 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5025 * with the new network after which no further updates are given about the previously-best
5026 * network, unless it becomes the best again at some later time. All callbacks are invoked
5027 * in order on the same thread, which by default is a thread created by the framework running
5028 * in the app.
5029 *
5030 * <p>This{@link NetworkRequest} will live until released via
5031 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5032 * which point the system may let go of the network at any time.
5033 *
5034 * <p>It is presently unsupported to request a network with mutable
5035 * {@link NetworkCapabilities} such as
5036 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5037 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5038 * as these {@code NetworkCapabilities} represent states that a particular
5039 * network may never attain, and whether a network will attain these states
5040 * is unknown prior to bringing up the network so the framework does not
5041 * know how to go about satisfying a request with these capabilities.
5042 *
5043 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5044 * number of outstanding requests to 100 per app (identified by their UID), shared with
5045 * all variants of this method, of {@link #registerNetworkCallback} as well as
5046 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5047 * Requesting a network with this method will count toward this limit. If this limit is
5048 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5049 * make sure to unregister the callbacks with
5050 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5051 *
5052 * @param request {@link NetworkRequest} describing this request.
5053 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5054 * If null, the callback is invoked on the default internal Handler.
5055 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5056 * the callback must not be shared - it uniquely specifies this request.
5057 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5058 * @throws SecurityException if missing the appropriate permissions.
5059 * @throws RuntimeException if the app already has too many callbacks registered.
5060 *
5061 * @hide
5062 */
5063 @SystemApi(client = MODULE_LIBRARIES)
5064 @SuppressLint("ExecutorRegistration")
5065 @RequiresPermission(anyOf = {
5066 android.Manifest.permission.NETWORK_SETTINGS,
5067 android.Manifest.permission.NETWORK_STACK,
5068 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5069 })
5070 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
5071 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
5072 final NetworkCapabilities nc = request.networkCapabilities;
5073 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
5074 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
5075 }
James Mattis45d81842021-01-10 14:24:24 -08005076
5077 /**
5078 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
5079 * OnSetOemNetworkPreferenceListener)}.
James Mattisda32cfe2021-01-26 16:23:52 -08005080 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005081 */
James Mattisda32cfe2021-01-26 16:23:52 -08005082 @SystemApi
5083 public interface OnSetOemNetworkPreferenceListener {
James Mattis45d81842021-01-10 14:24:24 -08005084 /**
5085 * Called when setOemNetworkPreference() successfully completes.
5086 */
5087 void onComplete();
5088 }
5089
5090 /**
5091 * Used by automotive devices to set the network preferences used to direct traffic at an
5092 * application level as per the given OemNetworkPreferences. An example use-case would be an
5093 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5094 * vehicle via a particular network.
5095 *
5096 * Calling this will overwrite the existing preference.
5097 *
5098 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5099 * @param executor the executor on which listener will be invoked.
5100 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5101 * communicate completion of setOemNetworkPreference(). This will only be
5102 * called once upon successful completion of setOemNetworkPreference().
5103 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5104 * @throws SecurityException if missing the appropriate permissions.
5105 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005106 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005107 */
James Mattisda32cfe2021-01-26 16:23:52 -08005108 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005109 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005110 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005111 @Nullable @CallbackExecutor final Executor executor,
5112 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5113 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5114 if (null != listener) {
5115 Objects.requireNonNull(executor, "Executor must be non-null");
5116 }
5117 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5118 new IOnSetOemNetworkPreferenceListener.Stub() {
5119 @Override
5120 public void onComplete() {
5121 executor.execute(listener::onComplete);
5122 }
5123 };
5124
5125 try {
5126 mService.setOemNetworkPreference(preference, listenerInternal);
5127 } catch (RemoteException e) {
5128 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5129 throw e.rethrowFromSystemServer();
5130 }
5131 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005132}