blob: 071ec34b620c144e6fb06a216599f64c4c33f3b8 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Project28527d22009-03-03 19:31:44 -080016package android.net;
17
Junyu Lai23568a42021-01-19 11:10:56 +000018import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
junyulai48a59382019-01-15 11:32:44 +080019import static android.net.IpSecManager.INVALID_RESOURCE_ID;
Junyu Lai23568a42021-01-19 11:10:56 +000020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaid1a78162021-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 Colitti80b48bc2021-01-29 20:14:04 +090024import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Bright60f02ed2020-06-15 16:10:01 -070025import static android.net.QosCallback.QosCallbackRegistrationException;
junyulai48a59382019-01-15 11:32:44 +080026
junyulaia86defc2018-12-27 17:25:29 +080027import android.annotation.CallbackExecutor;
Felipe Lemed16384b2016-01-22 09:44:57 -080028import android.annotation.IntDef;
Chalard Jean42a9c292019-01-07 19:26:34 +090029import android.annotation.NonNull;
Robin Lee33c73e22016-01-05 18:03:46 +000030import android.annotation.Nullable;
Jeff Sharkey2ac62992017-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 Lai23568a42021-01-19 11:10:56 +000034import android.annotation.SuppressLint;
Udam Saini53b71ee2016-01-04 12:16:14 -080035import android.annotation.SystemApi;
Jeff Sharkeyb8c73032017-06-02 17:36:26 -060036import android.annotation.SystemService;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070037import android.app.PendingIntent;
Artur Satayev0e45d782019-12-10 17:47:52 +000038import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070039import android.content.Context;
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -070040import android.content.Intent;
junyulaia86defc2018-12-27 17:25:29 +080041import android.net.IpSecManager.UdpEncapsulationSocket;
42import android.net.SocketKeepalive.Callback;
markchiencc1bc1b2020-01-20 19:31:56 +080043import android.net.TetheringManager.StartTetheringCallback;
markchieneeea0be2020-01-21 13:11:06 +080044import android.net.TetheringManager.TetheringEventCallback;
markchiencc1bc1b2020-01-20 19:31:56 +080045import android.net.TetheringManager.TetheringRequest;
Robert Greenwalt2034b912009-08-12 16:08:25 -070046import android.os.Binder;
Mathew Inwoodac5968e2018-12-20 15:30:45 +000047import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070048import android.os.Build.VERSION_CODES;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080049import android.os.Bundle;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070050import android.os.Handler;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080051import android.os.IBinder;
52import android.os.INetworkActivityListener;
53import android.os.INetworkManagementService;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070054import android.os.Looper;
55import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070056import android.os.Messenger;
junyulai61143782019-03-04 22:45:36 +080057import android.os.ParcelFileDescriptor;
Cody Kestingb5c7abd2020-04-15 12:33:28 -070058import android.os.PersistableBundle;
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +090059import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080060import android.os.RemoteException;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080061import android.os.ResultReceiver;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080062import android.os.ServiceManager;
Hugo Benichi145e3792017-05-11 13:16:17 +090063import android.os.ServiceSpecificException;
Jeff Sharkey971cd162011-08-29 16:02:57 -070064import android.provider.Settings;
Wink Saville02eb35c2014-12-05 11:10:30 -080065import android.telephony.SubscriptionManager;
Meng Wang91311c02019-11-18 17:10:00 -080066import android.telephony.TelephonyManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080067import android.util.ArrayMap;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070068import android.util.Log;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090069import android.util.Range;
Erik Kline50068e52017-01-26 18:08:28 +090070import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080071
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +090072import com.android.connectivity.aidl.INetworkAgent;
markchieneeea0be2020-01-21 13:11:06 +080073import com.android.internal.annotations.GuardedBy;
Hugo Benichi45a49542017-03-06 09:17:06 +090074import com.android.internal.util.Preconditions;
75import com.android.internal.util.Protocol;
Robert Greenwalt3d6c9582014-05-21 20:04:36 -070076
Paul Jensen99c36662014-08-27 12:38:45 -040077import libcore.net.event.NetworkEventDispatcher;
78
junyulai61143782019-03-04 22:45:36 +080079import java.io.IOException;
80import java.io.UncheckedIOException;
Felipe Lemed16384b2016-01-22 09:44:57 -080081import java.lang.annotation.Retention;
82import java.lang.annotation.RetentionPolicy;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090083import java.net.DatagramSocket;
Jeremy Klein04863332015-12-28 15:11:58 -080084import java.net.InetAddress;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -070085import java.net.InetSocketAddress;
junyulaic7ea1242019-01-08 20:04:33 +080086import java.net.Socket;
Hugo Benichi45a49542017-03-06 09:17:06 +090087import java.util.ArrayList;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090088import java.util.Collection;
Jeremy Klein04863332015-12-28 15:11:58 -080089import java.util.HashMap;
Hugo Benichi45a49542017-03-06 09:17:06 +090090import java.util.List;
91import java.util.Map;
markchieneeea0be2020-01-21 13:11:06 +080092import java.util.Objects;
junyulaia86defc2018-12-27 17:25:29 +080093import java.util.concurrent.Executor;
junyulai9f872232019-01-16 20:23:34 +080094import java.util.concurrent.ExecutorService;
95import java.util.concurrent.Executors;
96import java.util.concurrent.RejectedExecutionException;
Jeremy Klein04863332015-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 Sharkeyb8c73032017-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 Greenwaltd0ebdbb2014-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 Sharkeyb8c73032017-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, Yoshinari99efcbd2015-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 Greenwaltd0ebdbb2014-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 Lue1682a02016-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 Greenwalt26744a52013-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 Jeanae2424a2018-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 Sharkey6932ff62013-02-20 18:21:19 -0800154 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jeanae2424a2018-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 Jensened4d55c2015-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 Jensen4173cce2015-05-22 10:50:39 -0400163 * desire to sign in to the network. Apps handling this activity should
Paul Jensened4d55c2015-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 Jensen4173cce2015-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 Jean73d9db72018-06-04 16:52:49 +0900178 * data network.</li>
Paul Jensen4173cce2015-05-22 10:50:39 -0400179 * <li> When the app handling this action believes the user explicitly wants
Paul Jensened4d55c2015-02-27 22:55:47 -0500180 * to ignore the captive portal and the network, the app should call
Paul Jensen4173cce2015-05-22 10:50:39 -0400181 * {@link CaptivePortal#ignoreNetwork}. </li>
182 * </ul>
Paul Jensened4d55c2015-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 Jeancc47b522019-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 Jeancc47b522019-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 Jeancc47b522019-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)}.
junyulai5c2f6262018-12-13 12:47:51 +0800215 *
216 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800217 */
junyulai5c2f6262018-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)}.
junyulai5c2f6262018-12-13 12:47:51 +0800224 *
225 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800226 */
junyulai5c2f6262018-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)}.
junyulai5c2f6262018-12-13 12:47:51 +0800248 *
249 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800250 */
junyulai5c2f6262018-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 Jensen4173cce2015-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 Jensened4d55c2015-02-27 22:55:47 -0500268 */
Paul Jensen4173cce2015-05-22 10:50:39 -0400269 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist0f3b4442015-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 Jensened4d55c2015-02-27 22:55:47 -0500276 /**
Remi NGUYEN VANd937e3a2018-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 VANe541d182019-01-17 14:38:31 +0900281 @SystemApi
Remi NGUYEN VANd937e3a2018-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 Benichidce21c52016-12-14 08:23:40 +0900286 * Key for passing a user agent string to the captive portal login activity.
287 * {@hide}
288 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900289 @SystemApi
Hugo Benichidce21c52016-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 Greenwalt26744a52013-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 Jean73d9db72018-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 Sharma601fba92014-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 Sharkey6932ff62013-02-20 18:21:19 -0800351 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood0b8f8612018-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 Greenwalt26744a52013-02-15 10:56:35 -0800357 * Broadcast Action: A tetherable connection has come or gone.
358 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline449ccfe2017-04-17 16:47:23 +0900359 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
360 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt26744a52013-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 Sharkey6932ff62013-02-20 18:21:19 -0800366 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood5a09a712020-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 =
markchien1f523702019-12-25 19:40:32 +0800369 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800370
371 /**
372 * @hide
Robert Greenwalt26744a52013-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 Inwood5a09a712020-11-04 09:29:36 +0000376 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-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 Kline449ccfe2017-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 */
markchien1f523702019-12-25 19:40:32 +0800384 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline449ccfe2017-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 Inwood5a09a712020-11-04 09:29:36 +0000391 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-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 Greenwalt26744a52013-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 Inwood5a09a712020-11-04 09:29:36 +0000400 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-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 Brenner4774b022013-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 Sharkey6932ff62013-02-20 18:21:19 -0800409 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner4774b022013-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 Colitti36fbebe2015-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 Colitti477bf5c2016-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 /**
lucaslin25a50472019-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 Klein9a36ec82016-01-22 14:11:45 -0800447 * Invalid tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900448 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800449 * @hide
450 */
markchien1f523702019-12-25 19:40:32 +0800451 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800452
453 /**
454 * Wifi tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900455 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800456 * @hide
457 */
458 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900459 public static final int TETHERING_WIFI = 0;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800460
461 /**
462 * USB tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900463 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800464 * @hide
465 */
466 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900467 public static final int TETHERING_USB = 1;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800468
469 /**
470 * Bluetooth tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900471 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800472 * @hide
473 */
474 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900475 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800476
477 /**
Jimmy Chen87db1542019-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 */
markchien1f523702019-12-25 19:40:32 +0800483 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chen87db1542019-07-15 18:03:23 +0800484
485 /**
Jeremy Klein9a36ec82016-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 */
markchieneeea0be2020-01-21 13:11:06 +0800490 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein9a36ec82016-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 */
markchieneeea0be2020-01-21 13:11:06 +0800497 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein9a36ec82016-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 */
markchieneeea0be2020-01-21 13:11:06 +0800504 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800505
506 /**
507 * Tells the TetherService to run a provision check now.
508 * @hide
509 */
markchieneeea0be2020-01-21 13:11:06 +0800510 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein9a36ec82016-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 */
markchieneeea0be2020-01-21 13:11:06 +0800517 public static final String EXTRA_PROVISION_CALLBACK =
518 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800519
520 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800521 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700522 * @hide
523 */
paulhu62af6122020-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 Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900534 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700535 public static final int TYPE_MOBILE = 0;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900536
Robert Greenwalt2034b912009-08-12 16:08:25 -0700537 /**
Chalard Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900544 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700545 public static final int TYPE_WIFI = 1;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900546
Robert Greenwalt2034b912009-08-12 16:08:25 -0700547 /**
Robert Greenwalt26744a52013-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 Colitti7cc32c52015-04-23 15:32:42 +0900552 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900553 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900554 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900555 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700556 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700557 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700558 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900559
Robert Greenwalt2034b912009-08-12 16:08:25 -0700560 /**
Robert Greenwalt26744a52013-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 Colitti7cc32c52015-04-23 15:32:42 +0900565 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900566 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900567 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900568 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700569 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700570 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900572
Robert Greenwalt2034b912009-08-12 16:08:25 -0700573 /**
Robert Greenwalt26744a52013-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 Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900583 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900585
Robert Greenwalt2034b912009-08-12 16:08:25 -0700586 /**
Robert Greenwalt26744a52013-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 Colitti7cc32c52015-04-23 15:32:42 +0900589 * is different.
590 *
Chalard Jean5acb7b72018-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 Liutikasa6bb0232016-05-24 15:22:55 -0700595 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700596 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900597
jshbfa81722010-03-11 15:04:43 -0800598 /**
Chalard Jean5acb7b72018-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 Jean5acb7b72018-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 Jean5acb7b72018-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 Jean5acb7b72018-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 Wang7d5f3782020-07-28 13:53:09 +0800619 * Fake data connection. This should not be used on shipping devices.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900620 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700621 */
Chalard Jean5acb7b72018-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 Jean5acb7b72018-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 Jean5acb7b72018-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 Greenwalt26744a52013-02-15 10:56:35 -0800636 * Over the air Administration.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900637 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800638 * {@hide}
639 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900640 @Deprecated
Chalard Jeanaa91c9d2019-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 Greenwalt26744a52013-02-15 10:56:35 -0800645 * IP Multimedia Subsystem.
Chalard Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900649 @Deprecated
Mathew Inwood0b8f8612018-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 Greenwalt26744a52013-02-15 10:56:35 -0800654 * Carrier Branded Services.
Chalard Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900658 @Deprecated
Chalard Jeanaa91c9d2019-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 Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900668 @Deprecated
paulhu028732e2020-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 Saville70dbdcc2013-07-29 15:00:57 -0700672 /**
673 * The network to use for initially attaching to the network
Chalard Jean5acb7b72018-03-08 13:54:53 +0900674 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville70dbdcc2013-07-29 15:00:57 -0700675 * {@hide}
676 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900677 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100678 @UnsupportedAppUsage
Wink Saville70dbdcc2013-07-29 15:00:57 -0700679 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700680
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900681 /**
Robert Greenwalt9db5f3c2015-07-09 14:49:35 -0700682 * Emergency PDN connection for emergency services. This
683 * may include IMS and MMS in emergency situations.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900684 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram201d45f2014-06-26 11:03:44 -0700685 * {@hide}
686 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900687 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900688 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram201d45f2014-06-26 11:03:44 -0700689 public static final int TYPE_MOBILE_EMERGENCY = 15;
690
Hui Lu07f29332014-01-15 11:05:36 -0500691 /**
692 * The network that uses proxy to achieve connectivity.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900693 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu07f29332014-01-15 11:05:36 -0500694 * {@hide}
695 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900696 @Deprecated
Remi NGUYEN VANdaeafee2020-11-30 19:23:45 +0900697 @SystemApi
Hui Lu07f29332014-01-15 11:05:36 -0500698 public static final int TYPE_PROXY = 16;
Wink Saville70dbdcc2013-07-29 15:00:57 -0700699
Robert Greenwaltb2a03d12014-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 Jean5acb7b72018-03-08 13:54:53 +0900703 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700704 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900705 @Deprecated
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700706 public static final int TYPE_VPN = 17;
Hui Lu07f29332014-01-15 11:05:36 -0500707
Benedict Wong80156022018-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 Greenwaltb2a03d12014-07-07 17:09:01 -0700716
Chalard Jeane5b9e822020-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 Jean1f42df12019-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 Greenwaltb2a03d12014-07-07 17:09:01 -0700753 /** {@hide} */
Benedict Wong80156022018-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 Benichi37d5c3c2017-06-20 14:07:59 +0900759 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
760
Jianzheng Zhoua8aa1602012-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 Greenwalt26744a52013-02-15 10:56:35 -0800767 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800768 * networkAttributes in config.xml. You can determine
Robert Greenwalt1ee3d2c2012-12-07 09:56:50 -0800769 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoua8aa1602012-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 Sharkey5eccd9c2012-09-26 22:03:49 -0700775 /**
Robert Greenwalta1402df2014-03-19 17:56:12 -0700776 * @hide
777 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900778 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltc34f83b2014-06-08 16:42:59 -0700779
Paul Jensen0478ace2014-07-11 12:28:19 -0400780 /**
Hugo Benichi1c027fe2017-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 Jean73d9db72018-06-04 16:52:49 +0900783 * registered from those that were already unregistered.
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900784 * @hide
785 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900786 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900787 new NetworkRequest.Builder().clearCapabilities().build();
788
789 /**
Paul Jensen0478ace2014-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 Kline1ecdd962017-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 Klineae1a3af2018-05-16 16:41:57 +0900823 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline1ecdd962017-10-30 15:29:44 +0900824
Chalard Jeanaa91c9d2019-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 Colitti0dd4b6f2021-02-04 17:32:07 +0900827
Paul Jensen12131352014-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 Colitti9b026fa2015-07-29 11:41:21 +0900836 private final Context mContext;
837
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800838 private INetworkManagementService mNMService;
Felipe Lemed16384b2016-01-22 09:44:57 -0800839 private INetworkPolicyManager mNPManager;
Amos Bianchiddadca42020-03-04 11:07:38 -0800840 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800841
Robert Greenwalt26744a52013-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 Jensen1c9f2e42015-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 Greenwalt26744a52013-02-15 10:56:35 -0800848 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700849 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700850 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-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 Greenwalt26744a52013-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 Jean5acb7b72018-03-08 13:54:53 +0900860 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800861 * {@hide}
862 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900863 @Deprecated
Mathew Inwood5a09a712020-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 Benichi37d5c3c2017-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 Saville70dbdcc2013-07-29 15:00:57 -0700897 case TYPE_MOBILE_IA:
898 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -0700899 case TYPE_MOBILE_EMERGENCY:
900 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -0500901 case TYPE_PROXY:
902 return "PROXY";
Erik Klineb1ff7002014-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 Greenwalt26744a52013-02-15 10:56:35 -0800910 /**
Aaron Huang925d09b2020-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 Greenwalt26744a52013-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 Jean5acb7b72018-03-08 13:54:53 +0900927 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800928 * {@hide}
929 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900930 @Deprecated
Chalard Jeanaa91c9d2019-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 Saville70dbdcc2013-07-29 15:00:57 -0700942 case TYPE_MOBILE_IA:
Ram201d45f2014-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 Greenwalt26744a52013-02-15 10:56:35 -0800950 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700951 * Checks if the given network type is backed by a Wi-Fi radio.
952 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900953 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700954 * @hide
955 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900956 @Deprecated
Jeff Sharkeye9bda1d2013-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 Greenwalt26744a52013-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 Greenwalt26744a52013-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 Greenwaltd0ebdbb2014-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 Greenwalt26744a52013-02-15 10:56:35 -0800978 */
Aurimas Liutikasa6bb0232016-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 Greenwalt26744a52013-02-15 10:56:35 -0800983 /**
984 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800985 *
986 * @return an integer representing the preferred network type
987 *
Robert Greenwaltd0ebdbb2014-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 Greenwalt26744a52013-02-15 10:56:35 -0800992 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700993 @Deprecated
Jeff Sharkey2ac62992017-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 Greenwaltd0ebdbb2014-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 Greenwalt26744a52013-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 Jean7c85ba42018-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 Greenwalt26744a52013-02-15 10:56:35 -08001009 *
1010 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001011 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001012 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001013 */
junyulai5c2f6262018-12-13 12:47:51 +08001014 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001015 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-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 Sharkeya6066fd2016-03-01 19:27:23 -07001021 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001022 }
1023 }
1024
Robert Greenwalt26744a52013-02-15 10:56:35 -08001025 /**
Paul Jensenc2569432015-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 Jensenc2569432015-02-13 14:18:39 -05001034 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001035 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001036 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001037 public Network getActiveNetwork() {
1038 try {
1039 return mService.getActiveNetwork();
1040 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001041 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001042 }
1043 }
1044
1045 /**
Robin Leeda4d2e22016-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 Leeda4d2e22016-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 */
paulhud70b7dd2019-08-12 16:25:11 +08001057 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001058 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001059 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001060 return getActiveNetworkForUid(uid, false);
1061 }
1062
1063 /** {@hide} */
1064 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001065 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001066 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001067 } catch (RemoteException e) {
1068 throw e.rethrowFromSystemServer();
1069 }
1070 }
1071
1072 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001073 * Adds or removes a requirement for given UID ranges to use the VPN.
1074 *
1075 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1076 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1077 * otherwise have permission to bypass the VPN (e.g., because they have the
1078 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1079 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1080 * set to {@code false}, a previously-added restriction is removed.
1081 * <p>
1082 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1083 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1084 * remove a previously-added range, the exact range must be removed as is.
1085 * <p>
1086 * The changes are applied asynchronously and may not have been applied by the time the method
1087 * returns. Apps will be notified about any changes that apply to them via
1088 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1089 * effect.
1090 * <p>
1091 * This method should be called only by the VPN code.
1092 *
1093 * @param ranges the UID ranges to restrict
1094 * @param requireVpn whether the specified UID ranges must use a VPN
1095 *
1096 * TODO: expose as @SystemApi.
1097 * @hide
1098 */
1099 @RequiresPermission(anyOf = {
1100 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1101 android.Manifest.permission.NETWORK_STACK})
1102 public void setRequireVpnForUids(boolean requireVpn,
1103 @NonNull Collection<Range<Integer>> ranges) {
1104 Objects.requireNonNull(ranges);
1105 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1106 // This method is not necessarily expected to be used outside the system server, so
1107 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1108 // stack process, or by tests.
1109 UidRange[] rangesArray = new UidRange[ranges.size()];
1110 int index = 0;
1111 for (Range<Integer> range : ranges) {
1112 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1113 }
1114 try {
1115 mService.setRequireVpnForUids(requireVpn, rangesArray);
1116 } catch (RemoteException e) {
1117 throw e.rethrowFromSystemServer();
1118 }
1119 }
1120
1121 /**
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001122 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1123 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1124 * but is still supported for backwards compatibility.
1125 * <p>
1126 * This type of VPN is assumed always to use the system default network, and must always declare
1127 * exactly one underlying network, which is the network that was the default when the VPN
1128 * connected.
1129 * <p>
1130 * Calling this method with {@code true} enables legacy behaviour, specifically:
1131 * <ul>
1132 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1133 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1134 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1135 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1136 * underlying the VPN.</li>
1137 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1138 * similarly replaced by the VPN network state.</li>
1139 * <li>Information on current network interfaces passed to NetworkStatsService will not
1140 * include any VPN interfaces.</li>
1141 * </ul>
1142 *
1143 * @param enabled whether legacy lockdown VPN is enabled or disabled
1144 *
1145 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1146 *
1147 * @hide
1148 */
1149 @RequiresPermission(anyOf = {
1150 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1151 android.Manifest.permission.NETWORK_SETTINGS})
1152 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1153 try {
1154 mService.setLegacyLockdownVpnEnabled(enabled);
1155 } catch (RemoteException e) {
1156 throw e.rethrowFromSystemServer();
1157 }
1158 }
1159
1160 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001161 * Returns details about the currently active default data network
1162 * for a given uid. This is for internal use only to avoid spying
1163 * other apps.
1164 *
1165 * @return a {@link NetworkInfo} object for the current default network
1166 * for the given uid or {@code null} if no default network is
1167 * available for the specified uid.
1168 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001169 * {@hide}
1170 */
paulhud70b7dd2019-08-12 16:25:11 +08001171 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwood5a09a712020-11-04 09:29:36 +00001172 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001173 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001174 return getActiveNetworkInfoForUid(uid, false);
1175 }
1176
1177 /** {@hide} */
1178 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001179 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001180 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001181 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001182 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001183 }
1184 }
1185
Robert Greenwalt26744a52013-02-15 10:56:35 -08001186 /**
1187 * Returns connection status information about a particular
1188 * network type.
1189 *
1190 * @param networkType integer specifying which networkType in
1191 * which you're interested.
1192 * @return a {@link NetworkInfo} object for the requested
1193 * network type or {@code null} if the type is not
Chalard Jean7c85ba42018-03-29 17:45:24 +09001194 * supported by the device. If {@code networkType} is
1195 * TYPE_VPN and a VPN is active for the calling app,
1196 * then this method will try to return one of the
1197 * underlying networks for the VPN or null if the
1198 * VPN agent didn't specify any.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001199 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001200 * @deprecated This method does not support multiple connected networks
1201 * of the same type. Use {@link #getAllNetworks} and
1202 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001203 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001204 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001205 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001206 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001207 public NetworkInfo getNetworkInfo(int networkType) {
1208 try {
1209 return mService.getNetworkInfo(networkType);
1210 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001211 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001212 }
1213 }
1214
Robert Greenwalt26744a52013-02-15 10:56:35 -08001215 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001216 * Returns connection status information about a particular
1217 * Network.
1218 *
1219 * @param network {@link Network} specifying which network
1220 * in which you're interested.
1221 * @return a {@link NetworkInfo} object for the requested
1222 * network or {@code null} if the {@code Network}
1223 * is not valid.
junyulai5c2f6262018-12-13 12:47:51 +08001224 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001225 */
junyulai5c2f6262018-12-13 12:47:51 +08001226 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001227 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001228 @Nullable
1229 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001230 return getNetworkInfoForUid(network, Process.myUid(), false);
1231 }
1232
1233 /** {@hide} */
1234 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001235 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001236 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001237 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001238 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001239 }
1240 }
1241
1242 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001243 * Returns connection status information about all network
1244 * types supported by the device.
1245 *
1246 * @return an array of {@link NetworkInfo} objects. Check each
1247 * {@link NetworkInfo#getType} for which type each applies.
1248 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001249 * @deprecated This method does not support multiple connected networks
1250 * of the same type. Use {@link #getAllNetworks} and
1251 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001252 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001253 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001254 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001255 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001256 public NetworkInfo[] getAllNetworkInfo() {
1257 try {
1258 return mService.getAllNetworkInfo();
1259 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001260 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001261 }
1262 }
1263
Robert Greenwalt26744a52013-02-15 10:56:35 -08001264 /**
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001265 * Returns the {@link Network} object currently serving a given type, or
1266 * null if the given type is not connected.
1267 *
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001268 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04001269 * @deprecated This method does not support multiple connected networks
1270 * of the same type. Use {@link #getAllNetworks} and
1271 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001272 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001273 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001274 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001275 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001276 public Network getNetworkForType(int networkType) {
1277 try {
1278 return mService.getNetworkForType(networkType);
1279 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001280 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001281 }
1282 }
1283
1284 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001285 * Returns an array of all {@link Network} currently tracked by the
1286 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001287 *
1288 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001289 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001290 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001291 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001292 public Network[] getAllNetworks() {
1293 try {
1294 return mService.getAllNetworks();
1295 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001296 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001297 }
1298 }
1299
1300 /**
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +09001301 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001302 * the Networks that applications run by the given user will use by default.
1303 * @hide
1304 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001305 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001306 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1307 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001308 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001309 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001310 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001311 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001312 }
1313 }
1314
1315 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001316 * Returns the IP information for the current default network.
1317 *
1318 * @return a {@link LinkProperties} object describing the IP info
1319 * for the current default network, or {@code null} if there
1320 * is no current default network.
1321 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001322 * {@hide}
Chalard Jeancc47b522019-01-11 16:47:53 +09001323 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1324 * value of {@link #getActiveNetwork()} instead. In particular,
1325 * this method will return non-null LinkProperties even if the
1326 * app is blocked by policy from using this network.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001327 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001328 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-01-11 16:47:53 +09001329 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001330 public LinkProperties getActiveLinkProperties() {
1331 try {
1332 return mService.getActiveLinkProperties();
1333 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001334 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001335 }
1336 }
1337
Robert Greenwalt26744a52013-02-15 10:56:35 -08001338 /**
1339 * Returns the IP information for a given network type.
1340 *
1341 * @param networkType the network type of interest.
1342 * @return a {@link LinkProperties} object describing the IP info
1343 * for the given networkType, or {@code null} if there is
1344 * no current default network.
1345 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001346 * {@hide}
Paul Jensena8e6dc62015-03-18 12:23:02 -04001347 * @deprecated This method does not support multiple connected networks
1348 * of the same type. Use {@link #getAllNetworks},
1349 * {@link #getNetworkInfo(android.net.Network)}, and
1350 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001351 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001352 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001353 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001354 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001355 public LinkProperties getLinkProperties(int networkType) {
1356 try {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001357 return mService.getLinkPropertiesForType(networkType);
1358 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001359 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001360 }
1361 }
1362
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001363 /**
1364 * Get the {@link LinkProperties} for the given {@link Network}. This
1365 * will return {@code null} if the network is unknown.
1366 *
1367 * @param network The {@link Network} object identifying the network in question.
1368 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001369 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001370 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001371 @Nullable
1372 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001373 try {
1374 return mService.getLinkProperties(network);
1375 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001376 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001377 }
1378 }
1379
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001380 /**
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +09001381 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001382 * will return {@code null} if the network is unknown.
1383 *
1384 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +09001385 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001386 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001387 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001388 @Nullable
1389 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001390 try {
Roshan Piusc97d8062020-12-17 14:53:09 -08001391 return mService.getNetworkCapabilities(
1392 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001393 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001394 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001395 }
1396 }
1397
Robert Greenwalt26744a52013-02-15 10:56:35 -08001398 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001399 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001400 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1401 * portal is present.
1402 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1403 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1404 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001405 * The system network validation may be using different strategies to detect captive portals,
1406 * so this method does not necessarily return a URL used by the system. It only returns a URL
1407 * that may be relevant for other components trying to detect captive portals.
paulhud70b7dd2019-08-12 16:25:11 +08001408 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001409 * @hide
paulhud70b7dd2019-08-12 16:25:11 +08001410 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1411 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001412 */
paulhud70b7dd2019-08-12 16:25:11 +08001413 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001414 @SystemApi
paulhud70b7dd2019-08-12 16:25:11 +08001415 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001416 public String getCaptivePortalServerUrl() {
1417 try {
1418 return mService.getCaptivePortalServerUrl();
1419 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001420 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001421 }
1422 }
1423
1424 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001425 * Tells the underlying networking system that the caller wants to
1426 * begin using the named feature. The interpretation of {@code feature}
1427 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001428 *
1429 * <p>This method requires the caller to hold either the
1430 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1431 * or the ability to modify system settings as determined by
1432 * {@link android.provider.Settings.System#canWrite}.</p>
1433 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001434 * @param networkType specifies which network the request pertains to
1435 * @param feature the name of the feature to be used
1436 * @return an integer value representing the outcome of the request.
1437 * The interpretation of this value is specific to each networking
1438 * implementation+feature combination, except that the value {@code -1}
1439 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001440 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001441 * @deprecated Deprecated in favor of the cleaner
1442 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001443 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001444 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001445 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001446 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001447 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001448 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001449 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001450 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1451 if (netCap == null) {
1452 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1453 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001454 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001455 }
1456
1457 NetworkRequest request = null;
1458 synchronized (sLegacyRequests) {
1459 LegacyRequest l = sLegacyRequests.get(netCap);
1460 if (l != null) {
1461 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1462 renewRequestLocked(l);
1463 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001464 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001465 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001466 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001467 }
1468 }
1469
1470 request = requestNetworkForFeatureLocked(netCap);
1471 }
1472 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001473 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001474 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001475 } else {
1476 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001477 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001478 }
1479 }
1480
1481 /**
1482 * Tells the underlying networking system that the caller is finished
1483 * using the named feature. The interpretation of {@code feature}
1484 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001485 *
1486 * <p>This method requires the caller to hold either the
1487 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1488 * or the ability to modify system settings as determined by
1489 * {@link android.provider.Settings.System#canWrite}.</p>
1490 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001491 * @param networkType specifies which network the request pertains to
1492 * @param feature the name of the feature that is no longer needed
1493 * @return an integer value representing the outcome of the request.
1494 * The interpretation of this value is specific to each networking
1495 * implementation+feature combination, except that the value {@code -1}
1496 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001497 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001498 * @deprecated Deprecated in favor of the cleaner
1499 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001500 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001501 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001502 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001503 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001504 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001505 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001506 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001507 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1508 if (netCap == null) {
1509 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1510 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001511 return -1;
1512 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001513
Paul Jensen034dea32014-12-17 10:39:34 -05001514 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001515 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001516 }
1517 return 1;
1518 }
1519
Mathew Inwood5a09a712020-11-04 09:29:36 +00001520 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001521 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1522 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001523 switch (feature) {
1524 case "enableCBS":
1525 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1526 case "enableDUN":
1527 case "enableDUNAlways":
1528 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1529 case "enableFOTA":
1530 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1531 case "enableHIPRI":
1532 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1533 case "enableIMS":
1534 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1535 case "enableMMS":
1536 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1537 case "enableSUPL":
1538 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1539 default:
1540 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001541 }
Erik Kline50068e52017-01-26 18:08:28 +09001542 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1543 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001544 }
1545 return null;
1546 }
1547
Robert Greenwalt5a367872014-06-02 15:32:02 -07001548 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001549 if (netCap == null) return TYPE_NONE;
1550 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1551 return TYPE_MOBILE_CBS;
1552 }
1553 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1554 return TYPE_MOBILE_IMS;
1555 }
1556 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1557 return TYPE_MOBILE_FOTA;
1558 }
1559 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1560 return TYPE_MOBILE_DUN;
1561 }
1562 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1563 return TYPE_MOBILE_SUPL;
1564 }
1565 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1566 return TYPE_MOBILE_MMS;
1567 }
1568 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1569 return TYPE_MOBILE_HIPRI;
1570 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001571 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1572 return TYPE_WIFI_P2P;
1573 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001574 return TYPE_NONE;
1575 }
1576
1577 private static class LegacyRequest {
1578 NetworkCapabilities networkCapabilities;
1579 NetworkRequest networkRequest;
1580 int expireSequenceNumber;
1581 Network currentNetwork;
1582 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001583
1584 private void clearDnsBinding() {
1585 if (currentNetwork != null) {
1586 currentNetwork = null;
1587 setProcessDefaultNetworkForHostResolution(null);
1588 }
1589 }
1590
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001591 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001592 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001593 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001594 currentNetwork = network;
1595 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001596 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001597 }
1598 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001599 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001600 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001601 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1602 }
1603 };
1604 }
1605
Mathew Inwood5a09a712020-11-04 09:29:36 +00001606 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001607 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1608 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001609
1610 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1611 synchronized (sLegacyRequests) {
1612 LegacyRequest l = sLegacyRequests.get(netCap);
1613 if (l != null) return l.networkRequest;
1614 }
1615 return null;
1616 }
1617
1618 private void renewRequestLocked(LegacyRequest l) {
1619 l.expireSequenceNumber++;
1620 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1621 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1622 }
1623
1624 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1625 int ourSeqNum = -1;
1626 synchronized (sLegacyRequests) {
1627 LegacyRequest l = sLegacyRequests.get(netCap);
1628 if (l == null) return;
1629 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001630 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001631 }
1632 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1633 }
1634
Mathew Inwood5a09a712020-11-04 09:29:36 +00001635 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001636 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1637 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001638 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001639 try {
1640 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001641 } catch (RemoteException e) {
1642 throw e.rethrowFromSystemServer();
1643 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001644 LegacyRequest l = new LegacyRequest();
1645 l.networkCapabilities = netCap;
1646 l.delay = delay;
1647 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001648 l.networkRequest = sendRequestForNetwork(
1649 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001650 if (l.networkRequest == null) return null;
1651 sLegacyRequests.put(netCap, l);
1652 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1653 return l.networkRequest;
1654 }
1655
1656 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1657 if (delay >= 0) {
1658 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001659 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001660 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1661 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001662 }
1663 }
1664
Mathew Inwood5a09a712020-11-04 09:29:36 +00001665 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001666 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1667 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001668 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001669 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001670 }
Paul Jensen034dea32014-12-17 10:39:34 -05001671 if (l == null) return false;
1672 unregisterNetworkCallback(l.networkCallback);
1673 l.clearDnsBinding();
1674 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001675 }
1676
Erik Kline50068e52017-01-26 18:08:28 +09001677 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1678 static {
1679 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1680 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1681 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1682 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1683 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1684 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1685 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1686 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1687 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1688 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1689 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1690 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1691 }
1692
1693 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1694 static {
1695 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1696 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1697 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1698 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1699 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1700 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1701 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1702 }
1703
1704 /**
1705 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1706 * instance suitable for registering a request or callback. Throws an
1707 * IllegalArgumentException if no mapping from the legacy type to
1708 * NetworkCapabilities is known.
1709 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001710 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1711 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001712 * @hide
1713 */
1714 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1715 final NetworkCapabilities nc = new NetworkCapabilities();
1716
1717 // Map from type to transports.
1718 final int NOT_FOUND = -1;
1719 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichiff4bf602017-05-09 15:19:01 +09001720 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline50068e52017-01-26 18:08:28 +09001721 nc.addTransportType(transport);
1722
1723 // Map from type to capabilities.
1724 nc.addCapability(sLegacyTypeToCapability.get(
1725 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1726 nc.maybeMarkCapabilitiesRestricted();
1727 return nc;
1728 }
1729
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001730 /** @hide */
1731 public static class PacketKeepaliveCallback {
Mathew Inwood5a09a712020-11-04 09:29:36 +00001732 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev198d6502019-11-04 17:50:59 +00001733 public PacketKeepaliveCallback() {
1734 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001735 /** The requested keepalive was successfully started. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001736 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001737 public void onStarted() {}
1738 /** The keepalive was successfully stopped. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001739 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001740 public void onStopped() {}
1741 /** An error occurred. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001742 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001743 public void onError(int error) {}
1744 }
1745
1746 /**
1747 * Allows applications to request that the system periodically send specific packets on their
1748 * behalf, using hardware offload to save battery power.
1749 *
1750 * To request that the system send keepalives, call one of the methods that return a
1751 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1752 * passing in a non-null callback. If the callback is successfully started, the callback's
1753 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1754 * specifying one of the {@code ERROR_*} constants in this class.
1755 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001756 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1757 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1758 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001759 *
junyulaia86defc2018-12-27 17:25:29 +08001760 * @deprecated Use {@link SocketKeepalive} instead.
1761 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001762 * @hide
1763 */
1764 public class PacketKeepalive {
1765
1766 private static final String TAG = "PacketKeepalive";
1767
1768 /** @hide */
1769 public static final int SUCCESS = 0;
1770
1771 /** @hide */
1772 public static final int NO_KEEPALIVE = -1;
1773
1774 /** @hide */
1775 public static final int BINDER_DIED = -10;
1776
1777 /** The specified {@code Network} is not connected. */
1778 public static final int ERROR_INVALID_NETWORK = -20;
1779 /** The specified IP addresses are invalid. For example, the specified source IP address is
1780 * not configured on the specified {@code Network}. */
1781 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1782 /** The requested port is invalid. */
1783 public static final int ERROR_INVALID_PORT = -22;
1784 /** The packet length is invalid (e.g., too long). */
1785 public static final int ERROR_INVALID_LENGTH = -23;
1786 /** The packet transmission interval is invalid (e.g., too short). */
1787 public static final int ERROR_INVALID_INTERVAL = -24;
1788
1789 /** The hardware does not support this request. */
1790 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001791 /** The hardware returned an error. */
1792 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001793
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001794 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001795 public static final int NATT_PORT = 4500;
1796
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001797 /** The minimum interval in seconds between keepalive packet transmissions */
1798 public static final int MIN_INTERVAL = 10;
1799
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001800 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001801 private final ISocketKeepaliveCallback mCallback;
1802 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001803
1804 private volatile Integer mSlot;
1805
Mathew Inwood5a09a712020-11-04 09:29:36 +00001806 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001807 public void stop() {
1808 try {
junyulai9f872232019-01-16 20:23:34 +08001809 mExecutor.execute(() -> {
1810 try {
1811 if (mSlot != null) {
1812 mService.stopKeepalive(mNetwork, mSlot);
1813 }
1814 } catch (RemoteException e) {
1815 Log.e(TAG, "Error stopping packet keepalive: ", e);
1816 throw e.rethrowFromSystemServer();
1817 }
1818 });
1819 } catch (RejectedExecutionException e) {
1820 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001821 }
1822 }
1823
1824 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi45a49542017-03-06 09:17:06 +09001825 Preconditions.checkNotNull(network, "network cannot be null");
1826 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001827 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08001828 mExecutor = Executors.newSingleThreadExecutor();
1829 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001830 @Override
junyulai9f872232019-01-16 20:23:34 +08001831 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08001832 final long token = Binder.clearCallingIdentity();
1833 try {
1834 mExecutor.execute(() -> {
1835 mSlot = slot;
1836 callback.onStarted();
1837 });
1838 } finally {
1839 Binder.restoreCallingIdentity(token);
1840 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001841 }
junyulai9f872232019-01-16 20:23:34 +08001842
1843 @Override
1844 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08001845 final long token = Binder.clearCallingIdentity();
1846 try {
1847 mExecutor.execute(() -> {
1848 mSlot = null;
1849 callback.onStopped();
1850 });
1851 } finally {
1852 Binder.restoreCallingIdentity(token);
1853 }
junyulai9f872232019-01-16 20:23:34 +08001854 mExecutor.shutdown();
1855 }
1856
1857 @Override
1858 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08001859 final long token = Binder.clearCallingIdentity();
1860 try {
1861 mExecutor.execute(() -> {
1862 mSlot = null;
1863 callback.onError(error);
1864 });
1865 } finally {
1866 Binder.restoreCallingIdentity(token);
1867 }
junyulai9f872232019-01-16 20:23:34 +08001868 mExecutor.shutdown();
1869 }
1870
1871 @Override
1872 public void onDataReceived() {
1873 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1874 // this callback when data is received.
1875 }
1876 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001877 }
1878 }
1879
1880 /**
1881 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1882 *
junyulaia86defc2018-12-27 17:25:29 +08001883 * @deprecated Use {@link #createSocketKeepalive} instead.
1884 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001885 * @hide
1886 */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001887 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001888 public PacketKeepalive startNattKeepalive(
1889 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1890 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1891 final PacketKeepalive k = new PacketKeepalive(network, callback);
1892 try {
junyulai9f872232019-01-16 20:23:34 +08001893 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001894 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1895 } catch (RemoteException e) {
1896 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08001897 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001898 }
1899 return k;
1900 }
1901
Chiachang Wangc5f86f42021-01-15 11:06:21 +08001902 // Construct an invalid fd.
1903 private ParcelFileDescriptor createInvalidFd() {
1904 final int invalidFd = -1;
1905 return ParcelFileDescriptor.adoptFd(invalidFd);
1906 }
1907
The Android Open Source Project28527d22009-03-03 19:31:44 -08001908 /**
junyulaia86defc2018-12-27 17:25:29 +08001909 * Request that keepalives be started on a IPsec NAT-T socket.
1910 *
1911 * @param network The {@link Network} the socket is on.
1912 * @param socket The socket that needs to be kept alive.
1913 * @param source The source address of the {@link UdpEncapsulationSocket}.
1914 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1915 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1916 * must run callback sequentially, otherwise the order of callbacks cannot be
1917 * guaranteed.
1918 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1919 * changes. Must be extended by applications that use this API.
1920 *
junyulaic7ea1242019-01-08 20:04:33 +08001921 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1922 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08001923 **/
junyulai61143782019-03-04 22:45:36 +08001924 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08001925 @NonNull UdpEncapsulationSocket socket,
1926 @NonNull InetAddress source,
1927 @NonNull InetAddress destination,
1928 @NonNull @CallbackExecutor Executor executor,
1929 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08001930 ParcelFileDescriptor dup;
1931 try {
junyulaic4fb2482019-03-27 11:00:37 +08001932 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1933 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08001934 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1935 } catch (IOException ignored) {
1936 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1937 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08001938 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08001939 }
1940 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1941 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08001942 }
1943
1944 /**
1945 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1946 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1947 *
1948 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08001949 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1950 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1951 * from that port.
junyulai48a59382019-01-15 11:32:44 +08001952 * @param source The source address of the {@link UdpEncapsulationSocket}.
1953 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1954 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1955 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1956 * must run callback sequentially, otherwise the order of callbacks cannot be
1957 * guaranteed.
1958 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1959 * changes. Must be extended by applications that use this API.
1960 *
junyulaic7ea1242019-01-08 20:04:33 +08001961 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1962 * given socket.
junyulai48a59382019-01-15 11:32:44 +08001963 * @hide
1964 */
1965 @SystemApi
1966 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08001967 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1968 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08001969 @NonNull InetAddress source,
1970 @NonNull InetAddress destination,
1971 @NonNull @CallbackExecutor Executor executor,
1972 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08001973 ParcelFileDescriptor dup;
1974 try {
junyulaic4fb2482019-03-27 11:00:37 +08001975 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08001976 dup = pfd.dup();
1977 } catch (IOException ignored) {
1978 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1979 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08001980 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08001981 }
1982 return new NattSocketKeepalive(mService, network, dup,
1983 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08001984 }
1985
1986 /**
junyulaic7ea1242019-01-08 20:04:33 +08001987 * Request that keepalives be started on a TCP socket.
1988 * The socket must be established.
1989 *
1990 * @param network The {@link Network} the socket is on.
1991 * @param socket The socket that needs to be kept alive.
1992 * @param executor The executor on which callback will be invoked. This implementation assumes
1993 * the provided {@link Executor} runs the callbacks in sequence with no
1994 * concurrency. Failing this, no guarantee of correctness can be made. It is
1995 * the responsibility of the caller to ensure the executor provides this
1996 * guarantee. A simple way of creating such an executor is with the standard
1997 * tool {@code Executors.newSingleThreadExecutor}.
1998 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1999 * changes. Must be extended by applications that use this API.
2000 *
2001 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2002 * given socket.
2003 * @hide
2004 */
2005 @SystemApi
2006 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002007 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002008 @NonNull Socket socket,
2009 @NonNull Executor executor,
2010 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002011 ParcelFileDescriptor dup;
2012 try {
2013 dup = ParcelFileDescriptor.fromSocket(socket);
2014 } catch (UncheckedIOException ignored) {
2015 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2016 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002017 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002018 }
2019 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002020 }
2021
2022 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002023 * Ensure that a network route exists to deliver traffic to the specified
2024 * host via the specified network interface. An attempt to add a route that
2025 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002026 *
2027 * <p>This method requires the caller to hold either the
2028 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2029 * or the ability to modify system settings as determined by
2030 * {@link android.provider.Settings.System#canWrite}.</p>
2031 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002032 * @param networkType the type of the network over which traffic to the specified
2033 * host is to be routed
2034 * @param hostAddress the IP address of the host to which the route is desired
2035 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002036 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002037 * @deprecated Deprecated in favor of the
2038 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2039 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002040 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002041 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002042 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002043 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002044 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002045 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002046 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002047 }
2048
2049 /**
2050 * Ensure that a network route exists to deliver traffic to the specified
2051 * host via the specified network interface. An attempt to add a route that
2052 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002053 *
2054 * <p>This method requires the caller to hold either the
2055 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2056 * or the ability to modify system settings as determined by
2057 * {@link android.provider.Settings.System#canWrite}.</p>
2058 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002059 * @param networkType the type of the network over which traffic to the specified
2060 * host is to be routed
2061 * @param hostAddress the IP address of the host to which the route is desired
2062 * @return {@code true} on success, {@code false} on failure
2063 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002064 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002065 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002066 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002067 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002068 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002069 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002070 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002071 try {
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002072 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2073 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002074 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002075 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002076 }
2077 }
2078
2079 /**
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002080 * @return the context's attribution tag
2081 */
2082 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2083 private @Nullable String getAttributionTag() {
Roshan Piusc97d8062020-12-17 14:53:09 -08002084 return mContext.getAttributionTag();
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002085 }
2086
2087 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002088 * Returns the value of the setting for background data usage. If false,
2089 * applications should not use the network if the application is not in the
2090 * foreground. Developers should respect this setting, and check the value
2091 * of this before performing any background data operations.
2092 * <p>
2093 * All applications that have background services that use the network
2094 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002095 * <p>
Scott Main50589142011-10-06 18:32:43 -07002096 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002097 * background data depends on several combined factors, and this method will
2098 * always return {@code true}. Instead, when background data is unavailable,
2099 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002100 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002101 * @return Whether background data usage is allowed.
2102 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002103 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002104 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002105 // assume that background data is allowed; final authority is
2106 // NetworkInfo which may be blocked.
2107 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002108 }
2109
2110 /**
2111 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002112 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002113 * @param allowBackgroundData Whether an application should use data while
2114 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002115 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002116 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2117 * @see #getBackgroundDataSetting()
2118 * @hide
2119 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002120 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002121 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002122 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002123 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002124 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002125
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002126 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002127 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002128 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002129 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002130 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002131 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002132 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002133 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2134 if (tm != null) {
2135 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2136 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2137 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2138 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2139 + " retVal=" + retVal);
2140 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002141 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002142 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002143 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002144 }
2145
The Android Open Source Project28527d22009-03-03 19:31:44 -08002146 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002147 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002148 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002149 */
2150 public interface OnNetworkActiveListener {
2151 /**
2152 * Called on the main thread of the process to report that the current data network
2153 * has become active, and it is now a good time to perform any pending network
2154 * operations. Note that this listener only tells you when the network becomes
2155 * active; if at any other time you want to know whether it is active (and thus okay
2156 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002157 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002158 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002159 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002160 }
2161
2162 private INetworkManagementService getNetworkManagementService() {
2163 synchronized (this) {
2164 if (mNMService != null) {
2165 return mNMService;
2166 }
2167 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2168 mNMService = INetworkManagementService.Stub.asInterface(b);
2169 return mNMService;
2170 }
2171 }
2172
2173 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002174 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002175
2176 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002177 * Start listening to reports when the system's default data network is active, meaning it is
2178 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2179 * to determine the current state of the system's default network after registering the
2180 * listener.
2181 * <p>
2182 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002183 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002184 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002185 *
2186 * @param l The listener to be told when the network is active.
2187 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002188 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002189 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2190 @Override
2191 public void onNetworkActive() throws RemoteException {
2192 l.onNetworkActive();
2193 }
2194 };
2195
2196 try {
2197 getNetworkManagementService().registerNetworkActivityListener(rl);
2198 mNetworkActivityListeners.put(l, rl);
2199 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002200 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002201 }
2202 }
2203
2204 /**
2205 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002206 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002207 *
2208 * @param l Previously registered listener.
2209 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002210 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002211 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichiff4bf602017-05-09 15:19:01 +09002212 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002213 try {
2214 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2215 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002216 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002217 }
2218 }
2219
2220 /**
2221 * Return whether the data network is currently active. An active network means that
2222 * it is currently in a high power state for performing data transmission. On some
2223 * types of networks, it may be expensive to move and stay in such a state, so it is
2224 * more power efficient to batch network traffic together when the radio is already in
2225 * this state. This method tells you whether right now is currently a good time to
2226 * initiate network traffic, as the network is already active.
2227 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002228 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002229 try {
2230 return getNetworkManagementService().isNetworkActive();
2231 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002232 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002233 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002234 }
2235
2236 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002237 * {@hide}
2238 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002239 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi45a49542017-03-06 09:17:06 +09002240 mContext = Preconditions.checkNotNull(context, "missing context");
2241 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchiddadca42020-03-04 11:07:38 -08002242 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002243 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002244 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002245
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002246 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002247 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002248 public static ConnectivityManager from(Context context) {
2249 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2250 }
2251
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002252 /** @hide */
2253 public NetworkRequest getDefaultRequest() {
2254 try {
2255 // This is not racy as the default request is final in ConnectivityService.
2256 return mService.getDefaultRequest();
2257 } catch (RemoteException e) {
2258 throw e.rethrowFromSystemServer();
2259 }
2260 }
2261
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09002262 /* TODO: These permissions checks don't belong in client-side code. Move them to
2263 * services.jar, possibly in com.android.server.net. */
2264
2265 /** {@hide} */
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002266 public static final void enforceChangePermission(Context context,
2267 String callingPkg, String callingAttributionTag) {
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002268 int uid = Binder.getCallingUid();
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002269 checkAndNoteChangeNetworkStateOperation(context, uid, callingPkg,
2270 callingAttributionTag, true /* throwException */);
2271 }
2272
2273 /**
2274 * Check if the package is a allowed to change the network state. This also accounts that such
2275 * an access happened.
2276 *
2277 * @return {@code true} iff the package is allowed to change the network state.
2278 */
2279 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2280 private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context,
2281 int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag,
2282 boolean throwException) {
2283 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, callingPackage,
2284 throwException);
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002285 }
2286
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002287 /**
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002288 * Check if the package is a allowed to write settings. This also accounts that such an access
2289 * happened.
2290 *
2291 * @return {@code true} iff the package is allowed to write settings.
2292 */
2293 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2294 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2295 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2296 boolean throwException) {
2297 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2298 throwException);
2299 }
2300
2301 /**
Paul Jensen12131352014-12-10 15:12:18 -05002302 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2303 * situations where a Context pointer is unavailable.
2304 * @hide
2305 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002306 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002307 static ConnectivityManager getInstanceOrNull() {
2308 return sInstance;
2309 }
2310
2311 /**
2312 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2313 * situations where a Context pointer is unavailable.
2314 * @hide
2315 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002316 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002317 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002318 private static ConnectivityManager getInstance() {
2319 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002320 throw new IllegalStateException("No ConnectivityManager yet constructed");
2321 }
Paul Jensen895c3942015-03-10 10:54:12 -04002322 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002323 }
2324
2325 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002326 * Get the set of tetherable, available interfaces. This list is limited by
2327 * device configuration and current interface existence.
2328 *
2329 * @return an array of 0 or more Strings of tetherable interface names.
2330 *
markchieneeea0be2020-01-21 13:11:06 +08002331 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002332 * {@hide}
2333 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002334 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002335 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002336 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002337 public String[] getTetherableIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002338 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002339 }
2340
2341 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002342 * Get the set of tethered interfaces.
2343 *
2344 * @return an array of 0 or more String of currently tethered interface names.
2345 *
markchieneeea0be2020-01-21 13:11:06 +08002346 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002347 * {@hide}
2348 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002349 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002350 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002351 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002352 public String[] getTetheredIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002353 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002354 }
2355
2356 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002357 * Get the set of interface names which attempted to tether but
2358 * failed. Re-attempting to tether may cause them to reset to the Tethered
2359 * state. Alternatively, causing the interface to be destroyed and recreated
2360 * may cause them to reset to the available state.
2361 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2362 * information on the cause of the errors.
2363 *
2364 * @return an array of 0 or more String indicating the interface names
2365 * which failed to tether.
2366 *
markchieneeea0be2020-01-21 13:11:06 +08002367 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002368 * {@hide}
2369 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002370 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002371 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002372 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002373 public String[] getTetheringErroredIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002374 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002375 }
2376
2377 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002378 * Get the set of tethered dhcp ranges.
2379 *
markchien218230f2020-02-14 11:55:48 +08002380 * @deprecated This method is not supported.
2381 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002382 * {@hide}
2383 */
paulhud70b7dd2019-08-12 16:25:11 +08002384 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchieneeea0be2020-01-21 13:11:06 +08002385 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002386 public String[] getTetheredDhcpRanges() {
markchien218230f2020-02-14 11:55:48 +08002387 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002388 }
2389
2390 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002391 * Attempt to tether the named interface. This will setup a dhcp server
2392 * on the interface, forward and NAT IP packets and forward DNS requests
2393 * to the best active upstream network interface. Note that if no upstream
2394 * IP network interface is available, dhcp will still run and traffic will be
2395 * allowed between the tethered devices and this device, though upstream net
2396 * access will of course fail until an upstream network interface becomes
2397 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002398 *
2399 * <p>This method requires the caller to hold either the
2400 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2401 * or the ability to modify system settings as determined by
2402 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002403 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002404 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2405 * and WifiStateMachine which need direct access. All other clients should use
2406 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2407 * logic.</p>
2408 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002409 * @param iface the interface name to tether.
2410 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiencc1bc1b2020-01-20 19:31:56 +08002411 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002412 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002413 * {@hide}
2414 */
Mathew Inwood5a09a712020-11-04 09:29:36 +00002415 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiencc1bc1b2020-01-20 19:31:56 +08002416 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002417 public int tether(String iface) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002418 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002419 }
2420
2421 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002422 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002423 *
2424 * <p>This method requires the caller to hold either the
2425 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2426 * or the ability to modify system settings as determined by
2427 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002428 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002429 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2430 * and WifiStateMachine which need direct access. All other clients should use
2431 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2432 * logic.</p>
2433 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002434 * @param iface the interface name to untether.
2435 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2436 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002437 * {@hide}
2438 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002439 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002440 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002441 public int untether(String iface) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002442 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002443 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002444
2445 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002446 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002447 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002448 * due to device configuration.
2449 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002450 * <p>If this app does not have permission to use this API, it will always
2451 * return false rather than throw an exception.</p>
2452 *
2453 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2454 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2455 *
2456 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2457 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2458 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002459 * @return a boolean - {@code true} indicating Tethering is supported.
2460 *
markchieneeea0be2020-01-21 13:11:06 +08002461 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002462 * {@hide}
2463 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002464 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002465 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2466 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002467 public boolean isTetheringSupported() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002468 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002469 }
2470
2471 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002472 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchiencc1bc1b2020-01-20 19:31:56 +08002473 *
2474 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002475 * @hide
2476 */
2477 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002478 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002479 public static abstract class OnStartTetheringCallback {
2480 /**
2481 * Called when tethering has been successfully started.
2482 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002483 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002484
2485 /**
2486 * Called when starting tethering failed.
2487 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002488 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002489 }
2490
2491 /**
2492 * Convenient overload for
2493 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2494 * handler to run on the current thread's {@link Looper}.
markchiencc1bc1b2020-01-20 19:31:56 +08002495 *
2496 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002497 * @hide
2498 */
2499 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002500 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002501 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002502 public void startTethering(int type, boolean showProvisioningUi,
2503 final OnStartTetheringCallback callback) {
2504 startTethering(type, showProvisioningUi, callback, null);
2505 }
2506
2507 /**
2508 * Runs tether provisioning for the given type if needed and then starts tethering if
2509 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2510 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2511 * schedules tether provisioning re-checks if appropriate.
2512 *
2513 * @param type The type of tethering to start. Must be one of
2514 * {@link ConnectivityManager.TETHERING_WIFI},
2515 * {@link ConnectivityManager.TETHERING_USB}, or
2516 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2517 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2518 * is one. This should be true the first time this function is called and also any time
2519 * the user can see this UI. It gives users information from their carrier about the
2520 * check failing and how they can sign up for tethering if possible.
2521 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2522 * of the result of trying to tether.
2523 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchiencc1bc1b2020-01-20 19:31:56 +08002524 *
2525 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002526 * @hide
2527 */
2528 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002529 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002530 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002531 public void startTethering(int type, boolean showProvisioningUi,
2532 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi45a49542017-03-06 09:17:06 +09002533 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002534
markchiencc1bc1b2020-01-20 19:31:56 +08002535 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002536 @Override
markchiencc1bc1b2020-01-20 19:31:56 +08002537 public void execute(Runnable command) {
2538 if (handler == null) {
2539 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002540 } else {
markchiencc1bc1b2020-01-20 19:31:56 +08002541 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002542 }
2543 }
2544 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002545
markchiencc1bc1b2020-01-20 19:31:56 +08002546 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2547 @Override
2548 public void onTetheringStarted() {
2549 callback.onTetheringStarted();
2550 }
2551
2552 @Override
markchien19336c22020-03-19 13:37:43 +08002553 public void onTetheringFailed(final int error) {
markchiencc1bc1b2020-01-20 19:31:56 +08002554 callback.onTetheringFailed();
2555 }
2556 };
2557
2558 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien19336c22020-03-19 13:37:43 +08002559 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchiencc1bc1b2020-01-20 19:31:56 +08002560
Amos Bianchiddadca42020-03-04 11:07:38 -08002561 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002562 }
2563
2564 /**
2565 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2566 * applicable.
2567 *
2568 * @param type The type of tethering to stop. Must be one of
2569 * {@link ConnectivityManager.TETHERING_WIFI},
2570 * {@link ConnectivityManager.TETHERING_USB}, or
2571 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchieneeea0be2020-01-21 13:11:06 +08002572 *
2573 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002574 * @hide
2575 */
2576 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002577 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002578 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002579 public void stopTethering(int type) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002580 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002581 }
2582
2583 /**
markchiena005c992019-02-27 14:56:11 +08002584 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2585 * upstream status.
2586 *
Nathan Haroldbbb48c62020-01-23 18:03:46 -08002587 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchieneeea0be2020-01-21 13:11:06 +08002588 * @hide
markchiena005c992019-02-27 14:56:11 +08002589 */
2590 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002591 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002592 public abstract static class OnTetheringEventCallback {
2593
2594 /**
2595 * Called when tethering upstream changed. This can be called multiple times and can be
2596 * called any time.
2597 *
2598 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2599 * have any upstream.
2600 */
2601 public void onUpstreamChanged(@Nullable Network network) {}
2602 }
2603
markchieneeea0be2020-01-21 13:11:06 +08002604 @GuardedBy("mTetheringEventCallbacks")
2605 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2606 mTetheringEventCallbacks = new ArrayMap<>();
2607
markchiena005c992019-02-27 14:56:11 +08002608 /**
2609 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002610 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002611 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2612 * with a null argument. The same callback object cannot be registered twice.
2613 *
2614 * @param executor the executor on which callback will be invoked.
2615 * @param callback the callback to be called when tethering has change events.
markchieneeea0be2020-01-21 13:11:06 +08002616 *
Nathan Haroldbbb48c62020-01-23 18:03:46 -08002617 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002618 * @hide
2619 */
2620 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002621 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002622 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2623 public void registerTetheringEventCallback(
2624 @NonNull @CallbackExecutor Executor executor,
2625 @NonNull final OnTetheringEventCallback callback) {
2626 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2627
markchieneeea0be2020-01-21 13:11:06 +08002628 final TetheringEventCallback tetherCallback =
2629 new TetheringEventCallback() {
2630 @Override
2631 public void onUpstreamChanged(@Nullable Network network) {
2632 callback.onUpstreamChanged(network);
2633 }
2634 };
2635
2636 synchronized (mTetheringEventCallbacks) {
2637 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchiddadca42020-03-04 11:07:38 -08002638 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchieneeea0be2020-01-21 13:11:06 +08002639 }
markchiena005c992019-02-27 14:56:11 +08002640 }
2641
2642 /**
2643 * Remove tethering event callback previously registered with
2644 * {@link #registerTetheringEventCallback}.
2645 *
2646 * @param callback previously registered callback.
markchieneeea0be2020-01-21 13:11:06 +08002647 *
2648 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002649 * @hide
2650 */
2651 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002652 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002653 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2654 public void unregisterTetheringEventCallback(
2655 @NonNull final OnTetheringEventCallback callback) {
markchieneeea0be2020-01-21 13:11:06 +08002656 Objects.requireNonNull(callback, "The callback must be non-null");
2657 synchronized (mTetheringEventCallbacks) {
2658 final TetheringEventCallback tetherCallback =
2659 mTetheringEventCallbacks.remove(callback);
Amos Bianchiddadca42020-03-04 11:07:38 -08002660 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchieneeea0be2020-01-21 13:11:06 +08002661 }
markchiena005c992019-02-27 14:56:11 +08002662 }
2663
2664
2665 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002666 * Get the list of regular expressions that define any tetherable
2667 * USB network interfaces. If USB tethering is not supported by the
2668 * device, this list should be empty.
2669 *
2670 * @return an array of 0 or more regular expression Strings defining
2671 * what interfaces are considered tetherable usb interfaces.
2672 *
markchieneeea0be2020-01-21 13:11:06 +08002673 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002674 * {@hide}
2675 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002676 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002677 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002678 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002679 public String[] getTetherableUsbRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002680 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002681 }
2682
2683 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002684 * Get the list of regular expressions that define any tetherable
2685 * Wifi network interfaces. If Wifi tethering is not supported by the
2686 * device, this list should be empty.
2687 *
2688 * @return an array of 0 or more regular expression Strings defining
2689 * what interfaces are considered tetherable wifi interfaces.
2690 *
markchieneeea0be2020-01-21 13:11:06 +08002691 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002692 * {@hide}
2693 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002694 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002695 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002696 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002697 public String[] getTetherableWifiRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002698 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002699 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002700
Danica Chang96567052010-08-11 14:54:43 -07002701 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002702 * Get the list of regular expressions that define any tetherable
2703 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2704 * device, this list should be empty.
2705 *
2706 * @return an array of 0 or more regular expression Strings defining
2707 * what interfaces are considered tetherable bluetooth interfaces.
2708 *
markchieneeea0be2020-01-21 13:11:06 +08002709 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2710 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002711 * {@hide}
2712 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002713 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002714 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002715 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002716 public String[] getTetherableBluetoothRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002717 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002718 }
2719
Mike Lockwooded4a1742011-07-19 13:04:47 -07002720 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002721 * Attempt to both alter the mode of USB and Tethering of USB. A
2722 * utility method to deal with some of the complexity of USB - will
2723 * attempt to switch to Rndis and subsequently tether the resulting
2724 * interface on {@code true} or turn off tethering and switch off
2725 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002726 *
2727 * <p>This method requires the caller to hold either the
2728 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2729 * or the ability to modify system settings as determined by
2730 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002731 *
2732 * @param enable a boolean - {@code true} to enable tethering
2733 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiencc1bc1b2020-01-20 19:31:56 +08002734 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002735 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002736 * {@hide}
2737 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002738 @UnsupportedAppUsage
markchiencc1bc1b2020-01-20 19:31:56 +08002739 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002740 public int setUsbTethering(boolean enable) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002741 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002742 }
2743
markchieneeea0be2020-01-21 13:11:06 +08002744 /**
2745 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2746 * {@hide}
2747 */
markchien5bd499c2019-01-16 17:44:13 +08002748 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002749 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002750 public static final int TETHER_ERROR_NO_ERROR = 0;
markchieneeea0be2020-01-21 13:11:06 +08002751 /**
2752 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2753 * {@hide}
2754 */
2755 @Deprecated
2756 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2757 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2758 /**
2759 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2760 * {@hide}
2761 */
2762 @Deprecated
2763 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2764 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2765 /**
2766 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2767 * {@hide}
2768 */
2769 @Deprecated
2770 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2771 /**
2772 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2773 * {@hide}
2774 */
2775 @Deprecated
2776 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2777 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2778 /**
markchien19336c22020-03-19 13:37:43 +08002779 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002780 * {@hide}
2781 */
2782 @Deprecated
markchien19336c22020-03-19 13:37:43 +08002783 public static final int TETHER_ERROR_MASTER_ERROR =
2784 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002785 /**
2786 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2787 * {@hide}
2788 */
2789 @Deprecated
2790 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2791 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2792 /**
2793 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2794 * {@hide}
2795 */
2796 @Deprecated
2797 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2798 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2799 /**
markchien19336c22020-03-19 13:37:43 +08002800 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002801 * {@hide}
2802 */
2803 @Deprecated
2804 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien19336c22020-03-19 13:37:43 +08002805 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002806 /**
markchien19336c22020-03-19 13:37:43 +08002807 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002808 * {@hide}
2809 */
2810 @Deprecated
2811 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien19336c22020-03-19 13:37:43 +08002812 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002813 /**
2814 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2815 * {@hide}
2816 */
2817 @Deprecated
2818 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2819 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2820 /**
markchien19336c22020-03-19 13:37:43 +08002821 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchieneeea0be2020-01-21 13:11:06 +08002822 * {@hide}
2823 */
markchien5bd499c2019-01-16 17:44:13 +08002824 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002825 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002826 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchieneeea0be2020-01-21 13:11:06 +08002827 /**
2828 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2829 * {@hide}
2830 */
2831 @Deprecated
2832 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2833 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2834 /**
2835 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2836 * {@hide}
2837 */
markchien5bd499c2019-01-16 17:44:13 +08002838 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002839 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002840 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002841
2842 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002843 * Get a more detailed error code after a Tethering or Untethering
2844 * request asynchronously failed.
2845 *
2846 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002847 * @return error The error code of the last error tethering or untethering the named
2848 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002849 *
markchieneeea0be2020-01-21 13:11:06 +08002850 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002851 * {@hide}
2852 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002853 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood5a09a712020-11-04 09:29:36 +00002854 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchieneeea0be2020-01-21 13:11:06 +08002855 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002856 public int getLastTetherError(String iface) {
markchien19336c22020-03-19 13:37:43 +08002857 int error = mTetheringManager.getLastTetherError(iface);
2858 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2859 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2860 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2861 // instead.
2862 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2863 }
2864 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002865 }
2866
markchiendd41c822019-03-06 16:25:00 +08002867 /** @hide */
2868 @Retention(RetentionPolicy.SOURCE)
2869 @IntDef(value = {
2870 TETHER_ERROR_NO_ERROR,
2871 TETHER_ERROR_PROVISION_FAILED,
2872 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2873 })
2874 public @interface EntitlementResultCode {
2875 }
2876
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002877 /**
markchiendd41c822019-03-06 16:25:00 +08002878 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08002879 * entitlement succeeded.
markchieneeea0be2020-01-21 13:11:06 +08002880 *
2881 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08002882 * @hide
2883 */
2884 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002885 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08002886 public interface OnTetheringEntitlementResultListener {
2887 /**
2888 * Called to notify entitlement result.
2889 *
2890 * @param resultCode an int value of entitlement result. It may be one of
2891 * {@link #TETHER_ERROR_NO_ERROR},
2892 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2893 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2894 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07002895 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08002896 }
2897
2898 /**
markchien5bd499c2019-01-16 17:44:13 +08002899 * Get the last value of the entitlement check on this downstream. If the cached value is
2900 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2901 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2902 * guaranteed that the UI-based entitlement check will complete in any specific time period
2903 * and may in fact never complete. Any successful entitlement check the platform performs for
2904 * any reason will update the cached value.
2905 *
2906 * @param type the downstream type of tethering. Must be one of
2907 * {@link #TETHERING_WIFI},
2908 * {@link #TETHERING_USB}, or
2909 * {@link #TETHERING_BLUETOOTH}.
2910 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08002911 * @param executor the executor on which callback will be invoked.
2912 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2913 * notify the caller of the result of entitlement check. The listener may be called zero
2914 * or one time.
markchieneeea0be2020-01-21 13:11:06 +08002915 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08002916 * {@hide}
2917 */
2918 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002919 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08002920 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08002921 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2922 @NonNull @CallbackExecutor Executor executor,
2923 @NonNull final OnTetheringEntitlementResultListener listener) {
2924 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2925 ResultReceiver wrappedListener = new ResultReceiver(null) {
2926 @Override
2927 protected void onReceiveResult(int resultCode, Bundle resultData) {
2928 Binder.withCleanCallingIdentity(() ->
2929 executor.execute(() -> {
Jeremy Kleina9aad902019-03-12 13:32:08 -07002930 listener.onTetheringEntitlementResult(resultCode);
markchiendd41c822019-03-06 16:25:00 +08002931 }));
2932 }
2933 };
2934
Amos Bianchiddadca42020-03-04 11:07:38 -08002935 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien4f949812019-12-16 20:15:20 +08002936 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08002937 }
2938
2939 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002940 * Report network connectivity status. This is currently used only
2941 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04002942 * <p>This method requires the caller to hold the permission
2943 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08002944 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002945 * @param networkType The type of network you want to report on
2946 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09002947 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002948 * {@hide}
2949 */
2950 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09002951 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002952 try {
2953 mService.reportInetCondition(networkType, percentage);
2954 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002955 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002956 }
2957 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002958
2959 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002960 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07002961 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002962 * the framework to re-evaluate network connectivity and/or switch to another
2963 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002964 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002965 * @param network The {@link Network} the application was attempting to use
2966 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04002967 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2968 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002969 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002970 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09002971 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09002972 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002973 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04002974 // One of these will be ignored because it matches system's current state.
2975 // The other will trigger the necessary reevaluation.
2976 mService.reportNetworkConnectivity(network, true);
2977 mService.reportNetworkConnectivity(network, false);
2978 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002979 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04002980 }
2981 }
2982
2983 /**
2984 * Report to the framework whether a network has working connectivity.
2985 * This provides a hint to the system that a particular network is providing
2986 * working connectivity or not. In response the framework may re-evaluate
2987 * the network's connectivity and might take further action thereafter.
2988 *
2989 * @param network The {@link Network} the application was attempting to use
2990 * or {@code null} to indicate the current default network.
2991 * @param hasConnectivity {@code true} if the application was able to successfully access the
2992 * Internet using {@code network} or {@code false} if not.
2993 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002994 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09002995 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04002996 try {
2997 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002998 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002999 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003000 }
3001 }
3002
3003 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003004 * Set a network-independent global http proxy. This is not normally what you want
3005 * for typical HTTP proxies - they are general network dependent. However if you're
3006 * doing something unusual like general internal filtering this may be useful. On
3007 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003008 *
3009 * @param p A {@link ProxyInfo} object defining the new global
3010 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003011 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003012 */
paulhud70b7dd2019-08-12 16:25:11 +08003013 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk1e3df5d2014-04-25 15:00:09 -04003014 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003015 try {
3016 mService.setGlobalProxy(p);
3017 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003018 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003019 }
3020 }
3021
3022 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003023 * Retrieve any network-independent global HTTP proxy.
3024 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003025 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003026 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003027 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003028 */
Jason Monk1e3df5d2014-04-25 15:00:09 -04003029 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003030 try {
3031 return mService.getGlobalProxy();
3032 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003033 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003034 }
3035 }
3036
3037 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003038 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3039 * network-specific HTTP proxy. If {@code network} is null, the
3040 * network-specific proxy returned is the proxy of the default active
3041 * network.
3042 *
3043 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3044 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3045 * or when {@code network} is {@code null},
3046 * the {@code ProxyInfo} for the default active network. Returns
3047 * {@code null} when no proxy applies or the caller doesn't have
3048 * permission to use {@code network}.
3049 * @hide
3050 */
3051 public ProxyInfo getProxyForNetwork(Network network) {
3052 try {
3053 return mService.getProxyForNetwork(network);
3054 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003055 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003056 }
3057 }
3058
3059 /**
Paul Jensen12131352014-12-10 15:12:18 -05003060 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3061 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003062 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003063 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003064 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003065 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003066 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003067 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003068 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003069 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003070 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003071 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003072
3073 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003074 * Returns true if the hardware supports the given network type
3075 * else it returns false. This doesn't indicate we have coverage
3076 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003077 * hardware supports it. For example a GSM phone without a SIM
3078 * should still return {@code true} for mobile data, but a wifi only
3079 * tablet would return {@code false}.
3080 *
3081 * @param networkType The network type we'd like to check
3082 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003083 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003084 * @hide
3085 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003086 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003087 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003088 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003089 public boolean isNetworkSupported(int networkType) {
3090 try {
3091 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003092 } catch (RemoteException e) {
3093 throw e.rethrowFromSystemServer();
3094 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003095 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003096
3097 /**
3098 * Returns if the currently active data network is metered. A network is
3099 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003100 * that connection due to monetary costs, data limitations or
3101 * battery/performance issues. You should check this before doing large
3102 * data transfers, and warn the user or delay the operation until another
3103 * network is available.
3104 *
3105 * @return {@code true} if large transfers should be avoided, otherwise
3106 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003107 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003108 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003109 public boolean isActiveNetworkMetered() {
3110 try {
3111 return mService.isActiveNetworkMetered();
3112 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003113 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003114 }
3115 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003116
Robert Greenwalt26744a52013-02-15 10:56:35 -08003117 /**
Sarah Chincf44f2f2020-11-25 12:15:14 -08003118 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003119 *
Sarah Chincf44f2f2020-11-25 12:15:14 -08003120 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003121 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003122 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003123 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003124 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003125 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003126 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003127 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003128 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003129 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003130 }
3131 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003132
3133 /**
3134 * Set the value for enabling/disabling airplane mode
3135 *
3136 * @param enable whether to enable airplane mode or not
3137 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003138 * @hide
3139 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003140 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003141 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003142 android.Manifest.permission.NETWORK_SETTINGS,
3143 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3144 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003145 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003146 public void setAirplaneMode(boolean enable) {
3147 try {
3148 mService.setAirplaneMode(enable);
3149 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003150 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003151 }
3152 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003153
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003154 /**
3155 * Registers the specified {@link NetworkProvider}.
3156 * Each listener must only be registered once. The listener can be unregistered with
3157 * {@link #unregisterNetworkProvider}.
3158 *
3159 * @param provider the provider to register
3160 * @return the ID of the provider. This ID must be used by the provider when registering
3161 * {@link android.net.NetworkAgent}s.
3162 * @hide
3163 */
3164 @SystemApi
paulhu44939832020-03-04 09:43:41 +08003165 @RequiresPermission(anyOf = {
3166 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3167 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003168 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3169 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003170 throw new IllegalStateException("NetworkProviders can only be registered once");
3171 }
3172
3173 try {
3174 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3175 provider.getName());
3176 provider.setProviderId(providerId);
3177 } catch (RemoteException e) {
3178 throw e.rethrowFromSystemServer();
3179 }
3180 return provider.getProviderId();
3181 }
3182
3183 /**
3184 * Unregisters the specified NetworkProvider.
3185 *
3186 * @param provider the provider to unregister
3187 * @hide
3188 */
3189 @SystemApi
paulhu44939832020-03-04 09:43:41 +08003190 @RequiresPermission(anyOf = {
3191 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3192 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003193 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3194 try {
3195 mService.unregisterNetworkProvider(provider.getMessenger());
3196 } catch (RemoteException e) {
3197 throw e.rethrowFromSystemServer();
3198 }
3199 provider.setProviderId(NetworkProvider.ID_NONE);
3200 }
3201
3202
3203 /** @hide exposed via the NetworkProvider class. */
paulhu44939832020-03-04 09:43:41 +08003204 @RequiresPermission(anyOf = {
3205 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3206 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003207 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3208 try {
3209 mService.declareNetworkRequestUnfulfillable(request);
3210 } catch (RemoteException e) {
3211 throw e.rethrowFromSystemServer();
3212 }
3213 }
3214
Chalard Jean44689aa2018-05-02 21:14:54 +09003215 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3216 // of dependent changes that would conflict throughout the automerger graph. Having this
3217 // temporarily helps with the process of going through with all these dependent changes across
3218 // the entire tree.
Paul Jensenc2569432015-02-13 14:18:39 -05003219 /**
3220 * @hide
3221 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana973c7a2019-12-13 19:47:12 +09003222 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003223 */
paulhu44939832020-03-04 09:43:41 +08003224 @RequiresPermission(anyOf = {
3225 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3226 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003227 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colitticf595362020-01-12 22:28:37 +09003228 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003229 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean44689aa2018-05-02 21:14:54 +09003230 }
3231
3232 /**
3233 * @hide
3234 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana973c7a2019-12-13 19:47:12 +09003235 * @return Network corresponding to NetworkAgent.
Chalard Jean44689aa2018-05-02 21:14:54 +09003236 */
paulhu44939832020-03-04 09:43:41 +08003237 @RequiresPermission(anyOf = {
3238 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3239 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003240 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colitticf595362020-01-12 22:28:37 +09003241 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003242 try {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003243 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003244 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003245 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003246 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003247 }
3248
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003249 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003250 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3251 * changes. Should be extended by applications wanting notifications.
3252 *
3253 * A {@code NetworkCallback} is registered by calling
3254 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3255 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003256 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003257 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3258 * A {@code NetworkCallback} should be registered at most once at any time.
3259 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003260 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003261 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003262 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003263 * Called when the framework connects to a new network to evaluate whether it satisfies this
3264 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3265 * callback. There is no guarantee that this new network will satisfy any requests, or that
3266 * the network will stay connected for longer than the time necessary to evaluate it.
3267 * <p>
3268 * Most applications <b>should not</b> act on this callback, and should instead use
3269 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3270 * the framework in properly evaluating the network &mdash; for example, an application that
3271 * can automatically log in to a captive portal without user intervention.
3272 *
3273 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003274 *
3275 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003276 */
paulhua9a6e2a2019-03-22 16:35:06 +08003277 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003278
3279 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003280 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003281 * This callback may be called more than once if the {@link Network} that is
3282 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003283 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003284 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003285 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3286 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003287 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003288 * @hide
3289 */
paulhua9a6e2a2019-03-22 16:35:06 +08003290 public void onAvailable(@NonNull Network network,
3291 @NonNull NetworkCapabilities networkCapabilities,
3292 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003293 // Internally only this method is called when a new network is available, and
3294 // it calls the callback in the same way and order that older versions used
3295 // to call so as not to change the behavior.
3296 onAvailable(network);
3297 if (!networkCapabilities.hasCapability(
3298 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3299 onNetworkSuspended(network);
3300 }
3301 onCapabilitiesChanged(network, networkCapabilities);
3302 onLinkPropertiesChanged(network, linkProperties);
junyulai5ab727b2018-08-07 19:50:45 +08003303 onBlockedStatusChanged(network, blocked);
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003304 }
3305
3306 /**
3307 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003308 *
3309 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3310 * be available at the same time, and onAvailable will be called for each of these as they
3311 * appear.
3312 *
3313 * <p>For callbacks registered with {@link #requestNetwork} and
3314 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3315 * is the new best network for this request and is now tracked by this callback ; this
3316 * callback will no longer receive method calls about other networks that may have been
3317 * passed to this method previously. The previously-best network may have disconnected, or
3318 * it may still be around and the newly-best network may simply be better.
3319 *
3320 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3321 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3322 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3323 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3324 *
3325 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3326 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3327 * this callback as this is prone to race conditions (there is no guarantee the objects
3328 * returned by these methods will be current). Instead, wait for a call to
3329 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3330 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3331 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003332 *
3333 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003334 */
paulhua9a6e2a2019-03-22 16:35:06 +08003335 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003336
3337 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003338 * Called when the network is about to be lost, typically because there are no outstanding
3339 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3340 * with the new replacement network for graceful handover. This method is not guaranteed
3341 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3342 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003343 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003344 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3345 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3346 * this callback as this is prone to race conditions ; calling these methods while in a
3347 * callback may return an outdated or even a null object.
3348 *
3349 * @param network The {@link Network} that is about to be lost.
3350 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3351 * connected for graceful handover; note that the network may still
3352 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003353 */
paulhua9a6e2a2019-03-22 16:35:06 +08003354 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003355
3356 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003357 * Called when a network disconnects or otherwise no longer satisfies this request or
3358 * callback.
3359 *
3360 * <p>If the callback was registered with requestNetwork() or
3361 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3362 * returned by onAvailable() when that network is lost and no other network satisfies
3363 * the criteria of the request.
3364 *
3365 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3366 * each network which no longer satisfies the criteria of the callback.
3367 *
3368 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3369 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3370 * this callback as this is prone to race conditions ; calling these methods while in a
3371 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003372 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003373 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003374 */
paulhua9a6e2a2019-03-22 16:35:06 +08003375 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003376
3377 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003378 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003379 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3380 * requested network request cannot be fulfilled (whether or not a timeout was
3381 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003382 * {@link NetworkRequest} will have already been removed and released, as if
3383 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003384 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003385 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003386
3387 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003388 * Called when the network corresponding to this request changes capabilities but still
3389 * satisfies the requested criteria.
3390 *
3391 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3392 * to be called immediately after {@link #onAvailable}.
3393 *
3394 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3395 * ConnectivityManager methods in this callback as this is prone to race conditions :
3396 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003397 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003398 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003399 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3400 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003401 */
paulhua9a6e2a2019-03-22 16:35:06 +08003402 public void onCapabilitiesChanged(@NonNull Network network,
3403 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003404
3405 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003406 * Called when the network corresponding to this request changes {@link LinkProperties}.
3407 *
3408 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3409 * to be called immediately after {@link #onAvailable}.
3410 *
3411 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3412 * ConnectivityManager methods in this callback as this is prone to race conditions :
3413 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003414 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003415 * @param network The {@link Network} whose link properties have changed.
3416 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003417 */
paulhua9a6e2a2019-03-22 16:35:06 +08003418 public void onLinkPropertiesChanged(@NonNull Network network,
3419 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003420
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003421 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003422 * Called when the network the framework connected to for this request suspends data
3423 * transmission temporarily.
3424 *
3425 * <p>This generally means that while the TCP connections are still live temporarily
3426 * network data fails to transfer. To give a specific example, this is used on cellular
3427 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3428 * means read operations on sockets on this network will block once the buffers are
3429 * drained, and write operations will block once the buffers are full.
3430 *
3431 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3432 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3433 * this callback as this is prone to race conditions (there is no guarantee the objects
3434 * returned by these methods will be current).
3435 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003436 * @hide
3437 */
paulhua9a6e2a2019-03-22 16:35:06 +08003438 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003439
3440 /**
3441 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003442 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3443 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003444
3445 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3446 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3447 * this callback as this is prone to race conditions : calling these methods while in a
3448 * callback may return an outdated or even a null object.
3449 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003450 * @hide
3451 */
paulhua9a6e2a2019-03-22 16:35:06 +08003452 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003453
junyulai5ab727b2018-08-07 19:50:45 +08003454 /**
3455 * Called when access to the specified network is blocked or unblocked.
3456 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003457 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3458 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3459 * this callback as this is prone to race conditions : calling these methods while in a
3460 * callback may return an outdated or even a null object.
3461 *
junyulai5ab727b2018-08-07 19:50:45 +08003462 * @param network The {@link Network} whose blocked status has changed.
3463 * @param blocked The blocked status of this {@link Network}.
3464 */
junyulai61143782019-03-04 22:45:36 +08003465 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003466
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003467 private NetworkRequest networkRequest;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003468 }
3469
Hugo Benichi145e3792017-05-11 13:16:17 +09003470 /**
3471 * Constant error codes used by ConnectivityService to communicate about failures and errors
3472 * across a Binder boundary.
3473 * @hide
3474 */
3475 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003476 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003477 }
3478
3479 /** @hide */
3480 public static class TooManyRequestsException extends RuntimeException {}
3481
3482 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3483 switch (e.errorCode) {
3484 case Errors.TOO_MANY_REQUESTS:
3485 return new TooManyRequestsException();
3486 default:
3487 Log.w(TAG, "Unknown service error code " + e.errorCode);
3488 return new RuntimeException(e);
3489 }
3490 }
3491
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003492 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003493 /** @hide */
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003494 public static final int CALLBACK_PRECHECK = BASE + 1;
3495 /** @hide */
3496 public static final int CALLBACK_AVAILABLE = BASE + 2;
3497 /** @hide arg1 = TTL */
3498 public static final int CALLBACK_LOSING = BASE + 3;
3499 /** @hide */
3500 public static final int CALLBACK_LOST = BASE + 4;
3501 /** @hide */
3502 public static final int CALLBACK_UNAVAIL = BASE + 5;
3503 /** @hide */
3504 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3505 /** @hide */
3506 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003507 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichi4802c802017-03-23 22:40:44 +09003508 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003509 /** @hide */
Hugo Benichi4802c802017-03-23 22:40:44 +09003510 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003511 /** @hide */
Hugo Benichi4802c802017-03-23 22:40:44 +09003512 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai5ab727b2018-08-07 19:50:45 +08003513 /** @hide */
3514 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003515
Erik Kline66721822015-11-25 12:49:38 +09003516 /** @hide */
3517 public static String getCallbackName(int whichCallback) {
3518 switch (whichCallback) {
3519 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3520 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3521 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3522 case CALLBACK_LOST: return "CALLBACK_LOST";
3523 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3524 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3525 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003526 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3527 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3528 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003529 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003530 default:
3531 return Integer.toString(whichCallback);
3532 }
3533 }
3534
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003535 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003536 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003537 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003538
Hugo Benichife3325f2016-07-06 22:53:17 +09003539 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003540 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003541 }
3542
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003543 CallbackHandler(Handler handler) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003544 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003545 }
3546
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003547 @Override
3548 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003549 if (message.what == EXPIRE_LEGACY_REQUEST) {
3550 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3551 return;
3552 }
3553
3554 final NetworkRequest request = getObject(message, NetworkRequest.class);
3555 final Network network = getObject(message, Network.class);
3556 final NetworkCallback callback;
3557 synchronized (sCallbacks) {
3558 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003559 if (callback == null) {
3560 Log.w(TAG,
3561 "callback not found for " + getCallbackName(message.what) + " message");
3562 return;
3563 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003564 if (message.what == CALLBACK_UNAVAIL) {
3565 sCallbacks.remove(request);
3566 callback.networkRequest = ALREADY_UNREGISTERED;
3567 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003568 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003569 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003570 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003571 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003572
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003573 switch (message.what) {
3574 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003575 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003576 break;
3577 }
3578 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003579 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3580 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai5ab727b2018-08-07 19:50:45 +08003581 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003582 break;
3583 }
3584 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003585 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003586 break;
3587 }
3588 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003589 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003590 break;
3591 }
3592 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003593 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003594 break;
3595 }
3596 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003597 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3598 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003599 break;
3600 }
3601 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003602 LinkProperties lp = getObject(message, LinkProperties.class);
3603 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003604 break;
3605 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003606 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003607 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003608 break;
3609 }
3610 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003611 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003612 break;
3613 }
junyulai5ab727b2018-08-07 19:50:45 +08003614 case CALLBACK_BLK_CHANGED: {
3615 boolean blocked = message.arg1 != 0;
3616 callback.onBlockedStatusChanged(network, blocked);
3617 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003618 }
3619 }
3620
Hugo Benichife3325f2016-07-06 22:53:17 +09003621 private <T> T getObject(Message msg, Class<T> c) {
3622 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003623 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003624 }
3625
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003626 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003627 synchronized (sCallbacks) {
3628 if (sCallbackHandler == null) {
3629 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003630 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003631 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003632 }
3633 }
3634
Hugo Benichiec180d52017-02-03 14:18:44 +09003635 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3636 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003637
Hugo Benichiec180d52017-02-03 14:18:44 +09003638 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaid1a78162021-01-11 16:53:38 +08003639 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003640 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003641 checkCallbackNotNull(callback);
junyulaid1a78162021-01-11 16:53:38 +08003642 Preconditions.checkArgument(
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09003643 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3644 "null NetworkCapabilities");
Hugo Benichife3325f2016-07-06 22:53:17 +09003645 final NetworkRequest request;
Roshan Pius34dc4be2020-01-16 12:17:17 -08003646 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003647 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003648 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003649 if (callback.networkRequest != null
3650 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003651 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3652 // and requests (http://b/20701525).
3653 Log.e(TAG, "NetworkCallback was already registered");
3654 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003655 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003656 Binder binder = new Binder();
junyulaid1a78162021-01-11 16:53:38 +08003657 if (reqType == LISTEN) {
Roshan Pius34dc4be2020-01-16 12:17:17 -08003658 request = mService.listenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08003659 need, messenger, binder, callingPackageName,
3660 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003661 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003662 request = mService.requestNetwork(
junyulaid1a78162021-01-11 16:53:38 +08003663 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3664 callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003665 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003666 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003667 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003668 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003669 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003670 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003671 } catch (RemoteException e) {
3672 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003673 } catch (ServiceSpecificException e) {
3674 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003675 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003676 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003677 }
3678
3679 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003680 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003681 *
markchieneddbe2b2020-03-18 21:16:15 +08003682 * This API is only for use in internal system code that requests networks with legacy type and
3683 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchienddd59372020-01-14 00:55:21 +08003684 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003685 *
markchienddd59372020-01-14 00:55:21 +08003686 * @param request {@link NetworkRequest} describing this request.
markchienddd59372020-01-14 00:55:21 +08003687 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3688 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3689 * be a positive value (i.e. >0).
3690 * @param legacyType to specify the network type(#TYPE_*).
3691 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchieneddbe2b2020-03-18 21:16:15 +08003692 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3693 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003694 *
3695 * @hide
3696 */
markchienddd59372020-01-14 00:55:21 +08003697 @SystemApi
markchieneddbe2b2020-03-18 21:16:15 +08003698 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003699 public void requestNetwork(@NonNull NetworkRequest request,
markchieneddbe2b2020-03-18 21:16:15 +08003700 int timeoutMs, int legacyType, @NonNull Handler handler,
3701 @NonNull NetworkCallback networkCallback) {
3702 if (legacyType == TYPE_NONE) {
3703 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3704 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003705 CallbackHandler cbHandler = new CallbackHandler(handler);
3706 NetworkCapabilities nc = request.networkCapabilities;
3707 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003708 }
3709
3710 /**
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +09003711 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003712 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003713 * <p>This method will attempt to find the best network that matches the passed
3714 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3715 * criteria. The platform will evaluate which network is the best at its own discretion.
3716 * Throughput, latency, cost per byte, policy, user preference and other considerations
3717 * may be factored in the decision of what is considered the best network.
3718 *
3719 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3720 * matching this request, while always attempting to match the request to a better network if
3721 * possible. If a better match is found, the platform will switch this request to the now-best
3722 * network and inform the app of the newly best network by invoking
3723 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3724 * will not try to maintain any other network than the best one currently matching the request:
3725 * a network not matching any network request may be disconnected at any time.
3726 *
3727 * <p>For example, an application could use this method to obtain a connected cellular network
3728 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3729 * radio to consume additional power. Or, an application could inform the system that it wants
3730 * a network supporting sending MMSes and have the system let it know about the currently best
3731 * MMS-supporting network through the provided {@link NetworkCallback}.
3732 *
3733 * <p>The status of the request can be followed by listening to the various callbacks described
3734 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3735 * used to direct traffic to the network (although accessing some networks may be subject to
3736 * holding specific permissions). Callers will learn about the specific characteristics of the
3737 * network through
3738 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3739 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3740 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3741 * matching the request at any given time; therefore when a better network matching the request
3742 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3743 * with the new network after which no further updates are given about the previously-best
3744 * network, unless it becomes the best again at some later time. All callbacks are invoked
3745 * in order on the same thread, which by default is a thread created by the framework running
3746 * in the app.
3747 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3748 * callbacks are invoked.
3749 *
3750 * <p>This{@link NetworkRequest} will live until released via
3751 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3752 * which point the system may let go of the network at any time.
3753 *
3754 * <p>A version of this method which takes a timeout is
3755 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3756 * wait for a limited amount of time for the network to become unavailable.
3757 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003758 * <p>It is presently unsupported to request a network with mutable
3759 * {@link NetworkCapabilities} such as
3760 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3761 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3762 * as these {@code NetworkCapabilities} represent states that a particular
3763 * network may never attain, and whether a network will attain these states
3764 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09003765 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003766 *
3767 * <p>This method requires the caller to hold either the
3768 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3769 * or the ability to modify system settings as determined by
3770 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003771 *
Chalard Jean7f06b342020-05-20 16:11:50 +09003772 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3773 * number of outstanding requests to 100 per app (identified by their UID), shared with
3774 * all variants of this method, of {@link #registerNetworkCallback} as well as
3775 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3776 * Requesting a network with this method will count toward this limit. If this limit is
3777 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3778 * make sure to unregister the callbacks with
3779 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3780 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003781 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003782 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3783 * the callback must not be shared - it uniquely specifies this request.
3784 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09003785 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3786 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09003787 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003788 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003789 public void requestNetwork(@NonNull NetworkRequest request,
3790 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003791 requestNetwork(request, networkCallback, getDefaultHandler());
3792 }
3793
3794 /**
3795 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3796 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003797 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3798 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003799 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003800 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003801 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3802 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003803 *
3804 * @param request {@link NetworkRequest} describing this request.
3805 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3806 * the callback must not be shared - it uniquely specifies this request.
3807 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003808 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003809 public void requestNetwork(@NonNull NetworkRequest request,
3810 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003811 CallbackHandler cbHandler = new CallbackHandler(handler);
markchieneddbe2b2020-03-18 21:16:15 +08003812 NetworkCapabilities nc = request.networkCapabilities;
3813 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003814 }
3815
3816 /**
Etan Cohen67e58a02017-03-01 12:47:28 -08003817 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3818 * by a timeout.
3819 *
3820 * This function behaves identically to the non-timed-out version
3821 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3822 * is not found within the given time (in milliseconds) the
3823 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3824 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3825 * not have to be released if timed-out (it is automatically released). Unregistering a
3826 * request that timed out is not an error.
3827 *
3828 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3829 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3830 * for that purpose. Calling this method will attempt to bring up the requested network.
3831 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003832 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003833 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3834 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08003835 *
3836 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003837 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3838 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003839 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3840 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3841 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08003842 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003843 public void requestNetwork(@NonNull NetworkRequest request,
3844 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003845 checkTimeout(timeoutMs);
markchieneddbe2b2020-03-18 21:16:15 +08003846 NetworkCapabilities nc = request.networkCapabilities;
3847 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3848 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003849 }
3850
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003851 /**
3852 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3853 * by a timeout.
3854 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003855 * This method behaves identically to
3856 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3857 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08003858 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003859 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003860 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3861 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003862 *
3863 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003864 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3865 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003866 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003867 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3868 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003869 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003870 public void requestNetwork(@NonNull NetworkRequest request,
3871 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003872 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003873 CallbackHandler cbHandler = new CallbackHandler(handler);
markchieneddbe2b2020-03-18 21:16:15 +08003874 NetworkCapabilities nc = request.networkCapabilities;
3875 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003876 }
3877
3878 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003879 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003880 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003881 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08003882 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04003883 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3884 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003885 */
Erik Klinefb087f12014-11-19 12:12:24 +09003886 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003887
3888 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003889 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003890 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003891 * {@link android.content.Intent#getParcelableExtra(String)}.
3892 */
Erik Klinefb087f12014-11-19 12:12:24 +09003893 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003894
3895
3896 /**
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +09003897 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003898 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08003899 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003900 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003901 * the request may outlive the calling application and get called back when a suitable
3902 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003903 * <p>
3904 * The operation is an Intent broadcast that goes to a broadcast receiver that
3905 * you registered with {@link Context#registerReceiver} or through the
3906 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3907 * <p>
3908 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09003909 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3910 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003911 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003912 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003913 * Intent to reserve the network or it will be released shortly after the Intent
3914 * is processed.
3915 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04003916 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003917 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003918 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003919 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08003920 * The request may be released normally by calling
3921 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003922 * <p>It is presently unsupported to request a network with either
3923 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3924 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3925 * as these {@code NetworkCapabilities} represent states that a particular
3926 * network may never attain, and whether a network will attain these states
3927 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09003928 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003929 *
Chalard Jean7f06b342020-05-20 16:11:50 +09003930 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3931 * number of outstanding requests to 100 per app (identified by their UID), shared with
3932 * all variants of this method, of {@link #registerNetworkCallback} as well as
3933 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3934 * Requesting a network with this method will count toward this limit. If this limit is
3935 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3936 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3937 * or {@link #releaseNetworkRequest(PendingIntent)}.
3938 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003939 * <p>This method requires the caller to hold either the
3940 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3941 * or the ability to modify system settings as determined by
3942 * {@link android.provider.Settings.System#canWrite}.</p>
3943 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003944 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003945 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003946 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08003947 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09003948 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3949 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09003950 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003951 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003952 public void requestNetwork(@NonNull NetworkRequest request,
3953 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003954 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003955 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003956 try {
Roshan Pius34dc4be2020-01-16 12:17:17 -08003957 mService.pendingRequestForNetwork(
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07003958 request.networkCapabilities, operation, mContext.getOpPackageName(),
3959 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003960 } catch (RemoteException e) {
3961 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003962 } catch (ServiceSpecificException e) {
3963 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003964 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003965 }
3966
3967 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08003968 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3969 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09003970 * This method has the same behavior as
3971 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08003972 * releasing network resources and disconnecting.
3973 *
3974 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3975 * PendingIntent passed to
3976 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3977 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3978 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003979 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003980 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003981 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003982 try {
3983 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003984 } catch (RemoteException e) {
3985 throw e.rethrowFromSystemServer();
3986 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08003987 }
3988
Hugo Benichiff4bf602017-05-09 15:19:01 +09003989 private static void checkPendingIntentNotNull(PendingIntent intent) {
3990 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3991 }
3992
3993 private static void checkCallbackNotNull(NetworkCallback callback) {
3994 Preconditions.checkNotNull(callback, "null NetworkCallback");
3995 }
3996
3997 private static void checkTimeout(int timeoutMs) {
3998 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin94c30992014-11-05 10:32:09 -08003999 }
4000
4001 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004002 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004003 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004004 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4005 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004006 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004007 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4008 * number of outstanding requests to 100 per app (identified by their UID), shared with
4009 * all variants of this method, of {@link #requestNetwork} as well as
4010 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4011 * Requesting a network with this method will count toward this limit. If this limit is
4012 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4013 * make sure to unregister the callbacks with
4014 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4015 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004016 * @param request {@link NetworkRequest} describing this request.
4017 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4018 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004019 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004020 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004021 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004022 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004023 public void registerNetworkCallback(@NonNull NetworkRequest request,
4024 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004025 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4026 }
4027
4028 /**
4029 * Registers to receive notifications about all networks which satisfy the given
4030 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004031 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4032 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004033 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004034 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4035 * number of outstanding requests to 100 per app (identified by their UID), shared with
4036 * all variants of this method, of {@link #requestNetwork} as well as
4037 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4038 * Requesting a network with this method will count toward this limit. If this limit is
4039 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4040 * make sure to unregister the callbacks with
4041 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4042 *
4043 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004044 * @param request {@link NetworkRequest} describing this request.
4045 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4046 * networks change state.
4047 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004048 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004049 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004050 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004051 public void registerNetworkCallback(@NonNull NetworkRequest request,
4052 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004053 CallbackHandler cbHandler = new CallbackHandler(handler);
4054 NetworkCapabilities nc = request.networkCapabilities;
4055 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004056 }
4057
4058 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004059 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4060 * {@link NetworkRequest}.
4061 *
4062 * This function behaves identically to the version that takes a NetworkCallback, but instead
4063 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4064 * the request may outlive the calling application and get called back when a suitable
4065 * network is found.
4066 * <p>
4067 * The operation is an Intent broadcast that goes to a broadcast receiver that
4068 * you registered with {@link Context#registerReceiver} or through the
4069 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4070 * <p>
4071 * The operation Intent is delivered with two extras, a {@link Network} typed
4072 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4073 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4074 * the original requests parameters.
4075 * <p>
4076 * If there is already a request for this Intent registered (with the equality of
4077 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4078 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4079 * <p>
4080 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004081 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004082 *
4083 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4084 * number of outstanding requests to 100 per app (identified by their UID), shared with
4085 * all variants of this method, of {@link #requestNetwork} as well as
4086 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4087 * Requesting a network with this method will count toward this limit. If this limit is
4088 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4089 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4090 * or {@link #releaseNetworkRequest(PendingIntent)}.
4091 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004092 * @param request {@link NetworkRequest} describing this request.
4093 * @param operation Action to perform when the network is available (corresponds
4094 * to the {@link NetworkCallback#onAvailable} call. Typically
4095 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004096 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004097 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004098 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004099 public void registerNetworkCallback(@NonNull NetworkRequest request,
4100 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004101 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004102 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004103 try {
Roshan Pius34dc4be2020-01-16 12:17:17 -08004104 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004105 request.networkCapabilities, operation, mContext.getOpPackageName(),
4106 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004107 } catch (RemoteException e) {
4108 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004109 } catch (ServiceSpecificException e) {
4110 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004111 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004112 }
4113
4114 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004115 * Registers to receive notifications about changes in the application's default network. This
4116 * may be a physical network or a virtual network, such as a VPN that applies to the
4117 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004118 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004119 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004120 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4121 * number of outstanding requests to 100 per app (identified by their UID), shared with
4122 * all variants of this method, of {@link #requestNetwork} as well as
4123 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4124 * Requesting a network with this method will count toward this limit. If this limit is
4125 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4126 * make sure to unregister the callbacks with
4127 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4128 *
Erik Klinee0aed632016-03-16 15:31:39 +09004129 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004130 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004131 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004132 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004133 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004134 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004135 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004136 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4137 }
4138
4139 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004140 * Registers to receive notifications about changes in the application's default network. This
4141 * may be a physical network or a virtual network, such as a VPN that applies to the
4142 * application. The callbacks will continue to be called until either the application exits or
4143 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4144 *
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
4152 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4153 *
4154 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4155 * application's default network changes.
4156 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4157 * @throws RuntimeException if the app already has too many callbacks registered.
4158 */
4159 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4160 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4161 @NonNull Handler handler) {
4162 CallbackHandler cbHandler = new CallbackHandler(handler);
4163 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4164 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4165 }
4166
4167 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004168 * Registers to receive notifications about changes in the system default network. The callbacks
4169 * will continue to be called until either the application exits or
4170 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004171 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004172 * This method should not be used to determine networking state seen by applications, because in
4173 * many cases, most or even all application traffic may not use the default network directly,
4174 * and traffic from different applications may go on different networks by default. As an
4175 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4176 * and not onto the system default network. Applications or system components desiring to do
4177 * determine network state as seen by applications should use other methods such as
4178 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4179 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004180 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4181 * number of outstanding requests to 100 per app (identified by their UID), shared with
4182 * all variants of this method, of {@link #requestNetwork} as well as
4183 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4184 * Requesting a network with this method will count toward this limit. If this limit is
4185 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4186 * make sure to unregister the callbacks with
4187 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4188 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004189 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4190 * system default network changes.
4191 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004192 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004193 *
4194 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004195 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004196 @SystemApi(client = MODULE_LIBRARIES)
4197 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4198 @RequiresPermission(anyOf = {
4199 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4200 android.Manifest.permission.NETWORK_SETTINGS})
4201 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004202 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004203 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004204 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004205 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004206 }
4207
4208 /**
fenglu73169332015-04-21 17:12:05 -07004209 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4210 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4211 * network connection for updated bandwidth information. The caller will be notified via
4212 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004213 * method assumes that the caller has previously called
4214 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4215 * changes.
fenglu76564332015-03-20 11:29:56 -07004216 *
fenglu41808e82015-04-27 14:28:04 -07004217 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004218 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004219 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004220 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004221 try {
fenglu73169332015-04-21 17:12:05 -07004222 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004223 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004224 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004225 }
4226 }
4227
4228 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004229 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004230 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4231 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4232 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004233 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4234 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004235 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004236 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4237 * triggering it as soon as this call returns.
4238 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004239 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004240 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004241 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004242 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004243 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004244 final List<NetworkRequest> reqs = new ArrayList<>();
4245 // Find all requests associated to this callback and stop callback triggers immediately.
4246 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4247 synchronized (sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004248 Preconditions.checkArgument(networkCallback.networkRequest != null,
4249 "NetworkCallback was not registered");
Etan Cohene0e2ca92019-04-16 15:07:55 -07004250 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4251 Log.d(TAG, "NetworkCallback was already unregistered");
4252 return;
4253 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004254 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4255 if (e.getValue() == networkCallback) {
4256 reqs.add(e.getKey());
4257 }
4258 }
4259 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4260 for (NetworkRequest r : reqs) {
4261 try {
4262 mService.releaseNetworkRequest(r);
4263 } catch (RemoteException e) {
4264 throw e.rethrowFromSystemServer();
4265 }
4266 // Only remove mapping if rpc was successful.
4267 sCallbacks.remove(r);
4268 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004269 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004270 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004271 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004272
4273 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004274 * Unregisters a callback previously registered via
4275 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4276 *
4277 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4278 * PendingIntent passed to
4279 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4280 * Cannot be null.
4281 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004282 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004283 releaseNetworkRequest(operation);
4284 }
4285
4286 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004287 * Informs the system whether it should switch to {@code network} regardless of whether it is
4288 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4289 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4290 * the system default network regardless of any other network that's currently connected. If
4291 * {@code always} is true, then the choice is remembered, so that the next time the user
4292 * connects to this network, the system will switch to it.
4293 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004294 * @param network The network to accept.
4295 * @param accept Whether to accept the network even if unvalidated.
4296 * @param always Whether to remember this choice in the future.
4297 *
4298 * @hide
4299 */
lucaslin25a50472019-03-12 13:08:03 +08004300 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004301 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4302 try {
4303 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004304 } catch (RemoteException e) {
4305 throw e.rethrowFromSystemServer();
4306 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004307 }
4308
4309 /**
lucaslin25a50472019-03-12 13:08:03 +08004310 * Informs the system whether it should consider the network as validated even if it only has
4311 * partial connectivity. If {@code accept} is true, then the network will be considered as
4312 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4313 * is remembered, so that the next time the user connects to this network, the system will
4314 * switch to it.
4315 *
4316 * @param network The network to accept.
4317 * @param accept Whether to consider the network as validated even if it has partial
4318 * connectivity.
4319 * @param always Whether to remember this choice in the future.
4320 *
4321 * @hide
4322 */
4323 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4324 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4325 try {
4326 mService.setAcceptPartialConnectivity(network, accept, always);
4327 } catch (RemoteException e) {
4328 throw e.rethrowFromSystemServer();
4329 }
4330 }
4331
4332 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004333 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4334 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4335 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4336 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4337 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004338 * @param network The network to accept.
4339 *
4340 * @hide
4341 */
lucaslin25a50472019-03-12 13:08:03 +08004342 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004343 public void setAvoidUnvalidated(Network network) {
4344 try {
4345 mService.setAvoidUnvalidated(network);
4346 } catch (RemoteException e) {
4347 throw e.rethrowFromSystemServer();
4348 }
4349 }
4350
4351 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004352 * Requests that the system open the captive portal app on the specified network.
4353 *
4354 * @param network The network to log into.
4355 *
4356 * @hide
4357 */
paulhud70b7dd2019-08-12 16:25:11 +08004358 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004359 public void startCaptivePortalApp(Network network) {
4360 try {
4361 mService.startCaptivePortalApp(network);
4362 } catch (RemoteException e) {
4363 throw e.rethrowFromSystemServer();
4364 }
4365 }
4366
4367 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004368 * Requests that the system open the captive portal app with the specified extras.
4369 *
4370 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4371 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004372 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004373 * @param appExtras Extras to include in the app start intent.
4374 * @hide
4375 */
4376 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004377 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004378 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004379 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004380 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004381 } catch (RemoteException e) {
4382 throw e.rethrowFromSystemServer();
4383 }
4384 }
4385
4386 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004387 * Determine whether the device is configured to avoid bad wifi.
4388 * @hide
4389 */
4390 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004391 @RequiresPermission(anyOf = {
4392 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4393 android.Manifest.permission.NETWORK_STACK})
4394 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004395 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004396 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004397 } catch (RemoteException e) {
4398 throw e.rethrowFromSystemServer();
4399 }
4400 }
4401
4402 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004403 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4404 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004405 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4406 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004407 *
4408 * An example of such an operation might be a time-sensitive foreground activity, such as a
4409 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4410 */
4411 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4412
4413 /**
4414 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4415 * a backup channel for traffic that is primarily going over another network.
4416 *
4417 * An example might be maintaining backup connections to peers or servers for the purpose of
4418 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4419 * on backup paths should be negligible compared to the traffic on the main path.
4420 */
4421 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4422
4423 /**
4424 * It is acceptable to use metered data to improve network latency and performance.
4425 */
4426 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4427
4428 /**
4429 * Return value to use for unmetered networks. On such networks we currently set all the flags
4430 * to true.
4431 * @hide
4432 */
4433 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4434 MULTIPATH_PREFERENCE_HANDOVER |
4435 MULTIPATH_PREFERENCE_RELIABILITY |
4436 MULTIPATH_PREFERENCE_PERFORMANCE;
4437
4438 /** @hide */
4439 @Retention(RetentionPolicy.SOURCE)
4440 @IntDef(flag = true, value = {
4441 MULTIPATH_PREFERENCE_HANDOVER,
4442 MULTIPATH_PREFERENCE_RELIABILITY,
4443 MULTIPATH_PREFERENCE_PERFORMANCE,
4444 })
4445 public @interface MultipathPreference {
4446 }
4447
4448 /**
4449 * Provides a hint to the calling application on whether it is desirable to use the
4450 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4451 * for multipath data transfer on this network when it is not the system default network.
4452 * Applications desiring to use multipath network protocols should call this method before
4453 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004454 *
4455 * @param network The network on which the application desires to use multipath data.
4456 * If {@code null}, this method will return the a preference that will generally
4457 * apply to metered networks.
4458 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4459 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004460 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004461 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004462 try {
4463 return mService.getMultipathPreference(network);
4464 } catch (RemoteException e) {
4465 throw e.rethrowFromSystemServer();
4466 }
4467 }
4468
4469 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004470 * Resets all connectivity manager settings back to factory defaults.
4471 * @hide
4472 */
paulhud70b7dd2019-08-12 16:25:11 +08004473 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scottd3bb5082015-03-30 13:17:11 -07004474 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004475 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004476 mService.factoryReset();
Amos Bianchiddadca42020-03-04 11:07:38 -08004477 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004478 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004479 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004480 }
4481 }
4482
4483 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004484 * Binds the current process to {@code network}. All Sockets created in the future
4485 * (and not explicitly bound via a bound SocketFactory from
4486 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4487 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4488 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4489 * work and all host name resolutions will fail. This is by design so an application doesn't
4490 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4491 * To clear binding pass {@code null} for {@code network}. Using individually bound
4492 * Sockets created by Network.getSocketFactory().createSocket() and
4493 * performing network-specific host name resolutions via
4494 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004495 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004496 *
4497 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4498 * the current binding.
4499 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4500 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004501 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004502 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004503 // instantiated.
4504 return setProcessDefaultNetwork(network);
4505 }
4506
4507 /**
4508 * Binds the current process to {@code network}. All Sockets created in the future
4509 * (and not explicitly bound via a bound SocketFactory from
4510 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4511 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4512 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4513 * work and all host name resolutions will fail. This is by design so an application doesn't
4514 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4515 * To clear binding pass {@code null} for {@code network}. Using individually bound
4516 * Sockets created by Network.getSocketFactory().createSocket() and
4517 * performing network-specific host name resolutions via
4518 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4519 * {@code setProcessDefaultNetwork}.
4520 *
4521 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4522 * the current binding.
4523 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4524 * @deprecated This function can throw {@link IllegalStateException}. Use
4525 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4526 * is a direct replacement.
4527 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004528 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004529 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004530 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004531 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4532
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004533 if (netId != NETID_UNSET) {
4534 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004535 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004536
4537 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4538 return false;
4539 }
4540
4541 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004542 // Set HTTP proxy system properties to match network.
4543 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004544 try {
Remi NGUYEN VAN9ff113b2021-02-03 10:18:20 +09004545 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004546 } catch (SecurityException e) {
4547 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4548 Log.e(TAG, "Can't set proxy properties", e);
4549 }
Paul Jensen99c36662014-08-27 12:38:45 -04004550 // Must flush DNS cache as new network may have different DNS resolutions.
4551 InetAddress.clearDnsCache();
4552 // Must flush socket pool as idle sockets will be bound to previous network and may
4553 // cause subsequent fetches to be performed on old network.
4554 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004555 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004556
4557 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004558 }
4559
4560 /**
4561 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004562 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004563 *
4564 * @return {@code Network} to which this process is bound, or {@code null}.
4565 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004566 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004567 public Network getBoundNetworkForProcess() {
4568 // Forcing callers to call thru non-static function ensures ConnectivityManager
4569 // instantiated.
4570 return getProcessDefaultNetwork();
4571 }
4572
4573 /**
4574 * Returns the {@link Network} currently bound to this process via
4575 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4576 *
4577 * @return {@code Network} to which this process is bound, or {@code null}.
4578 * @deprecated Using this function can lead to other functions throwing
4579 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4580 * {@code getBoundNetworkForProcess} is a direct replacement.
4581 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004582 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004583 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004584 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004585 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004586 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004587 return new Network(netId);
4588 }
4589
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004590 private void unsupportedStartingFrom(int version) {
4591 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004592 // The getApplicationInfo() call we make below is not supported in system context. Let
4593 // the call through here, and rely on the fact that ConnectivityService will refuse to
4594 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004595 return;
4596 }
4597
4598 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4599 throw new UnsupportedOperationException(
4600 "This method is not supported in target SDK version " + version + " and above");
4601 }
4602 }
4603
4604 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4605 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004606 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004607 // remove these exemptions. Note that this check is not secure, and apps can still access these
4608 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4609 // so is unsupported and may break in the future. http://b/22728205
4610 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07004611 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004612 }
4613
Paul Jensene98c6e02014-05-29 10:12:39 -04004614 /**
4615 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04004616 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04004617 *
4618 * @param network The {@link Network} to bind host resolutions from the current process to, or
4619 * {@code null} to clear the current binding.
4620 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4621 * @hide
4622 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4623 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004624 @Deprecated
Mathew Inwood5a09a712020-11-04 09:29:36 +00004625 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04004626 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04004627 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09004628 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04004629 }
Felipe Lemed16384b2016-01-22 09:44:57 -08004630
4631 /**
4632 * Device is not restricting metered network activity while application is running on
4633 * background.
4634 */
4635 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4636
4637 /**
4638 * Device is restricting metered network activity while application is running on background,
4639 * but application is allowed to bypass it.
4640 * <p>
4641 * In this state, application should take action to mitigate metered network access.
4642 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4643 */
4644 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4645
4646 /**
4647 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08004648 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08004649 * In this state, application should not try to use the network while running on background,
4650 * because it would be denied.
4651 */
4652 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4653
Felipe Leme6a5b7692016-01-27 14:46:39 -08004654 /**
4655 * A change in the background metered network activity restriction has occurred.
4656 * <p>
4657 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4658 * applies to them.
4659 * <p>
4660 * This is only sent to registered receivers, not manifest receivers.
4661 */
4662 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4663 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4664 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4665
Felipe Leme1b42ef92016-01-25 11:48:04 -08004666 /** @hide */
4667 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08004668 @IntDef(flag = false, value = {
4669 RESTRICT_BACKGROUND_STATUS_DISABLED,
4670 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4671 RESTRICT_BACKGROUND_STATUS_ENABLED,
4672 })
Felipe Lemed16384b2016-01-22 09:44:57 -08004673 public @interface RestrictBackgroundStatus {
4674 }
4675
4676 private INetworkPolicyManager getNetworkPolicyManager() {
4677 synchronized (this) {
4678 if (mNPManager != null) {
4679 return mNPManager;
4680 }
4681 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4682 .getService(Context.NETWORK_POLICY_SERVICE));
4683 return mNPManager;
4684 }
4685 }
4686
4687 /**
4688 * Determines if the calling application is subject to metered network restrictions while
4689 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07004690 *
4691 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4692 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4693 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08004694 */
4695 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4696 try {
4697 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4698 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004699 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08004700 }
4701 }
Ricky Waid53cf002018-01-23 04:09:45 +00004702
4703 /**
4704 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00004705 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4706 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00004707 *
4708 * @return Hash of network watchlist config file. Null if config does not exist.
4709 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004710 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00004711 public byte[] getNetworkWatchlistConfigHash() {
4712 try {
4713 return mService.getNetworkWatchlistConfigHash();
4714 } catch (RemoteException e) {
4715 Log.e(TAG, "Unable to get watchlist config hash");
4716 throw e.rethrowFromSystemServer();
4717 }
4718 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004719
4720 /**
4721 * Returns the {@code uid} of the owner of a network connection.
4722 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08004723 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4724 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004725 * @param local The local {@link InetSocketAddress} of a connection.
4726 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004727 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08004728 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4729 * android.os.Process#INVALID_UID} if the connection is not found.
4730 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4731 * user.
4732 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004733 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08004734 public int getConnectionOwnerUid(
4735 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004736 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4737 try {
4738 return mService.getConnectionOwnerUid(connectionInfo);
4739 } catch (RemoteException e) {
4740 throw e.rethrowFromSystemServer();
4741 }
4742 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004743
4744 private void printStackTrace() {
4745 if (DEBUG) {
4746 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4747 final StringBuffer sb = new StringBuffer();
4748 for (int i = 3; i < callStack.length; i++) {
4749 final String stackTrace = callStack[i].toString();
4750 if (stackTrace == null || stackTrace.contains("android.os")) {
4751 break;
4752 }
4753 sb.append(" [").append(stackTrace).append("]");
4754 }
4755 Log.d(TAG, "StackLog:" + sb.toString());
4756 }
4757 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004758
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004759 /** @hide */
4760 public TestNetworkManager startOrGetTestNetworkManager() {
4761 final IBinder tnBinder;
4762 try {
4763 tnBinder = mService.startOrGetTestNetworkService();
4764 } catch (RemoteException e) {
4765 throw e.rethrowFromSystemServer();
4766 }
4767
4768 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4769 }
4770
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004771 /** @hide */
4772 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4773 return new ConnectivityDiagnosticsManager(mContext, mService);
4774 }
4775
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004776 /**
4777 * Simulates a Data Stall for the specified Network.
4778 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004779 * <p>This method should only be used for tests.
4780 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004781 * <p>The caller must be the owner of the specified Network.
4782 *
4783 * @param detectionMethod The detection method used to identify the Data Stall.
4784 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4785 * @param network The Network for which a Data Stall is being simluated.
4786 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4787 * @throws SecurityException if the caller is not the owner of the given network.
4788 * @hide
4789 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004790 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004791 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4792 android.Manifest.permission.NETWORK_STACK})
4793 public void simulateDataStall(int detectionMethod, long timestampMillis,
4794 @NonNull Network network, @NonNull PersistableBundle extras) {
4795 try {
4796 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4797 } catch (RemoteException e) {
4798 e.rethrowFromSystemServer();
4799 }
4800 }
James Mattisdcea9fb2020-10-28 21:48:54 -07004801
Daniel Bright60f02ed2020-06-15 16:10:01 -07004802 @NonNull
4803 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4804
4805 /**
4806 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4807 * receive available QoS events related to the {@link Network} and local ip + port
4808 * specified within socketInfo.
4809 * <p/>
4810 * The same {@link QosCallback} must be unregistered before being registered a second time,
4811 * otherwise {@link QosCallbackRegistrationException} is thrown.
4812 * <p/>
4813 * This API does not, in itself, require any permission if called with a network that is not
4814 * restricted. However, the underlying implementation currently only supports the IMS network,
4815 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4816 * useful, because they'd never be called back on networks that they would have access to.
4817 *
4818 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4819 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4820 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4821 * @throws RuntimeException if the app already has too many callbacks registered.
4822 *
4823 * Exceptions after the time of registration is passed through
4824 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4825 *
4826 * @param socketInfo the socket information used to match QoS events
4827 * @param callback receives qos events that satisfy socketInfo
4828 * @param executor The executor on which the callback will be invoked. The provided
4829 * {@link Executor} must run callback sequentially, otherwise the order of
4830 * callbacks cannot be guaranteed.
4831 *
4832 * @hide
4833 */
4834 @SystemApi
4835 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4836 @NonNull final QosCallback callback,
4837 @CallbackExecutor @NonNull final Executor executor) {
4838 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4839 Objects.requireNonNull(callback, "callback must be non-null");
4840 Objects.requireNonNull(executor, "executor must be non-null");
4841
4842 try {
4843 synchronized (mQosCallbackConnections) {
4844 if (getQosCallbackConnection(callback) == null) {
4845 final QosCallbackConnection connection =
4846 new QosCallbackConnection(this, callback, executor);
4847 mQosCallbackConnections.add(connection);
4848 mService.registerQosSocketCallback(socketInfo, connection);
4849 } else {
4850 Log.e(TAG, "registerQosCallback: Callback already registered");
4851 throw new QosCallbackRegistrationException();
4852 }
4853 }
4854 } catch (final RemoteException e) {
4855 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4856
4857 // The same unregister method method is called for consistency even though nothing
4858 // will be sent to the ConnectivityService since the callback was never successfully
4859 // registered.
4860 unregisterQosCallback(callback);
4861 e.rethrowFromSystemServer();
4862 } catch (final ServiceSpecificException e) {
4863 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4864 unregisterQosCallback(callback);
4865 throw convertServiceException(e);
4866 }
4867 }
4868
4869 /**
4870 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4871 * events once unregistered and can be registered a second time.
4872 * <p/>
4873 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4874 *
4875 * @param callback the callback being unregistered
4876 *
4877 * @hide
4878 */
4879 @SystemApi
4880 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4881 Objects.requireNonNull(callback, "The callback must be non-null");
4882 try {
4883 synchronized (mQosCallbackConnections) {
4884 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4885 if (connection != null) {
4886 connection.stopReceivingMessages();
4887 mService.unregisterQosCallback(connection);
4888 mQosCallbackConnections.remove(connection);
4889 } else {
4890 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4891 }
4892 }
4893 } catch (final RemoteException e) {
4894 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4895 e.rethrowFromSystemServer();
4896 }
4897 }
4898
4899 /**
4900 * Gets the connection related to the callback.
4901 *
4902 * @param callback the callback to look up
4903 * @return the related connection
4904 */
4905 @Nullable
4906 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4907 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4908 // Checking by reference here is intentional
4909 if (connection.getCallback() == callback) {
4910 return connection;
4911 }
4912 }
4913 return null;
4914 }
Junyu Lai23568a42021-01-19 11:10:56 +00004915
4916 /**
4917 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4918 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4919 * be used to request that the system provide a network without causing the network to be
4920 * in the foreground.
4921 *
4922 * <p>This method will attempt to find the best network that matches the passed
4923 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4924 * criteria. The platform will evaluate which network is the best at its own discretion.
4925 * Throughput, latency, cost per byte, policy, user preference and other considerations
4926 * may be factored in the decision of what is considered the best network.
4927 *
4928 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4929 * matching this request, while always attempting to match the request to a better network if
4930 * possible. If a better match is found, the platform will switch this request to the now-best
4931 * network and inform the app of the newly best network by invoking
4932 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4933 * will not try to maintain any other network than the best one currently matching the request:
4934 * a network not matching any network request may be disconnected at any time.
4935 *
4936 * <p>For example, an application could use this method to obtain a connected cellular network
4937 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4938 * radio to consume additional power. Or, an application could inform the system that it wants
4939 * a network supporting sending MMSes and have the system let it know about the currently best
4940 * MMS-supporting network through the provided {@link NetworkCallback}.
4941 *
4942 * <p>The status of the request can be followed by listening to the various callbacks described
4943 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4944 * used to direct traffic to the network (although accessing some networks may be subject to
4945 * holding specific permissions). Callers will learn about the specific characteristics of the
4946 * network through
4947 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4948 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4949 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4950 * matching the request at any given time; therefore when a better network matching the request
4951 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4952 * with the new network after which no further updates are given about the previously-best
4953 * network, unless it becomes the best again at some later time. All callbacks are invoked
4954 * in order on the same thread, which by default is a thread created by the framework running
4955 * in the app.
4956 *
4957 * <p>This{@link NetworkRequest} will live until released via
4958 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4959 * which point the system may let go of the network at any time.
4960 *
4961 * <p>It is presently unsupported to request a network with mutable
4962 * {@link NetworkCapabilities} such as
4963 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4964 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4965 * as these {@code NetworkCapabilities} represent states that a particular
4966 * network may never attain, and whether a network will attain these states
4967 * is unknown prior to bringing up the network so the framework does not
4968 * know how to go about satisfying a request with these capabilities.
4969 *
4970 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4971 * number of outstanding requests to 100 per app (identified by their UID), shared with
4972 * all variants of this method, of {@link #registerNetworkCallback} as well as
4973 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4974 * Requesting a network with this method will count toward this limit. If this limit is
4975 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4976 * make sure to unregister the callbacks with
4977 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4978 *
4979 * @param request {@link NetworkRequest} describing this request.
4980 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4981 * If null, the callback is invoked on the default internal Handler.
4982 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4983 * the callback must not be shared - it uniquely specifies this request.
4984 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4985 * @throws SecurityException if missing the appropriate permissions.
4986 * @throws RuntimeException if the app already has too many callbacks registered.
4987 *
4988 * @hide
4989 */
4990 @SystemApi(client = MODULE_LIBRARIES)
4991 @SuppressLint("ExecutorRegistration")
4992 @RequiresPermission(anyOf = {
4993 android.Manifest.permission.NETWORK_SETTINGS,
4994 android.Manifest.permission.NETWORK_STACK,
4995 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4996 })
4997 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
4998 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
4999 final NetworkCapabilities nc = request.networkCapabilities;
5000 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
5001 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
5002 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005003
5004 /**
5005 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
5006 * OnSetOemNetworkPreferenceListener)}.
James Mattis7a253542021-01-26 16:23:52 -08005007 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005008 */
James Mattis7a253542021-01-26 16:23:52 -08005009 @SystemApi
5010 public interface OnSetOemNetworkPreferenceListener {
James Mattis6e6fabf2021-01-10 14:24:24 -08005011 /**
5012 * Called when setOemNetworkPreference() successfully completes.
5013 */
5014 void onComplete();
5015 }
5016
5017 /**
5018 * Used by automotive devices to set the network preferences used to direct traffic at an
5019 * application level as per the given OemNetworkPreferences. An example use-case would be an
5020 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5021 * vehicle via a particular network.
5022 *
5023 * Calling this will overwrite the existing preference.
5024 *
5025 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5026 * @param executor the executor on which listener will be invoked.
5027 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5028 * communicate completion of setOemNetworkPreference(). This will only be
5029 * called once upon successful completion of setOemNetworkPreference().
5030 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5031 * @throws SecurityException if missing the appropriate permissions.
5032 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005033 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005034 */
James Mattis7a253542021-01-26 16:23:52 -08005035 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005036 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005037 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005038 @Nullable @CallbackExecutor final Executor executor,
5039 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5040 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5041 if (null != listener) {
5042 Objects.requireNonNull(executor, "Executor must be non-null");
5043 }
5044 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5045 new IOnSetOemNetworkPreferenceListener.Stub() {
5046 @Override
5047 public void onComplete() {
5048 executor.execute(listener::onComplete);
5049 }
5050 };
5051
5052 try {
5053 mService.setOemNetworkPreference(preference, listenerInternal);
5054 } catch (RemoteException e) {
5055 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5056 throw e.rethrowFromSystemServer();
5057 }
5058 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005059}