blob: 4cf08fcec1ffd8f5ea613cfc904ad101e18103f9 [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;
Junyu Lai23568a42021-01-19 11:10:56 +000019import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaid1a78162021-01-11 16:53:38 +080020import static android.net.NetworkRequest.Type.LISTEN;
junyulai8cae3c72021-03-12 20:05:08 +080021import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
junyulaid1a78162021-01-11 16:53:38 +080022import 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;
lucaslin8f026612021-03-12 17:56:09 +080026import static android.provider.Settings.Global.PRIVATE_DNS_DEFAULT_MODE;
27import static android.provider.Settings.Global.PRIVATE_DNS_MODE;
junyulai48a59382019-01-15 11:32:44 +080028
junyulaia86defc2018-12-27 17:25:29 +080029import android.annotation.CallbackExecutor;
Felipe Lemed16384b2016-01-22 09:44:57 -080030import android.annotation.IntDef;
Chalard Jean42a9c292019-01-07 19:26:34 +090031import android.annotation.NonNull;
Robin Lee33c73e22016-01-05 18:03:46 +000032import android.annotation.Nullable;
Jeff Sharkey2ac62992017-04-24 11:18:03 -060033import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080034import android.annotation.SdkConstant;
35import android.annotation.SdkConstant.SdkConstantType;
lucaslin8f026612021-03-12 17:56:09 +080036import android.annotation.StringDef;
Junyu Lai23568a42021-01-19 11:10:56 +000037import android.annotation.SuppressLint;
Udam Saini53b71ee2016-01-04 12:16:14 -080038import android.annotation.SystemApi;
Jeff Sharkeyb8c73032017-06-02 17:36:26 -060039import android.annotation.SystemService;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070040import android.app.PendingIntent;
Artur Satayev0e45d782019-12-10 17:47:52 +000041import android.compat.annotation.UnsupportedAppUsage;
lucaslin8f026612021-03-12 17:56:09 +080042import android.content.ContentResolver;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070043import android.content.Context;
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -070044import android.content.Intent;
junyulaia86defc2018-12-27 17:25:29 +080045import android.net.IpSecManager.UdpEncapsulationSocket;
46import android.net.SocketKeepalive.Callback;
markchiencc1bc1b2020-01-20 19:31:56 +080047import android.net.TetheringManager.StartTetheringCallback;
markchieneeea0be2020-01-21 13:11:06 +080048import android.net.TetheringManager.TetheringEventCallback;
markchiencc1bc1b2020-01-20 19:31:56 +080049import android.net.TetheringManager.TetheringRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -080050import android.net.wifi.WifiNetworkSuggestion;
Robert Greenwalt2034b912009-08-12 16:08:25 -070051import android.os.Binder;
Mathew Inwoodac5968e2018-12-20 15:30:45 +000052import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070053import android.os.Build.VERSION_CODES;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080054import android.os.Bundle;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070055import android.os.Handler;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080056import android.os.IBinder;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070057import android.os.Looper;
58import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070059import android.os.Messenger;
junyulai61143782019-03-04 22:45:36 +080060import android.os.ParcelFileDescriptor;
Cody Kestingb5c7abd2020-04-15 12:33:28 -070061import android.os.PersistableBundle;
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +090062import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.os.RemoteException;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080064import android.os.ResultReceiver;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080065import android.os.ServiceManager;
Hugo Benichi145e3792017-05-11 13:16:17 +090066import android.os.ServiceSpecificException;
Chalard Jean03433052021-02-25 17:23:40 +090067import android.os.UserHandle;
Jeff Sharkey971cd162011-08-29 16:02:57 -070068import android.provider.Settings;
Wink Saville02eb35c2014-12-05 11:10:30 -080069import android.telephony.SubscriptionManager;
Meng Wang91311c02019-11-18 17:10:00 -080070import android.telephony.TelephonyManager;
lucaslin8f026612021-03-12 17:56:09 +080071import android.text.TextUtils;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080072import android.util.ArrayMap;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070073import android.util.Log;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090074import android.util.Range;
Erik Kline50068e52017-01-26 18:08:28 +090075import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080076
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +090077import com.android.connectivity.aidl.INetworkAgent;
markchieneeea0be2020-01-21 13:11:06 +080078import com.android.internal.annotations.GuardedBy;
Robert Greenwalt3d6c9582014-05-21 20:04:36 -070079
Paul Jensen99c36662014-08-27 12:38:45 -040080import libcore.net.event.NetworkEventDispatcher;
81
junyulai61143782019-03-04 22:45:36 +080082import java.io.IOException;
83import java.io.UncheckedIOException;
Felipe Lemed16384b2016-01-22 09:44:57 -080084import java.lang.annotation.Retention;
85import java.lang.annotation.RetentionPolicy;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090086import java.net.DatagramSocket;
Jeremy Klein04863332015-12-28 15:11:58 -080087import java.net.InetAddress;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -070088import java.net.InetSocketAddress;
junyulaic7ea1242019-01-08 20:04:33 +080089import java.net.Socket;
Hugo Benichi45a49542017-03-06 09:17:06 +090090import java.util.ArrayList;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090091import java.util.Collection;
Jeremy Klein04863332015-12-28 15:11:58 -080092import java.util.HashMap;
Hugo Benichi45a49542017-03-06 09:17:06 +090093import java.util.List;
94import java.util.Map;
markchieneeea0be2020-01-21 13:11:06 +080095import java.util.Objects;
junyulaia86defc2018-12-27 17:25:29 +080096import java.util.concurrent.Executor;
junyulai9f872232019-01-16 20:23:34 +080097import java.util.concurrent.ExecutorService;
98import java.util.concurrent.Executors;
99import java.util.concurrent.RejectedExecutionException;
Jeremy Klein04863332015-12-28 15:11:58 -0800100
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101/**
102 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600103 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800104 * <p>
105 * The primary responsibilities of this class are to:
106 * <ol>
107 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
108 * <li>Send broadcast intents when network connectivity changes</li>
109 * <li>Attempt to "fail over" to another network when connectivity to a network
110 * is lost</li>
111 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
112 * state of the available networks</li>
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700113 * <li>Provide an API that allows applications to request and select networks for their data
114 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800115 * </ol>
116 */
Jeff Sharkeyb8c73032017-06-02 17:36:26 -0600117@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700118public class ConnectivityManager {
119 private static final String TAG = "ConnectivityManager";
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +0900120 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700121
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -0700123 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800124 * been established or lost. The NetworkInfo for the affected network is
125 * sent as an extra; it should be consulted to see what kind of
126 * connectivity event occurred.
127 * <p/>
Mark Lue1682a02016-12-05 10:57:55 -0800128 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
129 * broadcast if they declare the broadcast receiver in their manifest. Apps
130 * will still receive broadcasts if they register their
131 * {@link android.content.BroadcastReceiver} with
132 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
133 * and that context is still valid.
134 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135 * If this is a connection that was the result of failing over from a
136 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
137 * set to true.
138 * <p/>
139 * For a loss of connectivity, if the connectivity manager is attempting
140 * to connect (or has already connected) to another network, the
141 * NetworkInfo for the new network is also passed as an extra. This lets
142 * any receivers of the broadcast know that they should not necessarily
143 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt26744a52013-02-15 10:56:35 -0800144 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145 * the failover attempt succeeded (and so there is still overall data
146 * connectivity), or that the failover attempt failed, meaning that all
147 * connectivity has been lost.
148 * <p/>
149 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
150 * is set to {@code true} if there are no connected networks at all.
Chalard Jeanae2424a2018-02-10 05:33:50 +0900151 *
152 * @deprecated apps should use the more versatile {@link #requestNetwork},
153 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
154 * functions instead for faster and more detailed updates about the network
155 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800157 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jeanae2424a2018-02-10 05:33:50 +0900158 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700160
The Android Open Source Project28527d22009-03-03 19:31:44 -0800161 /**
Paul Jensened4d55c2015-02-27 22:55:47 -0500162 * The device has connected to a network that has presented a captive
163 * portal, which is blocking Internet connectivity. The user was presented
164 * with a notification that network sign in is required,
165 * and the user invoked the notification's action indicating they
Paul Jensen4173cce2015-05-22 10:50:39 -0400166 * desire to sign in to the network. Apps handling this activity should
Paul Jensened4d55c2015-02-27 22:55:47 -0500167 * facilitate signing in to the network. This action includes a
168 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
169 * the network presenting the captive portal; all communication with the
170 * captive portal must be done using this {@code Network} object.
171 * <p/>
Paul Jensen4173cce2015-05-22 10:50:39 -0400172 * This activity includes a {@link CaptivePortal} extra named
173 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
174 * outcomes of the captive portal sign in to the system:
175 * <ul>
176 * <li> When the app handling this action believes the user has signed in to
177 * the network and the captive portal has been dismissed, the app should
178 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
179 * reevaluate the network. If reevaluation finds the network no longer
180 * subject to a captive portal, the network may become the default active
Chalard Jean73d9db72018-06-04 16:52:49 +0900181 * data network.</li>
Paul Jensen4173cce2015-05-22 10:50:39 -0400182 * <li> When the app handling this action believes the user explicitly wants
Paul Jensened4d55c2015-02-27 22:55:47 -0500183 * to ignore the captive portal and the network, the app should call
Paul Jensen4173cce2015-05-22 10:50:39 -0400184 * {@link CaptivePortal#ignoreNetwork}. </li>
185 * </ul>
Paul Jensened4d55c2015-02-27 22:55:47 -0500186 */
187 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
188 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
189
190 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800191 * The lookup key for a {@link NetworkInfo} object. Retrieve with
192 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700193 *
Chalard Jeancc47b522019-01-11 16:47:53 +0900194 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
195 * can't accurately represent modern network characteristics.
196 * Please obtain information about networks from the {@link NetworkCapabilities}
197 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700199 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800200 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700201
The Android Open Source Project28527d22009-03-03 19:31:44 -0800202 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700203 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700204 *
205 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeancc47b522019-01-11 16:47:53 +0900206 * @deprecated The network type is not rich enough to represent the characteristics
207 * of modern networks. Please use {@link NetworkCapabilities} instead,
208 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700209 */
Chalard Jeancc47b522019-01-11 16:47:53 +0900210 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700211 public static final String EXTRA_NETWORK_TYPE = "networkType";
212
213 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214 * The lookup key for a boolean that indicates whether a connect event
215 * is for a network to which the connectivity manager was failing over
216 * following a disconnect on another network.
217 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai5c2f6262018-12-13 12:47:51 +0800218 *
219 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220 */
junyulai5c2f6262018-12-13 12:47:51 +0800221 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222 public static final String EXTRA_IS_FAILOVER = "isFailover";
223 /**
224 * The lookup key for a {@link NetworkInfo} object. This is supplied when
225 * there is another network that it may be possible to connect to. Retrieve with
226 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800227 *
228 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229 */
junyulai5c2f6262018-12-13 12:47:51 +0800230 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
232 /**
233 * The lookup key for a boolean that indicates whether there is a
234 * complete lack of connectivity, i.e., no network is available.
235 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
236 */
237 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
238 /**
239 * The lookup key for a string that indicates why an attempt to connect
240 * to a network failed. The string has no particular structure. It is
241 * intended to be used in notifications presented to users. Retrieve
242 * it with {@link android.content.Intent#getStringExtra(String)}.
243 */
244 public static final String EXTRA_REASON = "reason";
245 /**
246 * The lookup key for a string that provides optionally supplied
247 * extra information about the network state. The information
248 * may be passed up from the lower networking layers, and its
249 * meaning may be specific to a particular network type. Retrieve
250 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai5c2f6262018-12-13 12:47:51 +0800251 *
252 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800253 */
junyulai5c2f6262018-12-13 12:47:51 +0800254 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800255 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700256 /**
257 * The lookup key for an int that provides information about
258 * our connection to the internet at large. 0 indicates no connection,
259 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700260 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700261 * {@hide}
262 */
263 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800264 /**
Paul Jensen4173cce2015-05-22 10:50:39 -0400265 * The lookup key for a {@link CaptivePortal} object included with the
266 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
267 * object can be used to either indicate to the system that the captive
268 * portal has been dismissed or that the user does not want to pursue
269 * signing in to captive portal. Retrieve it with
270 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensened4d55c2015-02-27 22:55:47 -0500271 */
Paul Jensen4173cce2015-05-22 10:50:39 -0400272 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist0f3b4442015-09-22 15:54:32 -0700273
274 /**
275 * Key for passing a URL to the captive portal login activity.
276 */
277 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
278
Paul Jensened4d55c2015-02-27 22:55:47 -0500279 /**
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900280 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
281 * portal login activity.
282 * {@hide}
283 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900284 @SystemApi
Remi NGUYEN VANd937e3a2018-05-22 10:01:53 +0900285 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
286 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
287
288 /**
Hugo Benichidce21c52016-12-14 08:23:40 +0900289 * Key for passing a user agent string to the captive portal login activity.
290 * {@hide}
291 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900292 @SystemApi
Hugo Benichidce21c52016-12-14 08:23:40 +0900293 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
294 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
295
296 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700297 * Broadcast action to indicate the change of data activity status
298 * (idle or active) on a network in a recent period.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800299 * The network becomes active when data transmission is started, or
300 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700301 * {@hide}
302 */
303 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean73d9db72018-06-04 16:52:49 +0900304 public static final String ACTION_DATA_ACTIVITY_CHANGE =
305 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700306 /**
307 * The lookup key for an enum that indicates the network device type on which this data activity
308 * change happens.
309 * {@hide}
310 */
311 public static final String EXTRA_DEVICE_TYPE = "deviceType";
312 /**
313 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
314 * it is actively sending or receiving data and {@code false} means it is idle.
315 * {@hide}
316 */
317 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma601fba92014-03-12 18:42:23 -0700318 /**
319 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
320 * {@hide}
321 */
322 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700323
324 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800325 * Broadcast Action: The setting for background data usage has changed
326 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
327 * <p>
328 * If an application uses the network in the background, it should listen
329 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700330 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800331 * <p>
332 *
333 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
334 * of background data depends on several combined factors, and
335 * this broadcast is no longer sent. Instead, when background
336 * data is unavailable, {@link #getActiveNetworkInfo()} will now
337 * appear disconnected. During first boot after a platform
338 * upgrade, this broadcast will be sent once if
339 * {@link #getBackgroundDataSetting()} was {@code false} before
340 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800341 */
342 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800343 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800344 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
345 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
346
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700347 /**
348 * Broadcast Action: The network connection may not be good
349 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
350 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
351 * the network and it's condition.
352 * @hide
353 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800354 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100355 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700356 public static final String INET_CONDITION_ACTION =
357 "android.net.conn.INET_CONDITION_ACTION";
358
Robert Greenwalt2034b912009-08-12 16:08:25 -0700359 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800360 * Broadcast Action: A tetherable connection has come or gone.
361 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline449ccfe2017-04-17 16:47:23 +0900362 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
363 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt26744a52013-02-15 10:56:35 -0800364 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
365 * the current state of tethering. Each include a list of
366 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800367 * @hide
368 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800369 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood5a09a712020-11-04 09:29:36 +0000370 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800371 public static final String ACTION_TETHER_STATE_CHANGED =
markchien1f523702019-12-25 19:40:32 +0800372 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800373
374 /**
375 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800376 * gives a String[] listing all the interfaces configured for
377 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800378 */
Mathew Inwood5a09a712020-11-04 09:29:36 +0000379 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800380 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800381
382 /**
383 * @hide
Erik Kline449ccfe2017-04-17 16:47:23 +0900384 * gives a String[] listing all the interfaces currently in local-only
385 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800386 */
markchien1f523702019-12-25 19:40:32 +0800387 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline449ccfe2017-04-17 16:47:23 +0900388
389 /**
390 * @hide
391 * gives a String[] listing all the interfaces currently tethered
392 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
393 */
Mathew Inwood5a09a712020-11-04 09:29:36 +0000394 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800395 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800396
397 /**
398 * @hide
Robert Greenwalt26744a52013-02-15 10:56:35 -0800399 * gives a String[] listing all the interfaces we tried to tether and
400 * failed. Use {@link #getLastTetherError} to find the error code
401 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800402 */
Mathew Inwood5a09a712020-11-04 09:29:36 +0000403 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-12-25 19:40:32 +0800404 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800405
406 /**
Russell Brenner4774b022013-02-12 10:03:14 -0800407 * Broadcast Action: The captive portal tracker has finished its test.
408 * Sent only while running Setup Wizard, in lieu of showing a user
409 * notification.
410 * @hide
411 */
Jeff Sharkey6932ff62013-02-20 18:21:19 -0800412 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner4774b022013-02-12 10:03:14 -0800413 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
414 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
415 /**
416 * The lookup key for a boolean that indicates whether a captive portal was detected.
417 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
418 * @hide
419 */
420 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
421
422 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900423 * Action used to display a dialog that asks the user whether to connect to a network that is
424 * not validated. This intent is used to start the dialog in settings via startActivity.
425 *
426 * @hide
427 */
428 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
429
430 /**
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +0900431 * Action used to display a dialog that asks the user whether to avoid a network that is no
432 * longer validated. This intent is used to start the dialog in settings via startActivity.
433 *
434 * @hide
435 */
436 public static final String ACTION_PROMPT_LOST_VALIDATION =
437 "android.net.conn.PROMPT_LOST_VALIDATION";
438
439 /**
lucaslin25a50472019-03-12 13:08:03 +0800440 * Action used to display a dialog that asks the user whether to stay connected to a network
441 * that has not validated. This intent is used to start the dialog in settings via
442 * startActivity.
443 *
444 * @hide
445 */
446 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
447 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
448
449 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800450 * Invalid tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900451 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800452 * @hide
453 */
markchien1f523702019-12-25 19:40:32 +0800454 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800455
456 /**
457 * Wifi tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900458 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800459 * @hide
460 */
461 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900462 public static final int TETHERING_WIFI = 0;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800463
464 /**
465 * USB tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900466 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800467 * @hide
468 */
469 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900470 public static final int TETHERING_USB = 1;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800471
472 /**
473 * Bluetooth tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900474 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800475 * @hide
476 */
477 @SystemApi
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +0900478 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800479
480 /**
Jimmy Chen87db1542019-07-15 18:03:23 +0800481 * Wifi P2p tethering type.
482 * Wifi P2p tethering is set through events automatically, and don't
483 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
484 * @hide
485 */
markchien1f523702019-12-25 19:40:32 +0800486 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chen87db1542019-07-15 18:03:23 +0800487
488 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800489 * Extra used for communicating with the TetherService. Includes the type of tethering to
490 * enable if any.
491 * @hide
492 */
markchieneeea0be2020-01-21 13:11:06 +0800493 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800494
495 /**
496 * Extra used for communicating with the TetherService. Includes the type of tethering for
497 * which to cancel provisioning.
498 * @hide
499 */
markchieneeea0be2020-01-21 13:11:06 +0800500 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800501
502 /**
503 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
504 * provisioning.
505 * @hide
506 */
markchieneeea0be2020-01-21 13:11:06 +0800507 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800508
509 /**
510 * Tells the TetherService to run a provision check now.
511 * @hide
512 */
markchieneeea0be2020-01-21 13:11:06 +0800513 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800514
515 /**
516 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
517 * which will receive provisioning results. Can be left empty.
518 * @hide
519 */
markchieneeea0be2020-01-21 13:11:06 +0800520 public static final String EXTRA_PROVISION_CALLBACK =
521 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800522
523 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800524 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700525 * @hide
526 */
paulhu62af6122020-01-13 16:46:45 +0800527 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700528 public static final int TYPE_NONE = -1;
529
530 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900531 * A Mobile data connection. Devices may support more than one.
532 *
533 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
534 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
535 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700536 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900537 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700538 public static final int TYPE_MOBILE = 0;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900539
Robert Greenwalt2034b912009-08-12 16:08:25 -0700540 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900541 * A WIFI data connection. Devices may support more than one.
542 *
543 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
544 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
545 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700546 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900547 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700548 public static final int TYPE_WIFI = 1;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900549
Robert Greenwalt2034b912009-08-12 16:08:25 -0700550 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800551 * An MMS-specific Mobile data connection. This network type may use the
552 * same network interface as {@link #TYPE_MOBILE} or it may use a different
553 * one. This is used by applications needing to talk to the carrier's
554 * Multimedia Messaging Service servers.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900555 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900556 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900557 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900558 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700559 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700560 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700561 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900562
Robert Greenwalt2034b912009-08-12 16:08:25 -0700563 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800564 * A SUPL-specific Mobile data connection. This network type may use the
565 * same network interface as {@link #TYPE_MOBILE} or it may use a different
566 * one. This is used by applications needing to talk to the carrier's
567 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900568 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900569 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900570 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900571 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700572 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700573 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700574 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900575
Robert Greenwalt2034b912009-08-12 16:08:25 -0700576 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800577 * A DUN-specific Mobile data connection. This network type may use the
578 * same network interface as {@link #TYPE_MOBILE} or it may use a different
579 * one. This is sometimes by the system when setting up an upstream connection
580 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900581 *
582 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
583 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
584 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700585 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900586 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700587 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900588
Robert Greenwalt2034b912009-08-12 16:08:25 -0700589 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800590 * A High Priority Mobile data connection. This network type uses the
591 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900592 * is different.
593 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900594 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
595 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
596 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700597 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700598 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700599 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900600
jshbfa81722010-03-11 15:04:43 -0800601 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900602 * A WiMAX data connection.
603 *
604 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
605 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
606 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800607 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900608 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800609 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800610
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800611 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900612 * A Bluetooth data connection.
613 *
614 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
615 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
616 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800617 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900618 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800619 public static final int TYPE_BLUETOOTH = 7;
620
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700621 /**
Chiachang Wang7d5f3782020-07-28 13:53:09 +0800622 * Fake data connection. This should not be used on shipping devices.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900623 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700624 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900625 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800626 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800627
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700628 /**
Chalard Jean5acb7b72018-03-08 13:54:53 +0900629 * An Ethernet data connection.
630 *
631 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
632 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
633 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700634 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900635 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800636 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700637
Wink Savilleb7c92c72011-03-12 14:52:01 -0800638 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800639 * Over the air Administration.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900640 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800641 * {@hide}
642 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900643 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900644 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800645 public static final int TYPE_MOBILE_FOTA = 10;
646
647 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800648 * IP Multimedia Subsystem.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900649 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800650 * {@hide}
651 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900652 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100653 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800654 public static final int TYPE_MOBILE_IMS = 11;
655
656 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800657 * Carrier Branded Services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900658 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800659 * {@hide}
660 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900661 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900662 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800663 public static final int TYPE_MOBILE_CBS = 12;
664
repo syncf5de5572011-07-29 23:55:49 -0700665 /**
666 * A Wi-Fi p2p connection. Only requesting processes will have access to
667 * the peers connected.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900668 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700669 * {@hide}
670 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900671 @Deprecated
paulhu028732e2020-01-15 15:38:23 +0800672 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700673 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800674
Wink Saville70dbdcc2013-07-29 15:00:57 -0700675 /**
676 * The network to use for initially attaching to the network
Chalard Jean5acb7b72018-03-08 13:54:53 +0900677 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville70dbdcc2013-07-29 15:00:57 -0700678 * {@hide}
679 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900680 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100681 @UnsupportedAppUsage
Wink Saville70dbdcc2013-07-29 15:00:57 -0700682 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700683
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900684 /**
Robert Greenwalt9db5f3c2015-07-09 14:49:35 -0700685 * Emergency PDN connection for emergency services. This
686 * may include IMS and MMS in emergency situations.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900687 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram201d45f2014-06-26 11:03:44 -0700688 * {@hide}
689 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900690 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900691 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram201d45f2014-06-26 11:03:44 -0700692 public static final int TYPE_MOBILE_EMERGENCY = 15;
693
Hui Lu07f29332014-01-15 11:05:36 -0500694 /**
695 * The network that uses proxy to achieve connectivity.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900696 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu07f29332014-01-15 11:05:36 -0500697 * {@hide}
698 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900699 @Deprecated
Remi NGUYEN VANdaeafee2020-11-30 19:23:45 +0900700 @SystemApi
Hui Lu07f29332014-01-15 11:05:36 -0500701 public static final int TYPE_PROXY = 16;
Wink Saville70dbdcc2013-07-29 15:00:57 -0700702
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700703 /**
704 * A virtual network using one or more native bearers.
705 * It may or may not be providing security services.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900706 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700707 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900708 @Deprecated
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700709 public static final int TYPE_VPN = 17;
Hui Lu07f29332014-01-15 11:05:36 -0500710
Benedict Wong80156022018-11-14 17:40:55 -0800711 /**
712 * A network that is exclusively meant to be used for testing
713 *
714 * @deprecated Use {@link NetworkCapabilities} instead.
715 * @hide
716 */
717 @Deprecated
718 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700719
Chalard Jeane5b9e822020-03-25 01:24:04 +0900720 /**
721 * @deprecated Use {@link NetworkCapabilities} instead.
722 * @hide
723 */
724 @Deprecated
725 @Retention(RetentionPolicy.SOURCE)
726 @IntDef(prefix = { "TYPE_" }, value = {
727 TYPE_NONE,
728 TYPE_MOBILE,
729 TYPE_WIFI,
730 TYPE_MOBILE_MMS,
731 TYPE_MOBILE_SUPL,
732 TYPE_MOBILE_DUN,
733 TYPE_MOBILE_HIPRI,
734 TYPE_WIMAX,
735 TYPE_BLUETOOTH,
736 TYPE_DUMMY,
737 TYPE_ETHERNET,
738 TYPE_MOBILE_FOTA,
739 TYPE_MOBILE_IMS,
740 TYPE_MOBILE_CBS,
741 TYPE_WIFI_P2P,
742 TYPE_MOBILE_IA,
743 TYPE_MOBILE_EMERGENCY,
744 TYPE_PROXY,
745 TYPE_VPN,
746 TYPE_TEST
747 })
748 public @interface LegacyNetworkType {}
749
Chalard Jean1f42df12019-11-21 14:48:00 +0900750 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
751 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
752 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
753 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
754 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
755
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700756 /** {@hide} */
Benedict Wong80156022018-11-14 17:40:55 -0800757 public static final int MAX_RADIO_TYPE = TYPE_TEST;
758
759 /** {@hide} */
760 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800761
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900762 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
763
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800764 /**
765 * If you want to set the default network preference,you can directly
766 * change the networkAttributes array in framework's config.xml.
767 *
768 * @deprecated Since we support so many more networks now, the single
769 * network default network preference can't really express
Robert Greenwalt26744a52013-02-15 10:56:35 -0800770 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800771 * networkAttributes in config.xml. You can determine
Robert Greenwalt1ee3d2c2012-12-07 09:56:50 -0800772 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800773 * from an App.
774 */
775 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800776 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
777
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700778 /**
Robert Greenwalta1402df2014-03-19 17:56:12 -0700779 * @hide
780 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900781 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltc34f83b2014-06-08 16:42:59 -0700782
Paul Jensen0478ace2014-07-11 12:28:19 -0400783 /**
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900784 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
785 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean73d9db72018-06-04 16:52:49 +0900786 * registered from those that were already unregistered.
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900787 * @hide
788 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900789 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900790 new NetworkRequest.Builder().clearCapabilities().build();
791
792 /**
Paul Jensen0478ace2014-07-11 12:28:19 -0400793 * A NetID indicating no Network is selected.
794 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
795 * @hide
796 */
797 public static final int NETID_UNSET = 0;
798
Erik Kline1ecdd962017-10-30 15:29:44 +0900799 /**
800 * Private DNS Mode values.
801 *
802 * The "private_dns_mode" global setting stores a String value which is
803 * expected to be one of the following.
804 */
805
806 /**
807 * @hide
808 */
lucaslin8f026612021-03-12 17:56:09 +0800809 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900810 public static final String PRIVATE_DNS_MODE_OFF = "off";
811 /**
812 * @hide
813 */
lucaslin8f026612021-03-12 17:56:09 +0800814 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900815 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
816 /**
817 * @hide
818 */
lucaslin8f026612021-03-12 17:56:09 +0800819 @SystemApi(client = MODULE_LIBRARIES)
Erik Kline1ecdd962017-10-30 15:29:44 +0900820 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin8f026612021-03-12 17:56:09 +0800821
822 /** @hide */
823 @Retention(RetentionPolicy.SOURCE)
824 @StringDef(value = {
825 PRIVATE_DNS_MODE_OFF,
826 PRIVATE_DNS_MODE_OPPORTUNISTIC,
827 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
828 })
829 public @interface PrivateDnsMode {}
Erik Kline1ecdd962017-10-30 15:29:44 +0900830
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900831 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700832 private final IConnectivityManager mService;
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +0900833
Paul Jensen12131352014-12-10 15:12:18 -0500834 /**
835 * A kludge to facilitate static access where a Context pointer isn't available, like in the
836 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
837 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
838 * methods that take a Context argument.
839 */
840 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800841
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +0900842 private final Context mContext;
843
Felipe Lemed16384b2016-01-22 09:44:57 -0800844 private INetworkPolicyManager mNPManager;
Amos Bianchiddadca42020-03-04 11:07:38 -0800845 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800846
Robert Greenwalt26744a52013-02-15 10:56:35 -0800847 /**
848 * Tests if a given integer represents a valid network type.
849 * @param networkType the type to be tested
850 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen1c9f2e42015-05-06 10:42:25 -0400851 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
852 * validate a network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800853 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700854 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700855 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900856 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800857 }
858
Robert Greenwalt26744a52013-02-15 10:56:35 -0800859 /**
860 * Returns a non-localized string representing a given network type.
861 * ONLY used for debugging output.
862 * @param type the type needing naming
863 * @return a String for the given type, or a string version of the type ("87")
864 * if no name is known.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900865 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800866 * {@hide}
867 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900868 @Deprecated
Mathew Inwood5a09a712020-11-04 09:29:36 +0000869 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700870 public static String getNetworkTypeName(int type) {
871 switch (type) {
Hugo Benichi37d5c3c2017-06-20 14:07:59 +0900872 case TYPE_NONE:
873 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700874 case TYPE_MOBILE:
875 return "MOBILE";
876 case TYPE_WIFI:
877 return "WIFI";
878 case TYPE_MOBILE_MMS:
879 return "MOBILE_MMS";
880 case TYPE_MOBILE_SUPL:
881 return "MOBILE_SUPL";
882 case TYPE_MOBILE_DUN:
883 return "MOBILE_DUN";
884 case TYPE_MOBILE_HIPRI:
885 return "MOBILE_HIPRI";
886 case TYPE_WIMAX:
887 return "WIMAX";
888 case TYPE_BLUETOOTH:
889 return "BLUETOOTH";
890 case TYPE_DUMMY:
891 return "DUMMY";
892 case TYPE_ETHERNET:
893 return "ETHERNET";
894 case TYPE_MOBILE_FOTA:
895 return "MOBILE_FOTA";
896 case TYPE_MOBILE_IMS:
897 return "MOBILE_IMS";
898 case TYPE_MOBILE_CBS:
899 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700900 case TYPE_WIFI_P2P:
901 return "WIFI_P2P";
Wink Saville70dbdcc2013-07-29 15:00:57 -0700902 case TYPE_MOBILE_IA:
903 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -0700904 case TYPE_MOBILE_EMERGENCY:
905 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -0500906 case TYPE_PROXY:
907 return "PROXY";
Erik Klineb1ff7002014-11-19 17:23:41 +0900908 case TYPE_VPN:
909 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700910 default:
911 return Integer.toString(type);
912 }
913 }
914
Robert Greenwalt26744a52013-02-15 10:56:35 -0800915 /**
Aaron Huang925d09b2020-06-27 07:18:23 +0800916 * @hide
917 * TODO: Expose for SystemServer when becomes a module.
918 */
919 public void systemReady() {
920 try {
921 mService.systemReady();
922 } catch (RemoteException e) {
923 throw e.rethrowFromSystemServer();
924 }
925 }
926
927 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800928 * Checks if a given type uses the cellular data connection.
929 * This should be replaced in the future by a network property.
930 * @param networkType the type to check
931 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +0900932 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800933 * {@hide}
934 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900935 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900936 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700937 public static boolean isNetworkTypeMobile(int networkType) {
938 switch (networkType) {
939 case TYPE_MOBILE:
940 case TYPE_MOBILE_MMS:
941 case TYPE_MOBILE_SUPL:
942 case TYPE_MOBILE_DUN:
943 case TYPE_MOBILE_HIPRI:
944 case TYPE_MOBILE_FOTA:
945 case TYPE_MOBILE_IMS:
946 case TYPE_MOBILE_CBS:
Wink Saville70dbdcc2013-07-29 15:00:57 -0700947 case TYPE_MOBILE_IA:
Ram201d45f2014-06-26 11:03:44 -0700948 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700949 return true;
950 default:
951 return false;
952 }
953 }
954
Robert Greenwalt26744a52013-02-15 10:56:35 -0800955 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700956 * Checks if the given network type is backed by a Wi-Fi radio.
957 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900958 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700959 * @hide
960 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900961 @Deprecated
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700962 public static boolean isNetworkTypeWifi(int networkType) {
963 switch (networkType) {
964 case TYPE_WIFI:
965 case TYPE_WIFI_P2P:
966 return true;
967 default:
968 return false;
969 }
970 }
971
972 /**
Chalard Jean03433052021-02-25 17:23:40 +0900973 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
974 * Specify that the traffic for this user should by follow the default rules.
975 * @hide
976 */
Chalard Jeancc9ad152021-03-03 16:37:13 +0900977 @SystemApi
Chalard Jean03433052021-02-25 17:23:40 +0900978 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
979
980 /**
981 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
982 * Specify that the traffic for this user should by default go on a network with
983 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
984 * if no such network is available.
985 * @hide
986 */
Chalard Jeancc9ad152021-03-03 16:37:13 +0900987 @SystemApi
Chalard Jean03433052021-02-25 17:23:40 +0900988 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
989
990 /** @hide */
991 @Retention(RetentionPolicy.SOURCE)
992 @IntDef(value = {
993 PROFILE_NETWORK_PREFERENCE_DEFAULT,
994 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
995 })
996 public @interface ProfileNetworkPreference {
997 }
998
999 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001000 * Specifies the preferred network type. When the device has more
1001 * than one type available the preferred network type will be used.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001002 *
1003 * @param preference the network type to prefer over all others. It is
1004 * unspecified what happens to the old preferred network in the
1005 * overall ordering.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001006 * @deprecated Functionality has been removed as it no longer makes sense,
1007 * with many more than two networks - we'd need an array to express
1008 * preference. Instead we use dynamic network properties of
1009 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001010 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001011 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001012 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001013 }
1014
Robert Greenwalt26744a52013-02-15 10:56:35 -08001015 /**
1016 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001017 *
1018 * @return an integer representing the preferred network type
1019 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001020 * @deprecated Functionality has been removed as it no longer makes sense,
1021 * with many more than two networks - we'd need an array to express
1022 * preference. Instead we use dynamic network properties of
1023 * the networks to describe their precedence.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001024 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001025 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001026 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001027 public int getNetworkPreference() {
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001028 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001029 }
1030
Scott Mainf58b7d82011-10-06 19:02:28 -07001031 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001032 * Returns details about the currently active default data network. When
1033 * connected, this network is the default route for outgoing connections.
1034 * You should always check {@link NetworkInfo#isConnected()} before initiating
1035 * network traffic. This may return {@code null} when there is no default
1036 * network.
Chalard Jean7c85ba42018-03-29 17:45:24 +09001037 * Note that if the default network is a VPN, this method will return the
1038 * NetworkInfo for one of its underlying networks instead, or null if the
1039 * VPN agent did not specify any. Apps interested in learning about VPNs
1040 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001041 *
1042 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001043 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001044 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001045 */
junyulai5c2f6262018-12-13 12:47:51 +08001046 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001047 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001048 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001049 public NetworkInfo getActiveNetworkInfo() {
1050 try {
1051 return mService.getActiveNetworkInfo();
1052 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001053 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001054 }
1055 }
1056
Robert Greenwalt26744a52013-02-15 10:56:35 -08001057 /**
Paul Jensenc2569432015-02-13 14:18:39 -05001058 * Returns a {@link Network} object corresponding to the currently active
1059 * default data network. In the event that the current active default data
1060 * network disconnects, the returned {@code Network} object will no longer
1061 * be usable. This will return {@code null} when there is no default
1062 * network.
1063 *
1064 * @return a {@link Network} object for the current default network or
1065 * {@code null} if no default network is currently active
Paul Jensenc2569432015-02-13 14:18:39 -05001066 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001067 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001068 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001069 public Network getActiveNetwork() {
1070 try {
1071 return mService.getActiveNetwork();
1072 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001073 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001074 }
1075 }
1076
1077 /**
Robin Leeda4d2e22016-03-24 12:07:00 +00001078 * Returns a {@link Network} object corresponding to the currently active
1079 * default data network for a specific UID. In the event that the default data
1080 * network disconnects, the returned {@code Network} object will no longer
1081 * be usable. This will return {@code null} when there is no default
1082 * network for the UID.
Robin Leeda4d2e22016-03-24 12:07:00 +00001083 *
1084 * @return a {@link Network} object for the current default network for the
1085 * given UID or {@code null} if no default network is currently active
1086 *
1087 * @hide
1088 */
paulhud70b7dd2019-08-12 16:25:11 +08001089 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001090 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001091 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001092 return getActiveNetworkForUid(uid, false);
1093 }
1094
1095 /** {@hide} */
1096 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001097 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001098 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001099 } catch (RemoteException e) {
1100 throw e.rethrowFromSystemServer();
1101 }
1102 }
1103
1104 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001105 * Adds or removes a requirement for given UID ranges to use the VPN.
1106 *
1107 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1108 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1109 * otherwise have permission to bypass the VPN (e.g., because they have the
1110 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1111 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1112 * set to {@code false}, a previously-added restriction is removed.
1113 * <p>
1114 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1115 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1116 * remove a previously-added range, the exact range must be removed as is.
1117 * <p>
1118 * The changes are applied asynchronously and may not have been applied by the time the method
1119 * returns. Apps will be notified about any changes that apply to them via
1120 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1121 * effect.
1122 * <p>
1123 * This method should be called only by the VPN code.
1124 *
1125 * @param ranges the UID ranges to restrict
1126 * @param requireVpn whether the specified UID ranges must use a VPN
1127 *
1128 * TODO: expose as @SystemApi.
1129 * @hide
1130 */
1131 @RequiresPermission(anyOf = {
1132 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1133 android.Manifest.permission.NETWORK_STACK})
1134 public void setRequireVpnForUids(boolean requireVpn,
1135 @NonNull Collection<Range<Integer>> ranges) {
1136 Objects.requireNonNull(ranges);
1137 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1138 // This method is not necessarily expected to be used outside the system server, so
1139 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1140 // stack process, or by tests.
1141 UidRange[] rangesArray = new UidRange[ranges.size()];
1142 int index = 0;
1143 for (Range<Integer> range : ranges) {
1144 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1145 }
1146 try {
1147 mService.setRequireVpnForUids(requireVpn, rangesArray);
1148 } catch (RemoteException e) {
1149 throw e.rethrowFromSystemServer();
1150 }
1151 }
1152
1153 /**
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09001154 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1155 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1156 * but is still supported for backwards compatibility.
1157 * <p>
1158 * This type of VPN is assumed always to use the system default network, and must always declare
1159 * exactly one underlying network, which is the network that was the default when the VPN
1160 * connected.
1161 * <p>
1162 * Calling this method with {@code true} enables legacy behaviour, specifically:
1163 * <ul>
1164 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1165 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1166 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1167 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1168 * underlying the VPN.</li>
1169 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1170 * similarly replaced by the VPN network state.</li>
1171 * <li>Information on current network interfaces passed to NetworkStatsService will not
1172 * include any VPN interfaces.</li>
1173 * </ul>
1174 *
1175 * @param enabled whether legacy lockdown VPN is enabled or disabled
1176 *
1177 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1178 *
1179 * @hide
1180 */
1181 @RequiresPermission(anyOf = {
1182 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1183 android.Manifest.permission.NETWORK_SETTINGS})
1184 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1185 try {
1186 mService.setLegacyLockdownVpnEnabled(enabled);
1187 } catch (RemoteException e) {
1188 throw e.rethrowFromSystemServer();
1189 }
1190 }
1191
1192 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001193 * Returns details about the currently active default data network
1194 * for a given uid. This is for internal use only to avoid spying
1195 * other apps.
1196 *
1197 * @return a {@link NetworkInfo} object for the current default network
1198 * for the given uid or {@code null} if no default network is
1199 * available for the specified uid.
1200 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001201 * {@hide}
1202 */
paulhud70b7dd2019-08-12 16:25:11 +08001203 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwood5a09a712020-11-04 09:29:36 +00001204 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001205 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001206 return getActiveNetworkInfoForUid(uid, false);
1207 }
1208
1209 /** {@hide} */
1210 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001211 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001212 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001213 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001214 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001215 }
1216 }
1217
Robert Greenwalt26744a52013-02-15 10:56:35 -08001218 /**
1219 * Returns connection status information about a particular
1220 * network type.
1221 *
1222 * @param networkType integer specifying which networkType in
1223 * which you're interested.
1224 * @return a {@link NetworkInfo} object for the requested
1225 * network type or {@code null} if the type is not
Chalard Jean7c85ba42018-03-29 17:45:24 +09001226 * supported by the device. If {@code networkType} is
1227 * TYPE_VPN and a VPN is active for the calling app,
1228 * then this method will try to return one of the
1229 * underlying networks for the VPN or null if the
1230 * VPN agent didn't specify any.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001231 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001232 * @deprecated This method does not support multiple connected networks
1233 * of the same type. Use {@link #getAllNetworks} and
1234 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001235 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001236 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001237 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001238 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001239 public NetworkInfo getNetworkInfo(int networkType) {
1240 try {
1241 return mService.getNetworkInfo(networkType);
1242 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001243 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001244 }
1245 }
1246
Robert Greenwalt26744a52013-02-15 10:56:35 -08001247 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001248 * Returns connection status information about a particular
1249 * Network.
1250 *
1251 * @param network {@link Network} specifying which network
1252 * in which you're interested.
1253 * @return a {@link NetworkInfo} object for the requested
1254 * network or {@code null} if the {@code Network}
1255 * is not valid.
junyulai5c2f6262018-12-13 12:47:51 +08001256 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001257 */
junyulai5c2f6262018-12-13 12:47:51 +08001258 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001259 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001260 @Nullable
1261 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001262 return getNetworkInfoForUid(network, Process.myUid(), false);
1263 }
1264
1265 /** {@hide} */
1266 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001267 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001268 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001269 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001270 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001271 }
1272 }
1273
1274 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001275 * Returns connection status information about all network
1276 * types supported by the device.
1277 *
1278 * @return an array of {@link NetworkInfo} objects. Check each
1279 * {@link NetworkInfo#getType} for which type each applies.
1280 *
Paul Jensena8e6dc62015-03-18 12:23:02 -04001281 * @deprecated This method does not support multiple connected networks
1282 * of the same type. Use {@link #getAllNetworks} and
1283 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001284 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001285 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001286 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001287 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001288 public NetworkInfo[] getAllNetworkInfo() {
1289 try {
1290 return mService.getAllNetworkInfo();
1291 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001292 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001293 }
1294 }
1295
Robert Greenwalt26744a52013-02-15 10:56:35 -08001296 /**
junyulai57840802021-03-03 12:09:05 +08001297 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1298 * connected.
1299 * @hide
1300 */
1301 @SystemApi(client = MODULE_LIBRARIES)
1302 @RequiresPermission(anyOf = {
1303 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1304 android.Manifest.permission.NETWORK_STACK,
1305 android.Manifest.permission.NETWORK_SETTINGS})
1306 @NonNull
1307 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1308 try {
1309 return mService.getAllNetworkStateSnapshot();
1310 } catch (RemoteException e) {
1311 throw e.rethrowFromSystemServer();
1312 }
1313 }
1314
1315 /**
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001316 * Returns the {@link Network} object currently serving a given type, or
1317 * null if the given type is not connected.
1318 *
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001319 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04001320 * @deprecated This method does not support multiple connected networks
1321 * of the same type. Use {@link #getAllNetworks} and
1322 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001323 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001324 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001325 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001326 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001327 public Network getNetworkForType(int networkType) {
1328 try {
1329 return mService.getNetworkForType(networkType);
1330 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001331 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001332 }
1333 }
1334
1335 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001336 * Returns an array of all {@link Network} currently tracked by the
1337 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001338 *
1339 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001340 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001341 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001342 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001343 public Network[] getAllNetworks() {
1344 try {
1345 return mService.getAllNetworks();
1346 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001347 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001348 }
1349 }
1350
1351 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001352 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001353 * the Networks that applications run by the given user will use by default.
1354 * @hide
1355 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001356 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001357 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1358 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001359 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001360 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001361 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001362 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001363 }
1364 }
1365
1366 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08001367 * Returns the IP information for the current default network.
1368 *
1369 * @return a {@link LinkProperties} object describing the IP info
1370 * for the current default network, or {@code null} if there
1371 * is no current default network.
1372 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001373 * {@hide}
Chalard Jeancc47b522019-01-11 16:47:53 +09001374 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1375 * value of {@link #getActiveNetwork()} instead. In particular,
1376 * this method will return non-null LinkProperties even if the
1377 * app is blocked by policy from using this network.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001378 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001379 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-01-11 16:47:53 +09001380 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001381 public LinkProperties getActiveLinkProperties() {
1382 try {
1383 return mService.getActiveLinkProperties();
1384 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001385 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001386 }
1387 }
1388
Robert Greenwalt26744a52013-02-15 10:56:35 -08001389 /**
1390 * Returns the IP information for a given network type.
1391 *
1392 * @param networkType the network type of interest.
1393 * @return a {@link LinkProperties} object describing the IP info
1394 * for the given networkType, or {@code null} if there is
1395 * no current default network.
1396 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08001397 * {@hide}
Paul Jensena8e6dc62015-03-18 12:23:02 -04001398 * @deprecated This method does not support multiple connected networks
1399 * of the same type. Use {@link #getAllNetworks},
1400 * {@link #getNetworkInfo(android.net.Network)}, and
1401 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -08001402 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001403 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001404 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09001405 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001406 public LinkProperties getLinkProperties(int networkType) {
1407 try {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001408 return mService.getLinkPropertiesForType(networkType);
1409 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001410 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001411 }
1412 }
1413
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001414 /**
1415 * Get the {@link LinkProperties} for the given {@link Network}. This
1416 * will return {@code null} if the network is unknown.
1417 *
1418 * @param network The {@link Network} object identifying the network in question.
1419 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001420 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001421 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001422 @Nullable
1423 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001424 try {
1425 return mService.getLinkProperties(network);
1426 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001427 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001428 }
1429 }
1430
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001431 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08001432 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001433 * will return {@code null} if the network is unknown.
1434 *
Roshan Pius7992afd2020-12-22 15:10:42 -08001435 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1436 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1437 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1438 * this location sensitive information (subject to app's location permissions) will be
1439 * noted by system. To include any location sensitive data in {@link TransportInfo},
1440 * use a {@link NetworkCallback} with
1441 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1442 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001443 * @param network The {@link Network} object identifying the network in question.
Roshan Pius7992afd2020-12-22 15:10:42 -08001444 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001445 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001446 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001447 @Nullable
1448 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001449 try {
Roshan Piusc97d8062020-12-17 14:53:09 -08001450 return mService.getNetworkCapabilities(
1451 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001452 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001453 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001454 }
1455 }
1456
Robert Greenwalt26744a52013-02-15 10:56:35 -08001457 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001458 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001459 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1460 * portal is present.
1461 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1462 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1463 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001464 * The system network validation may be using different strategies to detect captive portals,
1465 * so this method does not necessarily return a URL used by the system. It only returns a URL
1466 * that may be relevant for other components trying to detect captive portals.
paulhud70b7dd2019-08-12 16:25:11 +08001467 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001468 * @hide
paulhud70b7dd2019-08-12 16:25:11 +08001469 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1470 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001471 */
paulhud70b7dd2019-08-12 16:25:11 +08001472 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001473 @SystemApi
paulhud70b7dd2019-08-12 16:25:11 +08001474 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001475 public String getCaptivePortalServerUrl() {
1476 try {
1477 return mService.getCaptivePortalServerUrl();
1478 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001479 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001480 }
1481 }
1482
1483 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001484 * Tells the underlying networking system that the caller wants to
1485 * begin using the named feature. The interpretation of {@code feature}
1486 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001487 *
1488 * <p>This method requires the caller to hold either the
1489 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1490 * or the ability to modify system settings as determined by
1491 * {@link android.provider.Settings.System#canWrite}.</p>
1492 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001493 * @param networkType specifies which network the request pertains to
1494 * @param feature the name of the feature to be used
1495 * @return an integer value representing the outcome of the request.
1496 * The interpretation of this value is specific to each networking
1497 * implementation+feature combination, except that the value {@code -1}
1498 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001499 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001500 * @deprecated Deprecated in favor of the cleaner
1501 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001502 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001503 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001504 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001505 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001506 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001507 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001508 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001509 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1510 if (netCap == null) {
1511 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1512 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001513 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001514 }
1515
1516 NetworkRequest request = null;
1517 synchronized (sLegacyRequests) {
1518 LegacyRequest l = sLegacyRequests.get(netCap);
1519 if (l != null) {
1520 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1521 renewRequestLocked(l);
1522 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001523 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001524 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001525 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001526 }
1527 }
1528
1529 request = requestNetworkForFeatureLocked(netCap);
1530 }
1531 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001532 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001533 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001534 } else {
1535 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001536 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001537 }
1538 }
1539
1540 /**
1541 * Tells the underlying networking system that the caller is finished
1542 * using the named feature. The interpretation of {@code feature}
1543 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001544 *
1545 * <p>This method requires the caller to hold either the
1546 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1547 * or the ability to modify system settings as determined by
1548 * {@link android.provider.Settings.System#canWrite}.</p>
1549 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001550 * @param networkType specifies which network the request pertains to
1551 * @param feature the name of the feature that is no longer needed
1552 * @return an integer value representing the outcome of the request.
1553 * The interpretation of this value is specific to each networking
1554 * implementation+feature combination, except that the value {@code -1}
1555 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001556 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001557 * @deprecated Deprecated in favor of the cleaner
1558 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001559 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001560 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001561 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001562 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001563 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001564 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001565 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001566 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1567 if (netCap == null) {
1568 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1569 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001570 return -1;
1571 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001572
Paul Jensen034dea32014-12-17 10:39:34 -05001573 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001574 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001575 }
1576 return 1;
1577 }
1578
Mathew Inwood5a09a712020-11-04 09:29:36 +00001579 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001580 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1581 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001582 switch (feature) {
1583 case "enableCBS":
1584 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1585 case "enableDUN":
1586 case "enableDUNAlways":
1587 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1588 case "enableFOTA":
1589 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1590 case "enableHIPRI":
1591 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1592 case "enableIMS":
1593 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1594 case "enableMMS":
1595 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1596 case "enableSUPL":
1597 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1598 default:
1599 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001600 }
Erik Kline50068e52017-01-26 18:08:28 +09001601 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1602 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001603 }
1604 return null;
1605 }
1606
Robert Greenwalt5a367872014-06-02 15:32:02 -07001607 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001608 if (netCap == null) return TYPE_NONE;
1609 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1610 return TYPE_MOBILE_CBS;
1611 }
1612 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1613 return TYPE_MOBILE_IMS;
1614 }
1615 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1616 return TYPE_MOBILE_FOTA;
1617 }
1618 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1619 return TYPE_MOBILE_DUN;
1620 }
1621 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1622 return TYPE_MOBILE_SUPL;
1623 }
1624 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1625 return TYPE_MOBILE_MMS;
1626 }
1627 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1628 return TYPE_MOBILE_HIPRI;
1629 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001630 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1631 return TYPE_WIFI_P2P;
1632 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001633 return TYPE_NONE;
1634 }
1635
1636 private static class LegacyRequest {
1637 NetworkCapabilities networkCapabilities;
1638 NetworkRequest networkRequest;
1639 int expireSequenceNumber;
1640 Network currentNetwork;
1641 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001642
1643 private void clearDnsBinding() {
1644 if (currentNetwork != null) {
1645 currentNetwork = null;
1646 setProcessDefaultNetworkForHostResolution(null);
1647 }
1648 }
1649
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001650 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001651 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001652 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001653 currentNetwork = network;
1654 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001655 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001656 }
1657 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001658 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001659 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001660 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1661 }
1662 };
1663 }
1664
Mathew Inwood5a09a712020-11-04 09:29:36 +00001665 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001666 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1667 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001668
1669 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1670 synchronized (sLegacyRequests) {
1671 LegacyRequest l = sLegacyRequests.get(netCap);
1672 if (l != null) return l.networkRequest;
1673 }
1674 return null;
1675 }
1676
1677 private void renewRequestLocked(LegacyRequest l) {
1678 l.expireSequenceNumber++;
1679 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1680 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1681 }
1682
1683 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1684 int ourSeqNum = -1;
1685 synchronized (sLegacyRequests) {
1686 LegacyRequest l = sLegacyRequests.get(netCap);
1687 if (l == null) return;
1688 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001689 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001690 }
1691 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1692 }
1693
Mathew Inwood5a09a712020-11-04 09:29:36 +00001694 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001695 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1696 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001697 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001698 try {
1699 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001700 } catch (RemoteException e) {
1701 throw e.rethrowFromSystemServer();
1702 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001703 LegacyRequest l = new LegacyRequest();
1704 l.networkCapabilities = netCap;
1705 l.delay = delay;
1706 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001707 l.networkRequest = sendRequestForNetwork(
1708 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001709 if (l.networkRequest == null) return null;
1710 sLegacyRequests.put(netCap, l);
1711 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1712 return l.networkRequest;
1713 }
1714
1715 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1716 if (delay >= 0) {
1717 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001718 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001719 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1720 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001721 }
1722 }
1723
Mathew Inwood5a09a712020-11-04 09:29:36 +00001724 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001725 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1726 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001727 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001728 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001729 }
Paul Jensen034dea32014-12-17 10:39:34 -05001730 if (l == null) return false;
1731 unregisterNetworkCallback(l.networkCallback);
1732 l.clearDnsBinding();
1733 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001734 }
1735
Erik Kline50068e52017-01-26 18:08:28 +09001736 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1737 static {
1738 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1739 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1740 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1741 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1742 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1743 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1744 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1745 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1746 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1747 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1748 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1749 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1750 }
1751
1752 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1753 static {
1754 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1755 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1756 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1757 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1758 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1759 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1760 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1761 }
1762
1763 /**
1764 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1765 * instance suitable for registering a request or callback. Throws an
1766 * IllegalArgumentException if no mapping from the legacy type to
1767 * NetworkCapabilities is known.
1768 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001769 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1770 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001771 * @hide
1772 */
1773 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1774 final NetworkCapabilities nc = new NetworkCapabilities();
1775
1776 // Map from type to transports.
1777 final int NOT_FOUND = -1;
1778 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00001779 if (transport == NOT_FOUND) {
1780 throw new IllegalArgumentException("unknown legacy type: " + type);
1781 }
Erik Kline50068e52017-01-26 18:08:28 +09001782 nc.addTransportType(transport);
1783
1784 // Map from type to capabilities.
1785 nc.addCapability(sLegacyTypeToCapability.get(
1786 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1787 nc.maybeMarkCapabilitiesRestricted();
1788 return nc;
1789 }
1790
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001791 /** @hide */
1792 public static class PacketKeepaliveCallback {
Mathew Inwood5a09a712020-11-04 09:29:36 +00001793 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev198d6502019-11-04 17:50:59 +00001794 public PacketKeepaliveCallback() {
1795 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001796 /** The requested keepalive was successfully started. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001797 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001798 public void onStarted() {}
1799 /** The keepalive was successfully stopped. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001800 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001801 public void onStopped() {}
1802 /** An error occurred. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001803 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001804 public void onError(int error) {}
1805 }
1806
1807 /**
1808 * Allows applications to request that the system periodically send specific packets on their
1809 * behalf, using hardware offload to save battery power.
1810 *
1811 * To request that the system send keepalives, call one of the methods that return a
1812 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1813 * passing in a non-null callback. If the callback is successfully started, the callback's
1814 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1815 * specifying one of the {@code ERROR_*} constants in this class.
1816 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001817 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1818 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1819 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001820 *
junyulaia86defc2018-12-27 17:25:29 +08001821 * @deprecated Use {@link SocketKeepalive} instead.
1822 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001823 * @hide
1824 */
1825 public class PacketKeepalive {
1826
1827 private static final String TAG = "PacketKeepalive";
1828
1829 /** @hide */
1830 public static final int SUCCESS = 0;
1831
1832 /** @hide */
1833 public static final int NO_KEEPALIVE = -1;
1834
1835 /** @hide */
1836 public static final int BINDER_DIED = -10;
1837
1838 /** The specified {@code Network} is not connected. */
1839 public static final int ERROR_INVALID_NETWORK = -20;
1840 /** The specified IP addresses are invalid. For example, the specified source IP address is
1841 * not configured on the specified {@code Network}. */
1842 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1843 /** The requested port is invalid. */
1844 public static final int ERROR_INVALID_PORT = -22;
1845 /** The packet length is invalid (e.g., too long). */
1846 public static final int ERROR_INVALID_LENGTH = -23;
1847 /** The packet transmission interval is invalid (e.g., too short). */
1848 public static final int ERROR_INVALID_INTERVAL = -24;
1849
1850 /** The hardware does not support this request. */
1851 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001852 /** The hardware returned an error. */
1853 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001854
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001855 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001856 public static final int NATT_PORT = 4500;
1857
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001858 /** The minimum interval in seconds between keepalive packet transmissions */
1859 public static final int MIN_INTERVAL = 10;
1860
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001861 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001862 private final ISocketKeepaliveCallback mCallback;
1863 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001864
1865 private volatile Integer mSlot;
1866
Mathew Inwood5a09a712020-11-04 09:29:36 +00001867 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001868 public void stop() {
1869 try {
junyulai9f872232019-01-16 20:23:34 +08001870 mExecutor.execute(() -> {
1871 try {
1872 if (mSlot != null) {
1873 mService.stopKeepalive(mNetwork, mSlot);
1874 }
1875 } catch (RemoteException e) {
1876 Log.e(TAG, "Error stopping packet keepalive: ", e);
1877 throw e.rethrowFromSystemServer();
1878 }
1879 });
1880 } catch (RejectedExecutionException e) {
1881 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001882 }
1883 }
1884
1885 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00001886 Objects.requireNonNull(network, "network cannot be null");
1887 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001888 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08001889 mExecutor = Executors.newSingleThreadExecutor();
1890 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001891 @Override
junyulai9f872232019-01-16 20:23:34 +08001892 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08001893 final long token = Binder.clearCallingIdentity();
1894 try {
1895 mExecutor.execute(() -> {
1896 mSlot = slot;
1897 callback.onStarted();
1898 });
1899 } finally {
1900 Binder.restoreCallingIdentity(token);
1901 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001902 }
junyulai9f872232019-01-16 20:23:34 +08001903
1904 @Override
1905 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08001906 final long token = Binder.clearCallingIdentity();
1907 try {
1908 mExecutor.execute(() -> {
1909 mSlot = null;
1910 callback.onStopped();
1911 });
1912 } finally {
1913 Binder.restoreCallingIdentity(token);
1914 }
junyulai9f872232019-01-16 20:23:34 +08001915 mExecutor.shutdown();
1916 }
1917
1918 @Override
1919 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08001920 final long token = Binder.clearCallingIdentity();
1921 try {
1922 mExecutor.execute(() -> {
1923 mSlot = null;
1924 callback.onError(error);
1925 });
1926 } finally {
1927 Binder.restoreCallingIdentity(token);
1928 }
junyulai9f872232019-01-16 20:23:34 +08001929 mExecutor.shutdown();
1930 }
1931
1932 @Override
1933 public void onDataReceived() {
1934 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1935 // this callback when data is received.
1936 }
1937 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001938 }
1939 }
1940
1941 /**
1942 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1943 *
junyulaia86defc2018-12-27 17:25:29 +08001944 * @deprecated Use {@link #createSocketKeepalive} instead.
1945 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001946 * @hide
1947 */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001948 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001949 public PacketKeepalive startNattKeepalive(
1950 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1951 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1952 final PacketKeepalive k = new PacketKeepalive(network, callback);
1953 try {
junyulai9f872232019-01-16 20:23:34 +08001954 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001955 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1956 } catch (RemoteException e) {
1957 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08001958 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001959 }
1960 return k;
1961 }
1962
Chiachang Wangc5f86f42021-01-15 11:06:21 +08001963 // Construct an invalid fd.
1964 private ParcelFileDescriptor createInvalidFd() {
1965 final int invalidFd = -1;
1966 return ParcelFileDescriptor.adoptFd(invalidFd);
1967 }
1968
The Android Open Source Project28527d22009-03-03 19:31:44 -08001969 /**
junyulaia86defc2018-12-27 17:25:29 +08001970 * Request that keepalives be started on a IPsec NAT-T socket.
1971 *
1972 * @param network The {@link Network} the socket is on.
1973 * @param socket The socket that needs to be kept alive.
1974 * @param source The source address of the {@link UdpEncapsulationSocket}.
1975 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1976 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1977 * must run callback sequentially, otherwise the order of callbacks cannot be
1978 * guaranteed.
1979 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1980 * changes. Must be extended by applications that use this API.
1981 *
junyulaic7ea1242019-01-08 20:04:33 +08001982 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1983 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08001984 **/
junyulai61143782019-03-04 22:45:36 +08001985 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08001986 @NonNull UdpEncapsulationSocket socket,
1987 @NonNull InetAddress source,
1988 @NonNull InetAddress destination,
1989 @NonNull @CallbackExecutor Executor executor,
1990 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08001991 ParcelFileDescriptor dup;
1992 try {
junyulaic4fb2482019-03-27 11:00:37 +08001993 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1994 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08001995 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1996 } catch (IOException ignored) {
1997 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1998 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08001999 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002000 }
2001 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2002 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08002003 }
2004
2005 /**
2006 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2007 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2008 *
2009 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08002010 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2011 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2012 * from that port.
junyulai48a59382019-01-15 11:32:44 +08002013 * @param source The source address of the {@link UdpEncapsulationSocket}.
2014 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2015 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2016 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2017 * must run callback sequentially, otherwise the order of callbacks cannot be
2018 * guaranteed.
2019 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2020 * changes. Must be extended by applications that use this API.
2021 *
junyulaic7ea1242019-01-08 20:04:33 +08002022 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2023 * given socket.
junyulai48a59382019-01-15 11:32:44 +08002024 * @hide
2025 */
2026 @SystemApi
2027 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002028 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2029 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08002030 @NonNull InetAddress source,
2031 @NonNull InetAddress destination,
2032 @NonNull @CallbackExecutor Executor executor,
2033 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002034 ParcelFileDescriptor dup;
2035 try {
junyulaic4fb2482019-03-27 11:00:37 +08002036 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08002037 dup = pfd.dup();
2038 } catch (IOException ignored) {
2039 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2040 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002041 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002042 }
2043 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VAN642d6ab2021-03-11 10:56:49 +00002044 -1 /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08002045 }
2046
2047 /**
junyulaic7ea1242019-01-08 20:04:33 +08002048 * Request that keepalives be started on a TCP socket.
2049 * The socket must be established.
2050 *
2051 * @param network The {@link Network} the socket is on.
2052 * @param socket The socket that needs to be kept alive.
2053 * @param executor The executor on which callback will be invoked. This implementation assumes
2054 * the provided {@link Executor} runs the callbacks in sequence with no
2055 * concurrency. Failing this, no guarantee of correctness can be made. It is
2056 * the responsibility of the caller to ensure the executor provides this
2057 * guarantee. A simple way of creating such an executor is with the standard
2058 * tool {@code Executors.newSingleThreadExecutor}.
2059 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2060 * changes. Must be extended by applications that use this API.
2061 *
2062 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2063 * given socket.
2064 * @hide
2065 */
2066 @SystemApi
2067 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002068 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002069 @NonNull Socket socket,
2070 @NonNull Executor executor,
2071 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002072 ParcelFileDescriptor dup;
2073 try {
2074 dup = ParcelFileDescriptor.fromSocket(socket);
2075 } catch (UncheckedIOException ignored) {
2076 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2077 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002078 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002079 }
2080 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002081 }
2082
2083 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002084 * Ensure that a network route exists to deliver traffic to the specified
2085 * host via the specified network interface. An attempt to add a route that
2086 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002087 *
2088 * <p>This method requires the caller to hold either the
2089 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2090 * or the ability to modify system settings as determined by
2091 * {@link android.provider.Settings.System#canWrite}.</p>
2092 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002093 * @param networkType the type of the network over which traffic to the specified
2094 * host is to be routed
2095 * @param hostAddress the IP address of the host to which the route is desired
2096 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002097 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002098 * @deprecated Deprecated in favor of the
2099 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2100 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002101 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002102 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002103 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002104 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002105 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002106 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002107 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002108 }
2109
2110 /**
2111 * Ensure that a network route exists to deliver traffic to the specified
2112 * host via the specified network interface. An attempt to add a route that
2113 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002114 *
2115 * <p>This method requires the caller to hold either the
2116 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2117 * or the ability to modify system settings as determined by
2118 * {@link android.provider.Settings.System#canWrite}.</p>
2119 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002120 * @param networkType the type of the network over which traffic to the specified
2121 * host is to be routed
2122 * @param hostAddress the IP address of the host to which the route is desired
2123 * @return {@code true} on success, {@code false} on failure
2124 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002125 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002126 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002127 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002128 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002129 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002130 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002131 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002132 try {
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002133 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2134 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002135 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002136 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 }
2138 }
2139
2140 /**
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002141 * @return the context's attribution tag
2142 */
2143 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2144 private @Nullable String getAttributionTag() {
Roshan Piusc97d8062020-12-17 14:53:09 -08002145 return mContext.getAttributionTag();
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002146 }
2147
2148 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002149 * Returns the value of the setting for background data usage. If false,
2150 * applications should not use the network if the application is not in the
2151 * foreground. Developers should respect this setting, and check the value
2152 * of this before performing any background data operations.
2153 * <p>
2154 * All applications that have background services that use the network
2155 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002156 * <p>
Scott Main50589142011-10-06 18:32:43 -07002157 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002158 * background data depends on several combined factors, and this method will
2159 * always return {@code true}. Instead, when background data is unavailable,
2160 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002161 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002162 * @return Whether background data usage is allowed.
2163 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002164 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002165 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002166 // assume that background data is allowed; final authority is
2167 // NetworkInfo which may be blocked.
2168 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002169 }
2170
2171 /**
2172 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002173 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 * @param allowBackgroundData Whether an application should use data while
2175 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002176 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002177 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2178 * @see #getBackgroundDataSetting()
2179 * @hide
2180 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002181 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002182 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002183 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002184 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002185 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002186
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002187 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002188 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002189 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002190 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002191 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002192 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002193 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002194 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2195 if (tm != null) {
2196 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2197 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2198 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2199 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2200 + " retVal=" + retVal);
2201 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002202 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002203 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002204 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002205 }
2206
The Android Open Source Project28527d22009-03-03 19:31:44 -08002207 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002208 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002209 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002210 */
2211 public interface OnNetworkActiveListener {
2212 /**
2213 * Called on the main thread of the process to report that the current data network
2214 * has become active, and it is now a good time to perform any pending network
2215 * operations. Note that this listener only tells you when the network becomes
2216 * active; if at any other time you want to know whether it is active (and thus okay
2217 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002218 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002219 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002220 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002221 }
2222
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002223 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002224 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002225
2226 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002227 * Start listening to reports when the system's default data network is active, meaning it is
2228 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2229 * to determine the current state of the system's default network after registering the
2230 * listener.
2231 * <p>
2232 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002233 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002234 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002235 *
2236 * @param l The listener to be told when the network is active.
2237 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002238 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002239 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2240 @Override
2241 public void onNetworkActive() throws RemoteException {
2242 l.onNetworkActive();
2243 }
2244 };
2245
2246 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002247 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002248 mNetworkActivityListeners.put(l, rl);
2249 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002250 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002251 }
2252 }
2253
2254 /**
2255 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002256 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002257 *
2258 * @param l Previously registered listener.
2259 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002260 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002261 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00002262 if (rl == null) {
2263 throw new IllegalArgumentException("Listener was not registered.");
2264 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002265 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002266 mService.registerNetworkActivityListener(rl);
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002267 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002268 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002269 }
2270 }
2271
2272 /**
2273 * Return whether the data network is currently active. An active network means that
2274 * it is currently in a high power state for performing data transmission. On some
2275 * types of networks, it may be expensive to move and stay in such a state, so it is
2276 * more power efficient to batch network traffic together when the radio is already in
2277 * this state. This method tells you whether right now is currently a good time to
2278 * initiate network traffic, as the network is already active.
2279 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002280 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002281 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08002282 return mService.isDefaultNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002283 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002284 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002285 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002286 }
2287
2288 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002289 * {@hide}
2290 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002291 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00002292 mContext = Objects.requireNonNull(context, "missing context");
2293 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Amos Bianchiddadca42020-03-04 11:07:38 -08002294 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002295 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002296 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002297
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002298 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002299 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002300 public static ConnectivityManager from(Context context) {
2301 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2302 }
2303
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002304 /** @hide */
2305 public NetworkRequest getDefaultRequest() {
2306 try {
2307 // This is not racy as the default request is final in ConnectivityService.
2308 return mService.getDefaultRequest();
2309 } catch (RemoteException e) {
2310 throw e.rethrowFromSystemServer();
2311 }
2312 }
2313
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002314 /**
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002315 * Check if the package is a allowed to write settings. This also accounts that such an access
2316 * happened.
2317 *
2318 * @return {@code true} iff the package is allowed to write settings.
2319 */
2320 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2321 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2322 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2323 boolean throwException) {
2324 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2325 throwException);
2326 }
2327
2328 /**
Paul Jensen12131352014-12-10 15:12:18 -05002329 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2330 * situations where a Context pointer is unavailable.
2331 * @hide
2332 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002333 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002334 static ConnectivityManager getInstanceOrNull() {
2335 return sInstance;
2336 }
2337
2338 /**
2339 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2340 * situations where a Context pointer is unavailable.
2341 * @hide
2342 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002343 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002344 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002345 private static ConnectivityManager getInstance() {
2346 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002347 throw new IllegalStateException("No ConnectivityManager yet constructed");
2348 }
Paul Jensen895c3942015-03-10 10:54:12 -04002349 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002350 }
2351
2352 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002353 * Get the set of tetherable, available interfaces. This list is limited by
2354 * device configuration and current interface existence.
2355 *
2356 * @return an array of 0 or more Strings of tetherable interface names.
2357 *
markchieneeea0be2020-01-21 13:11:06 +08002358 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002359 * {@hide}
2360 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002361 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002362 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002363 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002364 public String[] getTetherableIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002365 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002366 }
2367
2368 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002369 * Get the set of tethered interfaces.
2370 *
2371 * @return an array of 0 or more String of currently tethered interface names.
2372 *
markchieneeea0be2020-01-21 13:11:06 +08002373 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002374 * {@hide}
2375 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002376 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002377 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002378 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002379 public String[] getTetheredIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002380 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002381 }
2382
2383 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002384 * Get the set of interface names which attempted to tether but
2385 * failed. Re-attempting to tether may cause them to reset to the Tethered
2386 * state. Alternatively, causing the interface to be destroyed and recreated
2387 * may cause them to reset to the available state.
2388 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2389 * information on the cause of the errors.
2390 *
2391 * @return an array of 0 or more String indicating the interface names
2392 * which failed to tether.
2393 *
markchieneeea0be2020-01-21 13:11:06 +08002394 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002395 * {@hide}
2396 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002397 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002398 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002399 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002400 public String[] getTetheringErroredIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002401 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002402 }
2403
2404 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002405 * Get the set of tethered dhcp ranges.
2406 *
markchien218230f2020-02-14 11:55:48 +08002407 * @deprecated This method is not supported.
2408 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002409 * {@hide}
2410 */
paulhud70b7dd2019-08-12 16:25:11 +08002411 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchieneeea0be2020-01-21 13:11:06 +08002412 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002413 public String[] getTetheredDhcpRanges() {
markchien218230f2020-02-14 11:55:48 +08002414 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002415 }
2416
2417 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002418 * Attempt to tether the named interface. This will setup a dhcp server
2419 * on the interface, forward and NAT IP packets and forward DNS requests
2420 * to the best active upstream network interface. Note that if no upstream
2421 * IP network interface is available, dhcp will still run and traffic will be
2422 * allowed between the tethered devices and this device, though upstream net
2423 * access will of course fail until an upstream network interface becomes
2424 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002425 *
2426 * <p>This method requires the caller to hold either the
2427 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2428 * or the ability to modify system settings as determined by
2429 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002430 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002431 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2432 * and WifiStateMachine which need direct access. All other clients should use
2433 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2434 * logic.</p>
2435 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002436 * @param iface the interface name to tether.
2437 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiencc1bc1b2020-01-20 19:31:56 +08002438 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002439 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002440 * {@hide}
2441 */
Mathew Inwood5a09a712020-11-04 09:29:36 +00002442 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiencc1bc1b2020-01-20 19:31:56 +08002443 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002444 public int tether(String iface) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002445 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002446 }
2447
2448 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002449 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002450 *
2451 * <p>This method requires the caller to hold either the
2452 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2453 * or the ability to modify system settings as determined by
2454 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002455 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002456 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2457 * and WifiStateMachine which need direct access. All other clients should use
2458 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2459 * logic.</p>
2460 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002461 * @param iface the interface name to untether.
2462 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2463 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002464 * {@hide}
2465 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002466 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002467 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002468 public int untether(String iface) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002469 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002470 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002471
2472 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002473 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002474 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002475 * due to device configuration.
2476 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002477 * <p>If this app does not have permission to use this API, it will always
2478 * return false rather than throw an exception.</p>
2479 *
2480 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2481 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2482 *
2483 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2484 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2485 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002486 * @return a boolean - {@code true} indicating Tethering is supported.
2487 *
markchieneeea0be2020-01-21 13:11:06 +08002488 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002489 * {@hide}
2490 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002491 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002492 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2493 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002494 public boolean isTetheringSupported() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002495 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002496 }
2497
2498 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002499 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchiencc1bc1b2020-01-20 19:31:56 +08002500 *
2501 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002502 * @hide
2503 */
2504 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002505 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002506 public static abstract class OnStartTetheringCallback {
2507 /**
2508 * Called when tethering has been successfully started.
2509 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002510 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002511
2512 /**
2513 * Called when starting tethering failed.
2514 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002515 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002516 }
2517
2518 /**
2519 * Convenient overload for
2520 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2521 * handler to run on the current thread's {@link Looper}.
markchiencc1bc1b2020-01-20 19:31:56 +08002522 *
2523 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002524 * @hide
2525 */
2526 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002527 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002528 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002529 public void startTethering(int type, boolean showProvisioningUi,
2530 final OnStartTetheringCallback callback) {
2531 startTethering(type, showProvisioningUi, callback, null);
2532 }
2533
2534 /**
2535 * Runs tether provisioning for the given type if needed and then starts tethering if
2536 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2537 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2538 * schedules tether provisioning re-checks if appropriate.
2539 *
2540 * @param type The type of tethering to start. Must be one of
2541 * {@link ConnectivityManager.TETHERING_WIFI},
2542 * {@link ConnectivityManager.TETHERING_USB}, or
2543 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2544 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2545 * is one. This should be true the first time this function is called and also any time
2546 * the user can see this UI. It gives users information from their carrier about the
2547 * check failing and how they can sign up for tethering if possible.
2548 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2549 * of the result of trying to tether.
2550 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchiencc1bc1b2020-01-20 19:31:56 +08002551 *
2552 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002553 * @hide
2554 */
2555 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002556 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002557 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002558 public void startTethering(int type, boolean showProvisioningUi,
2559 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00002560 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002561
markchiencc1bc1b2020-01-20 19:31:56 +08002562 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002563 @Override
markchiencc1bc1b2020-01-20 19:31:56 +08002564 public void execute(Runnable command) {
2565 if (handler == null) {
2566 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002567 } else {
markchiencc1bc1b2020-01-20 19:31:56 +08002568 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002569 }
2570 }
2571 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002572
markchiencc1bc1b2020-01-20 19:31:56 +08002573 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2574 @Override
2575 public void onTetheringStarted() {
2576 callback.onTetheringStarted();
2577 }
2578
2579 @Override
markchien19336c22020-03-19 13:37:43 +08002580 public void onTetheringFailed(final int error) {
markchiencc1bc1b2020-01-20 19:31:56 +08002581 callback.onTetheringFailed();
2582 }
2583 };
2584
2585 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien19336c22020-03-19 13:37:43 +08002586 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchiencc1bc1b2020-01-20 19:31:56 +08002587
Amos Bianchiddadca42020-03-04 11:07:38 -08002588 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002589 }
2590
2591 /**
2592 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2593 * applicable.
2594 *
2595 * @param type The type of tethering to stop. Must be one of
2596 * {@link ConnectivityManager.TETHERING_WIFI},
2597 * {@link ConnectivityManager.TETHERING_USB}, or
2598 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchieneeea0be2020-01-21 13:11:06 +08002599 *
2600 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002601 * @hide
2602 */
2603 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002604 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002605 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002606 public void stopTethering(int type) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002607 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002608 }
2609
2610 /**
markchiena005c992019-02-27 14:56:11 +08002611 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2612 * upstream status.
2613 *
Nathan Haroldbbb48c62020-01-23 18:03:46 -08002614 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchieneeea0be2020-01-21 13:11:06 +08002615 * @hide
markchiena005c992019-02-27 14:56:11 +08002616 */
2617 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002618 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002619 public abstract static class OnTetheringEventCallback {
2620
2621 /**
2622 * Called when tethering upstream changed. This can be called multiple times and can be
2623 * called any time.
2624 *
2625 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2626 * have any upstream.
2627 */
2628 public void onUpstreamChanged(@Nullable Network network) {}
2629 }
2630
markchieneeea0be2020-01-21 13:11:06 +08002631 @GuardedBy("mTetheringEventCallbacks")
2632 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2633 mTetheringEventCallbacks = new ArrayMap<>();
2634
markchiena005c992019-02-27 14:56:11 +08002635 /**
2636 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002637 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002638 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2639 * with a null argument. The same callback object cannot be registered twice.
2640 *
2641 * @param executor the executor on which callback will be invoked.
2642 * @param callback the callback to be called when tethering has change events.
markchieneeea0be2020-01-21 13:11:06 +08002643 *
Nathan Haroldbbb48c62020-01-23 18:03:46 -08002644 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002645 * @hide
2646 */
2647 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002648 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002649 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2650 public void registerTetheringEventCallback(
2651 @NonNull @CallbackExecutor Executor executor,
2652 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00002653 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchiena005c992019-02-27 14:56:11 +08002654
markchieneeea0be2020-01-21 13:11:06 +08002655 final TetheringEventCallback tetherCallback =
2656 new TetheringEventCallback() {
2657 @Override
2658 public void onUpstreamChanged(@Nullable Network network) {
2659 callback.onUpstreamChanged(network);
2660 }
2661 };
2662
2663 synchronized (mTetheringEventCallbacks) {
2664 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchiddadca42020-03-04 11:07:38 -08002665 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchieneeea0be2020-01-21 13:11:06 +08002666 }
markchiena005c992019-02-27 14:56:11 +08002667 }
2668
2669 /**
2670 * Remove tethering event callback previously registered with
2671 * {@link #registerTetheringEventCallback}.
2672 *
2673 * @param callback previously registered callback.
markchieneeea0be2020-01-21 13:11:06 +08002674 *
2675 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002676 * @hide
2677 */
2678 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002679 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002680 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2681 public void unregisterTetheringEventCallback(
2682 @NonNull final OnTetheringEventCallback callback) {
markchieneeea0be2020-01-21 13:11:06 +08002683 Objects.requireNonNull(callback, "The callback must be non-null");
2684 synchronized (mTetheringEventCallbacks) {
2685 final TetheringEventCallback tetherCallback =
2686 mTetheringEventCallbacks.remove(callback);
Amos Bianchiddadca42020-03-04 11:07:38 -08002687 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchieneeea0be2020-01-21 13:11:06 +08002688 }
markchiena005c992019-02-27 14:56:11 +08002689 }
2690
2691
2692 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002693 * Get the list of regular expressions that define any tetherable
2694 * USB network interfaces. If USB tethering is not supported by the
2695 * device, this list should be empty.
2696 *
2697 * @return an array of 0 or more regular expression Strings defining
2698 * what interfaces are considered tetherable usb interfaces.
2699 *
markchieneeea0be2020-01-21 13:11:06 +08002700 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002701 * {@hide}
2702 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002703 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002704 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002705 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002706 public String[] getTetherableUsbRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002707 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002708 }
2709
2710 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002711 * Get the list of regular expressions that define any tetherable
2712 * Wifi network interfaces. If Wifi tethering is not supported by the
2713 * device, this list should be empty.
2714 *
2715 * @return an array of 0 or more regular expression Strings defining
2716 * what interfaces are considered tetherable wifi interfaces.
2717 *
markchieneeea0be2020-01-21 13:11:06 +08002718 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002719 * {@hide}
2720 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002721 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002722 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002723 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002724 public String[] getTetherableWifiRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002725 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002726 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002727
Danica Chang96567052010-08-11 14:54:43 -07002728 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002729 * Get the list of regular expressions that define any tetherable
2730 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2731 * device, this list should be empty.
2732 *
2733 * @return an array of 0 or more regular expression Strings defining
2734 * what interfaces are considered tetherable bluetooth interfaces.
2735 *
markchieneeea0be2020-01-21 13:11:06 +08002736 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2737 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002738 * {@hide}
2739 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002740 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002741 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002742 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002743 public String[] getTetherableBluetoothRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002744 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002745 }
2746
Mike Lockwooded4a1742011-07-19 13:04:47 -07002747 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002748 * Attempt to both alter the mode of USB and Tethering of USB. A
2749 * utility method to deal with some of the complexity of USB - will
2750 * attempt to switch to Rndis and subsequently tether the resulting
2751 * interface on {@code true} or turn off tethering and switch off
2752 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002753 *
2754 * <p>This method requires the caller to hold either the
2755 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2756 * or the ability to modify system settings as determined by
2757 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002758 *
2759 * @param enable a boolean - {@code true} to enable tethering
2760 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiencc1bc1b2020-01-20 19:31:56 +08002761 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002762 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002763 * {@hide}
2764 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002765 @UnsupportedAppUsage
markchiencc1bc1b2020-01-20 19:31:56 +08002766 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002767 public int setUsbTethering(boolean enable) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002768 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002769 }
2770
markchieneeea0be2020-01-21 13:11:06 +08002771 /**
2772 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2773 * {@hide}
2774 */
markchien5bd499c2019-01-16 17:44:13 +08002775 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002776 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002777 public static final int TETHER_ERROR_NO_ERROR = 0;
markchieneeea0be2020-01-21 13:11:06 +08002778 /**
2779 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2780 * {@hide}
2781 */
2782 @Deprecated
2783 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2784 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2785 /**
2786 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2787 * {@hide}
2788 */
2789 @Deprecated
2790 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2791 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2792 /**
2793 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2794 * {@hide}
2795 */
2796 @Deprecated
2797 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2798 /**
2799 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2800 * {@hide}
2801 */
2802 @Deprecated
2803 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2804 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2805 /**
markchien19336c22020-03-19 13:37:43 +08002806 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002807 * {@hide}
2808 */
2809 @Deprecated
markchien19336c22020-03-19 13:37:43 +08002810 public static final int TETHER_ERROR_MASTER_ERROR =
2811 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002812 /**
2813 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2814 * {@hide}
2815 */
2816 @Deprecated
2817 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2818 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2819 /**
2820 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2821 * {@hide}
2822 */
2823 @Deprecated
2824 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2825 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2826 /**
markchien19336c22020-03-19 13:37:43 +08002827 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002828 * {@hide}
2829 */
2830 @Deprecated
2831 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien19336c22020-03-19 13:37:43 +08002832 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002833 /**
markchien19336c22020-03-19 13:37:43 +08002834 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002835 * {@hide}
2836 */
2837 @Deprecated
2838 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien19336c22020-03-19 13:37:43 +08002839 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002840 /**
2841 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2842 * {@hide}
2843 */
2844 @Deprecated
2845 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2846 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2847 /**
markchien19336c22020-03-19 13:37:43 +08002848 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchieneeea0be2020-01-21 13:11:06 +08002849 * {@hide}
2850 */
markchien5bd499c2019-01-16 17:44:13 +08002851 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002852 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002853 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchieneeea0be2020-01-21 13:11:06 +08002854 /**
2855 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2856 * {@hide}
2857 */
2858 @Deprecated
2859 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2860 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2861 /**
2862 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2863 * {@hide}
2864 */
markchien5bd499c2019-01-16 17:44:13 +08002865 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002866 @Deprecated
Remi NGUYEN VAN23b853b2021-02-15 18:52:06 +09002867 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002868
2869 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002870 * Get a more detailed error code after a Tethering or Untethering
2871 * request asynchronously failed.
2872 *
2873 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002874 * @return error The error code of the last error tethering or untethering the named
2875 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002876 *
markchieneeea0be2020-01-21 13:11:06 +08002877 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002878 * {@hide}
2879 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002880 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood5a09a712020-11-04 09:29:36 +00002881 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchieneeea0be2020-01-21 13:11:06 +08002882 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002883 public int getLastTetherError(String iface) {
markchien19336c22020-03-19 13:37:43 +08002884 int error = mTetheringManager.getLastTetherError(iface);
2885 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2886 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2887 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2888 // instead.
2889 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2890 }
2891 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002892 }
2893
markchiendd41c822019-03-06 16:25:00 +08002894 /** @hide */
2895 @Retention(RetentionPolicy.SOURCE)
2896 @IntDef(value = {
2897 TETHER_ERROR_NO_ERROR,
2898 TETHER_ERROR_PROVISION_FAILED,
2899 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2900 })
2901 public @interface EntitlementResultCode {
2902 }
2903
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002904 /**
markchiendd41c822019-03-06 16:25:00 +08002905 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08002906 * entitlement succeeded.
markchieneeea0be2020-01-21 13:11:06 +08002907 *
2908 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08002909 * @hide
2910 */
2911 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002912 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08002913 public interface OnTetheringEntitlementResultListener {
2914 /**
2915 * Called to notify entitlement result.
2916 *
2917 * @param resultCode an int value of entitlement result. It may be one of
2918 * {@link #TETHER_ERROR_NO_ERROR},
2919 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2920 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2921 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07002922 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08002923 }
2924
2925 /**
markchien5bd499c2019-01-16 17:44:13 +08002926 * Get the last value of the entitlement check on this downstream. If the cached value is
2927 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2928 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2929 * guaranteed that the UI-based entitlement check will complete in any specific time period
2930 * and may in fact never complete. Any successful entitlement check the platform performs for
2931 * any reason will update the cached value.
2932 *
2933 * @param type the downstream type of tethering. Must be one of
2934 * {@link #TETHERING_WIFI},
2935 * {@link #TETHERING_USB}, or
2936 * {@link #TETHERING_BLUETOOTH}.
2937 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08002938 * @param executor the executor on which callback will be invoked.
2939 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2940 * notify the caller of the result of entitlement check. The listener may be called zero
2941 * or one time.
markchieneeea0be2020-01-21 13:11:06 +08002942 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08002943 * {@hide}
2944 */
2945 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002946 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08002947 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08002948 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2949 @NonNull @CallbackExecutor Executor executor,
2950 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00002951 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchiendd41c822019-03-06 16:25:00 +08002952 ResultReceiver wrappedListener = new ResultReceiver(null) {
2953 @Override
2954 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslin9cc04192021-03-04 09:38:21 +08002955 final long token = Binder.clearCallingIdentity();
2956 try {
2957 executor.execute(() -> {
2958 listener.onTetheringEntitlementResult(resultCode);
2959 });
2960 } finally {
2961 Binder.restoreCallingIdentity(token);
2962 }
markchiendd41c822019-03-06 16:25:00 +08002963 }
2964 };
2965
Amos Bianchiddadca42020-03-04 11:07:38 -08002966 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien4f949812019-12-16 20:15:20 +08002967 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08002968 }
2969
2970 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002971 * Report network connectivity status. This is currently used only
2972 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04002973 * <p>This method requires the caller to hold the permission
2974 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08002975 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002976 * @param networkType The type of network you want to report on
2977 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09002978 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002979 * {@hide}
2980 */
2981 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09002982 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002983 try {
2984 mService.reportInetCondition(networkType, percentage);
2985 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002986 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002987 }
2988 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002989
2990 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002991 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07002992 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002993 * the framework to re-evaluate network connectivity and/or switch to another
2994 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07002995 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002996 * @param network The {@link Network} the application was attempting to use
2997 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04002998 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2999 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003000 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003001 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09003002 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003003 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003004 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04003005 // One of these will be ignored because it matches system's current state.
3006 // The other will trigger the necessary reevaluation.
3007 mService.reportNetworkConnectivity(network, true);
3008 mService.reportNetworkConnectivity(network, false);
3009 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003010 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003011 }
3012 }
3013
3014 /**
3015 * Report to the framework whether a network has working connectivity.
3016 * This provides a hint to the system that a particular network is providing
3017 * working connectivity or not. In response the framework may re-evaluate
3018 * the network's connectivity and might take further action thereafter.
3019 *
3020 * @param network The {@link Network} the application was attempting to use
3021 * or {@code null} to indicate the current default network.
3022 * @param hasConnectivity {@code true} if the application was able to successfully access the
3023 * Internet using {@code network} or {@code false} if not.
3024 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003025 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003026 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003027 try {
3028 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003029 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003030 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003031 }
3032 }
3033
3034 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003035 * Set a network-independent global http proxy. This is not normally what you want
3036 * for typical HTTP proxies - they are general network dependent. However if you're
3037 * doing something unusual like general internal filtering this may be useful. On
3038 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003039 *
3040 * @param p A {@link ProxyInfo} object defining the new global
3041 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003042 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003043 */
paulhud70b7dd2019-08-12 16:25:11 +08003044 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk1e3df5d2014-04-25 15:00:09 -04003045 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003046 try {
3047 mService.setGlobalProxy(p);
3048 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003049 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003050 }
3051 }
3052
3053 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003054 * Retrieve any network-independent global HTTP proxy.
3055 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003056 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003057 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003058 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003059 */
Jason Monk1e3df5d2014-04-25 15:00:09 -04003060 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003061 try {
3062 return mService.getGlobalProxy();
3063 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003064 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003065 }
3066 }
3067
3068 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003069 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3070 * network-specific HTTP proxy. If {@code network} is null, the
3071 * network-specific proxy returned is the proxy of the default active
3072 * network.
3073 *
3074 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3075 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3076 * or when {@code network} is {@code null},
3077 * the {@code ProxyInfo} for the default active network. Returns
3078 * {@code null} when no proxy applies or the caller doesn't have
3079 * permission to use {@code network}.
3080 * @hide
3081 */
3082 public ProxyInfo getProxyForNetwork(Network network) {
3083 try {
3084 return mService.getProxyForNetwork(network);
3085 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003086 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003087 }
3088 }
3089
3090 /**
Paul Jensen12131352014-12-10 15:12:18 -05003091 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3092 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003093 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003094 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003095 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003096 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003097 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003098 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003099 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003100 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003101 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003102 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003103
3104 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003105 * Returns true if the hardware supports the given network type
3106 * else it returns false. This doesn't indicate we have coverage
3107 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003108 * hardware supports it. For example a GSM phone without a SIM
3109 * should still return {@code true} for mobile data, but a wifi only
3110 * tablet would return {@code false}.
3111 *
3112 * @param networkType The network type we'd like to check
3113 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003114 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003115 * @hide
3116 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003117 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003118 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003119 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003120 public boolean isNetworkSupported(int networkType) {
3121 try {
3122 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003123 } catch (RemoteException e) {
3124 throw e.rethrowFromSystemServer();
3125 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003126 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003127
3128 /**
3129 * Returns if the currently active data network is metered. A network is
3130 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003131 * that connection due to monetary costs, data limitations or
3132 * battery/performance issues. You should check this before doing large
3133 * data transfers, and warn the user or delay the operation until another
3134 * network is available.
3135 *
3136 * @return {@code true} if large transfers should be avoided, otherwise
3137 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003138 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003139 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003140 public boolean isActiveNetworkMetered() {
3141 try {
3142 return mService.isActiveNetworkMetered();
3143 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003144 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003145 }
3146 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003147
Robert Greenwalt26744a52013-02-15 10:56:35 -08003148 /**
Sarah Chincf44f2f2020-11-25 12:15:14 -08003149 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003150 *
Sarah Chincf44f2f2020-11-25 12:15:14 -08003151 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003152 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003153 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003154 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003155 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003156 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003157 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003158 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003159 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003160 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003161 }
3162 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003163
3164 /**
3165 * Set the value for enabling/disabling airplane mode
3166 *
3167 * @param enable whether to enable airplane mode or not
3168 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003169 * @hide
3170 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003171 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003172 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003173 android.Manifest.permission.NETWORK_SETTINGS,
3174 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3175 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003176 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003177 public void setAirplaneMode(boolean enable) {
3178 try {
3179 mService.setAirplaneMode(enable);
3180 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003181 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003182 }
3183 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003184
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003185 /**
3186 * Registers the specified {@link NetworkProvider}.
3187 * Each listener must only be registered once. The listener can be unregistered with
3188 * {@link #unregisterNetworkProvider}.
3189 *
3190 * @param provider the provider to register
3191 * @return the ID of the provider. This ID must be used by the provider when registering
3192 * {@link android.net.NetworkAgent}s.
3193 * @hide
3194 */
3195 @SystemApi
paulhu44939832020-03-04 09:43:41 +08003196 @RequiresPermission(anyOf = {
3197 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3198 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003199 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3200 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003201 throw new IllegalStateException("NetworkProviders can only be registered once");
3202 }
3203
3204 try {
3205 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3206 provider.getName());
3207 provider.setProviderId(providerId);
3208 } catch (RemoteException e) {
3209 throw e.rethrowFromSystemServer();
3210 }
3211 return provider.getProviderId();
3212 }
3213
3214 /**
3215 * Unregisters the specified NetworkProvider.
3216 *
3217 * @param provider the provider to unregister
3218 * @hide
3219 */
3220 @SystemApi
paulhu44939832020-03-04 09:43:41 +08003221 @RequiresPermission(anyOf = {
3222 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3223 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003224 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3225 try {
3226 mService.unregisterNetworkProvider(provider.getMessenger());
3227 } catch (RemoteException e) {
3228 throw e.rethrowFromSystemServer();
3229 }
3230 provider.setProviderId(NetworkProvider.ID_NONE);
3231 }
3232
3233
3234 /** @hide exposed via the NetworkProvider class. */
paulhu44939832020-03-04 09:43:41 +08003235 @RequiresPermission(anyOf = {
3236 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3237 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003238 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3239 try {
3240 mService.declareNetworkRequestUnfulfillable(request);
3241 } catch (RemoteException e) {
3242 throw e.rethrowFromSystemServer();
3243 }
3244 }
3245
Paul Jensenc2569432015-02-13 14:18:39 -05003246 /**
3247 * @hide
3248 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana973c7a2019-12-13 19:47:12 +09003249 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003250 */
paulhu44939832020-03-04 09:43:41 +08003251 @RequiresPermission(anyOf = {
3252 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3253 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003254 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeandd753522020-12-21 18:36:52 +09003255 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3256 int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003257 try {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003258 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003259 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003260 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003261 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003262 }
3263
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003264 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003265 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3266 * changes. Should be extended by applications wanting notifications.
3267 *
3268 * A {@code NetworkCallback} is registered by calling
3269 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3270 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003271 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003272 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3273 * A {@code NetworkCallback} should be registered at most once at any time.
3274 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003275 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003276 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003277 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003278 * No flags associated with this callback.
3279 * @hide
3280 */
3281 public static final int FLAG_NONE = 0;
3282 /**
3283 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3284 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3285 * <p>
3286 * These include:
3287 * <li> Some transport info instances (retrieved via
3288 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3289 * contain location sensitive information.
3290 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3291 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3292 * </p>
3293 * <p>
3294 * Note:
3295 * <li> Retrieving this location sensitive information (subject to app's location
3296 * permissions) will be noted by system. </li>
3297 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3298 * not include location sensitive info.
3299 * </p>
3300 */
3301 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3302
3303 /** @hide */
3304 @Retention(RetentionPolicy.SOURCE)
3305 @IntDef(flag = true, prefix = "FLAG_", value = {
3306 FLAG_NONE,
3307 FLAG_INCLUDE_LOCATION_INFO
3308 })
3309 public @interface Flag { }
3310
3311 /**
3312 * All the valid flags for error checking.
3313 */
3314 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3315
3316 public NetworkCallback() {
3317 this(FLAG_NONE);
3318 }
3319
3320 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00003321 if ((flags & VALID_FLAGS) != flags) {
3322 throw new IllegalArgumentException("Invalid flags");
3323 }
Roshan Pius7992afd2020-12-22 15:10:42 -08003324 mFlags = flags;
3325 }
3326
3327 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003328 * Called when the framework connects to a new network to evaluate whether it satisfies this
3329 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3330 * callback. There is no guarantee that this new network will satisfy any requests, or that
3331 * the network will stay connected for longer than the time necessary to evaluate it.
3332 * <p>
3333 * Most applications <b>should not</b> act on this callback, and should instead use
3334 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3335 * the framework in properly evaluating the network &mdash; for example, an application that
3336 * can automatically log in to a captive portal without user intervention.
3337 *
3338 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003339 *
3340 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003341 */
paulhua9a6e2a2019-03-22 16:35:06 +08003342 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003343
3344 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003345 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003346 * This callback may be called more than once if the {@link Network} that is
3347 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003348 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003349 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003350 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3351 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003352 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003353 * @hide
3354 */
paulhua9a6e2a2019-03-22 16:35:06 +08003355 public void onAvailable(@NonNull Network network,
3356 @NonNull NetworkCapabilities networkCapabilities,
3357 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003358 // Internally only this method is called when a new network is available, and
3359 // it calls the callback in the same way and order that older versions used
3360 // to call so as not to change the behavior.
3361 onAvailable(network);
3362 if (!networkCapabilities.hasCapability(
3363 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3364 onNetworkSuspended(network);
3365 }
3366 onCapabilitiesChanged(network, networkCapabilities);
3367 onLinkPropertiesChanged(network, linkProperties);
junyulai5ab727b2018-08-07 19:50:45 +08003368 onBlockedStatusChanged(network, blocked);
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003369 }
3370
3371 /**
3372 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003373 *
3374 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3375 * be available at the same time, and onAvailable will be called for each of these as they
3376 * appear.
3377 *
3378 * <p>For callbacks registered with {@link #requestNetwork} and
3379 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3380 * is the new best network for this request and is now tracked by this callback ; this
3381 * callback will no longer receive method calls about other networks that may have been
3382 * passed to this method previously. The previously-best network may have disconnected, or
3383 * it may still be around and the newly-best network may simply be better.
3384 *
3385 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3386 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3387 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3388 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3389 *
3390 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3391 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3392 * this callback as this is prone to race conditions (there is no guarantee the objects
3393 * returned by these methods will be current). Instead, wait for a call to
3394 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3395 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3396 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003397 *
3398 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003399 */
paulhua9a6e2a2019-03-22 16:35:06 +08003400 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003401
3402 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003403 * Called when the network is about to be lost, typically because there are no outstanding
3404 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3405 * with the new replacement network for graceful handover. This method is not guaranteed
3406 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3407 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003408 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003409 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3410 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3411 * this callback as this is prone to race conditions ; calling these methods while in a
3412 * callback may return an outdated or even a null object.
3413 *
3414 * @param network The {@link Network} that is about to be lost.
3415 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3416 * connected for graceful handover; note that the network may still
3417 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003418 */
paulhua9a6e2a2019-03-22 16:35:06 +08003419 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003420
3421 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003422 * Called when a network disconnects or otherwise no longer satisfies this request or
3423 * callback.
3424 *
3425 * <p>If the callback was registered with requestNetwork() or
3426 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3427 * returned by onAvailable() when that network is lost and no other network satisfies
3428 * the criteria of the request.
3429 *
3430 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3431 * each network which no longer satisfies the criteria of the callback.
3432 *
3433 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3434 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3435 * this callback as this is prone to race conditions ; calling these methods while in a
3436 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003437 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003438 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003439 */
paulhua9a6e2a2019-03-22 16:35:06 +08003440 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003441
3442 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003443 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003444 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3445 * requested network request cannot be fulfilled (whether or not a timeout was
3446 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003447 * {@link NetworkRequest} will have already been removed and released, as if
3448 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003449 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003450 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003451
3452 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003453 * Called when the network corresponding to this request changes capabilities but still
3454 * satisfies the requested criteria.
3455 *
3456 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3457 * to be called immediately after {@link #onAvailable}.
3458 *
3459 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3460 * ConnectivityManager methods in this callback as this is prone to race conditions :
3461 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003462 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003463 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius7992afd2020-12-22 15:10:42 -08003464 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003465 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003466 */
paulhua9a6e2a2019-03-22 16:35:06 +08003467 public void onCapabilitiesChanged(@NonNull Network network,
3468 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003469
3470 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003471 * Called when the network corresponding to this request changes {@link LinkProperties}.
3472 *
3473 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3474 * to be called immediately after {@link #onAvailable}.
3475 *
3476 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3477 * ConnectivityManager methods in this callback as this is prone to race conditions :
3478 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003479 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003480 * @param network The {@link Network} whose link properties have changed.
3481 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003482 */
paulhua9a6e2a2019-03-22 16:35:06 +08003483 public void onLinkPropertiesChanged(@NonNull Network network,
3484 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003485
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003486 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003487 * Called when the network the framework connected to for this request suspends data
3488 * transmission temporarily.
3489 *
3490 * <p>This generally means that while the TCP connections are still live temporarily
3491 * network data fails to transfer. To give a specific example, this is used on cellular
3492 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3493 * means read operations on sockets on this network will block once the buffers are
3494 * drained, and write operations will block once the buffers are full.
3495 *
3496 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3497 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3498 * this callback as this is prone to race conditions (there is no guarantee the objects
3499 * returned by these methods will be current).
3500 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003501 * @hide
3502 */
paulhua9a6e2a2019-03-22 16:35:06 +08003503 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003504
3505 /**
3506 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003507 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3508 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003509
3510 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3511 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3512 * this callback as this is prone to race conditions : calling these methods while in a
3513 * callback may return an outdated or even a null object.
3514 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003515 * @hide
3516 */
paulhua9a6e2a2019-03-22 16:35:06 +08003517 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003518
junyulai5ab727b2018-08-07 19:50:45 +08003519 /**
3520 * Called when access to the specified network is blocked or unblocked.
3521 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003522 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3523 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3524 * this callback as this is prone to race conditions : calling these methods while in a
3525 * callback may return an outdated or even a null object.
3526 *
junyulai5ab727b2018-08-07 19:50:45 +08003527 * @param network The {@link Network} whose blocked status has changed.
3528 * @param blocked The blocked status of this {@link Network}.
3529 */
junyulai61143782019-03-04 22:45:36 +08003530 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003531
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003532 private NetworkRequest networkRequest;
Roshan Pius7992afd2020-12-22 15:10:42 -08003533 private final int mFlags;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003534 }
3535
Hugo Benichi145e3792017-05-11 13:16:17 +09003536 /**
3537 * Constant error codes used by ConnectivityService to communicate about failures and errors
3538 * across a Binder boundary.
3539 * @hide
3540 */
3541 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003542 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003543 }
3544
3545 /** @hide */
3546 public static class TooManyRequestsException extends RuntimeException {}
3547
3548 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3549 switch (e.errorCode) {
3550 case Errors.TOO_MANY_REQUESTS:
3551 return new TooManyRequestsException();
3552 default:
3553 Log.w(TAG, "Unknown service error code " + e.errorCode);
3554 return new RuntimeException(e);
3555 }
3556 }
3557
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003558 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003559 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003560 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003561 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003562 /** @hide arg1 = TTL */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003563 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003564 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003565 public static final int CALLBACK_LOST = 4;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003566 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003567 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003568 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003569 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003570 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003571 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003572 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003573 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003574 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003575 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003576 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003577 public static final int CALLBACK_RESUMED = 10;
junyulai5ab727b2018-08-07 19:50:45 +08003578 /** @hide */
Remi NGUYEN VANa711b3f2021-03-12 15:24:06 +09003579 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003580
Erik Kline66721822015-11-25 12:49:38 +09003581 /** @hide */
3582 public static String getCallbackName(int whichCallback) {
3583 switch (whichCallback) {
3584 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3585 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3586 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3587 case CALLBACK_LOST: return "CALLBACK_LOST";
3588 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3589 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3590 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003591 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3592 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3593 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003594 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003595 default:
3596 return Integer.toString(whichCallback);
3597 }
3598 }
3599
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003600 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003601 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003602 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003603
Hugo Benichife3325f2016-07-06 22:53:17 +09003604 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003605 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003606 }
3607
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003608 CallbackHandler(Handler handler) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00003609 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003610 }
3611
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003612 @Override
3613 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003614 if (message.what == EXPIRE_LEGACY_REQUEST) {
3615 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3616 return;
3617 }
3618
3619 final NetworkRequest request = getObject(message, NetworkRequest.class);
3620 final Network network = getObject(message, Network.class);
3621 final NetworkCallback callback;
3622 synchronized (sCallbacks) {
3623 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003624 if (callback == null) {
3625 Log.w(TAG,
3626 "callback not found for " + getCallbackName(message.what) + " message");
3627 return;
3628 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003629 if (message.what == CALLBACK_UNAVAIL) {
3630 sCallbacks.remove(request);
3631 callback.networkRequest = ALREADY_UNREGISTERED;
3632 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003633 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003634 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003635 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003636 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003637
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003638 switch (message.what) {
3639 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003640 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003641 break;
3642 }
3643 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003644 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3645 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai5ab727b2018-08-07 19:50:45 +08003646 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003647 break;
3648 }
3649 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003650 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003651 break;
3652 }
3653 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003654 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003655 break;
3656 }
3657 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003658 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003659 break;
3660 }
3661 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003662 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3663 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003664 break;
3665 }
3666 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003667 LinkProperties lp = getObject(message, LinkProperties.class);
3668 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003669 break;
3670 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003671 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003672 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003673 break;
3674 }
3675 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003676 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003677 break;
3678 }
junyulai5ab727b2018-08-07 19:50:45 +08003679 case CALLBACK_BLK_CHANGED: {
3680 boolean blocked = message.arg1 != 0;
3681 callback.onBlockedStatusChanged(network, blocked);
3682 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003683 }
3684 }
3685
Hugo Benichife3325f2016-07-06 22:53:17 +09003686 private <T> T getObject(Message msg, Class<T> c) {
3687 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003688 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003689 }
3690
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003691 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003692 synchronized (sCallbacks) {
3693 if (sCallbackHandler == null) {
3694 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003695 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003696 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003697 }
3698 }
3699
Hugo Benichiec180d52017-02-03 14:18:44 +09003700 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3701 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003702
Hugo Benichiec180d52017-02-03 14:18:44 +09003703 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaid1a78162021-01-11 16:53:38 +08003704 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003705 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003706 checkCallbackNotNull(callback);
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00003707 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3708 throw new IllegalArgumentException("null NetworkCapabilities");
3709 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003710 final NetworkRequest request;
Roshan Pius34dc4be2020-01-16 12:17:17 -08003711 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003712 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003713 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003714 if (callback.networkRequest != null
3715 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003716 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3717 // and requests (http://b/20701525).
3718 Log.e(TAG, "NetworkCallback was already registered");
3719 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003720 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003721 Binder binder = new Binder();
Roshan Pius7992afd2020-12-22 15:10:42 -08003722 final int callbackFlags = callback.mFlags;
junyulaid1a78162021-01-11 16:53:38 +08003723 if (reqType == LISTEN) {
Roshan Pius34dc4be2020-01-16 12:17:17 -08003724 request = mService.listenForNetwork(
Roshan Pius7992afd2020-12-22 15:10:42 -08003725 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08003726 getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003727 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003728 request = mService.requestNetwork(
junyulaid1a78162021-01-11 16:53:38 +08003729 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
Roshan Pius7992afd2020-12-22 15:10:42 -08003730 callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003731 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003732 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003733 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003734 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003735 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003736 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003737 } catch (RemoteException e) {
3738 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003739 } catch (ServiceSpecificException e) {
3740 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003741 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003742 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003743 }
3744
3745 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003746 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003747 *
markchieneddbe2b2020-03-18 21:16:15 +08003748 * This API is only for use in internal system code that requests networks with legacy type and
3749 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchienddd59372020-01-14 00:55:21 +08003750 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003751 *
markchienddd59372020-01-14 00:55:21 +08003752 * @param request {@link NetworkRequest} describing this request.
markchienddd59372020-01-14 00:55:21 +08003753 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3754 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3755 * be a positive value (i.e. >0).
3756 * @param legacyType to specify the network type(#TYPE_*).
3757 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchieneddbe2b2020-03-18 21:16:15 +08003758 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3759 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003760 *
3761 * @hide
3762 */
markchienddd59372020-01-14 00:55:21 +08003763 @SystemApi
markchieneddbe2b2020-03-18 21:16:15 +08003764 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003765 public void requestNetwork(@NonNull NetworkRequest request,
markchieneddbe2b2020-03-18 21:16:15 +08003766 int timeoutMs, int legacyType, @NonNull Handler handler,
3767 @NonNull NetworkCallback networkCallback) {
3768 if (legacyType == TYPE_NONE) {
3769 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3770 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003771 CallbackHandler cbHandler = new CallbackHandler(handler);
3772 NetworkCapabilities nc = request.networkCapabilities;
3773 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003774 }
3775
3776 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003777 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003778 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003779 * <p>This method will attempt to find the best network that matches the passed
3780 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3781 * criteria. The platform will evaluate which network is the best at its own discretion.
3782 * Throughput, latency, cost per byte, policy, user preference and other considerations
3783 * may be factored in the decision of what is considered the best network.
3784 *
3785 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3786 * matching this request, while always attempting to match the request to a better network if
3787 * possible. If a better match is found, the platform will switch this request to the now-best
3788 * network and inform the app of the newly best network by invoking
3789 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3790 * will not try to maintain any other network than the best one currently matching the request:
3791 * a network not matching any network request may be disconnected at any time.
3792 *
3793 * <p>For example, an application could use this method to obtain a connected cellular network
3794 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3795 * radio to consume additional power. Or, an application could inform the system that it wants
3796 * a network supporting sending MMSes and have the system let it know about the currently best
3797 * MMS-supporting network through the provided {@link NetworkCallback}.
3798 *
3799 * <p>The status of the request can be followed by listening to the various callbacks described
3800 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3801 * used to direct traffic to the network (although accessing some networks may be subject to
3802 * holding specific permissions). Callers will learn about the specific characteristics of the
3803 * network through
3804 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3805 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3806 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3807 * matching the request at any given time; therefore when a better network matching the request
3808 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3809 * with the new network after which no further updates are given about the previously-best
3810 * network, unless it becomes the best again at some later time. All callbacks are invoked
3811 * in order on the same thread, which by default is a thread created by the framework running
3812 * in the app.
3813 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3814 * callbacks are invoked.
3815 *
3816 * <p>This{@link NetworkRequest} will live until released via
3817 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3818 * which point the system may let go of the network at any time.
3819 *
3820 * <p>A version of this method which takes a timeout is
3821 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3822 * wait for a limited amount of time for the network to become unavailable.
3823 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003824 * <p>It is presently unsupported to request a network with mutable
3825 * {@link NetworkCapabilities} such as
3826 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3827 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3828 * as these {@code NetworkCapabilities} represent states that a particular
3829 * network may never attain, and whether a network will attain these states
3830 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09003831 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003832 *
3833 * <p>This method requires the caller to hold either the
3834 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3835 * or the ability to modify system settings as determined by
3836 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003837 *
Chalard Jean7f06b342020-05-20 16:11:50 +09003838 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3839 * number of outstanding requests to 100 per app (identified by their UID), shared with
3840 * all variants of this method, of {@link #registerNetworkCallback} as well as
3841 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3842 * Requesting a network with this method will count toward this limit. If this limit is
3843 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3844 * make sure to unregister the callbacks with
3845 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3846 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003847 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003848 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3849 * the callback must not be shared - it uniquely specifies this request.
3850 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09003851 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3852 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09003853 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003854 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003855 public void requestNetwork(@NonNull NetworkRequest request,
3856 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003857 requestNetwork(request, networkCallback, getDefaultHandler());
3858 }
3859
3860 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003861 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003862 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003863 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3864 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003865 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003866 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003867 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3868 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003869 *
3870 * @param request {@link NetworkRequest} describing this request.
3871 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3872 * the callback must not be shared - it uniquely specifies this request.
3873 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003874 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003875 public void requestNetwork(@NonNull NetworkRequest request,
3876 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003877 CallbackHandler cbHandler = new CallbackHandler(handler);
markchieneddbe2b2020-03-18 21:16:15 +08003878 NetworkCapabilities nc = request.networkCapabilities;
3879 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003880 }
3881
3882 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003883 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohen67e58a02017-03-01 12:47:28 -08003884 * by a timeout.
3885 *
3886 * This function behaves identically to the non-timed-out version
3887 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3888 * is not found within the given time (in milliseconds) the
3889 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3890 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3891 * not have to be released if timed-out (it is automatically released). Unregistering a
3892 * request that timed out is not an error.
3893 *
3894 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3895 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3896 * for that purpose. Calling this method will attempt to bring up the requested network.
3897 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003898 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003899 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3900 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08003901 *
3902 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003903 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3904 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003905 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3906 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3907 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08003908 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003909 public void requestNetwork(@NonNull NetworkRequest request,
3910 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003911 checkTimeout(timeoutMs);
markchieneddbe2b2020-03-18 21:16:15 +08003912 NetworkCapabilities nc = request.networkCapabilities;
3913 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3914 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003915 }
3916
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003917 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003918 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003919 * by a timeout.
3920 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003921 * This method behaves identically to
3922 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3923 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08003924 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003925 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003926 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3927 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003928 *
3929 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003930 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3931 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003932 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003933 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3934 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003935 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003936 public void requestNetwork(@NonNull NetworkRequest request,
3937 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003938 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003939 CallbackHandler cbHandler = new CallbackHandler(handler);
markchieneddbe2b2020-03-18 21:16:15 +08003940 NetworkCapabilities nc = request.networkCapabilities;
3941 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003942 }
3943
3944 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003945 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003946 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003947 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08003948 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04003949 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3950 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003951 */
Erik Klinefb087f12014-11-19 12:12:24 +09003952 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003953
3954 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003955 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003956 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003957 * {@link android.content.Intent#getParcelableExtra(String)}.
3958 */
Erik Klinefb087f12014-11-19 12:12:24 +09003959 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003960
3961
3962 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08003963 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003964 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08003965 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003966 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003967 * the request may outlive the calling application and get called back when a suitable
3968 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003969 * <p>
3970 * The operation is an Intent broadcast that goes to a broadcast receiver that
3971 * you registered with {@link Context#registerReceiver} or through the
3972 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3973 * <p>
3974 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09003975 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3976 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003977 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003978 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003979 * Intent to reserve the network or it will be released shortly after the Intent
3980 * is processed.
3981 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04003982 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003983 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003984 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003985 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08003986 * The request may be released normally by calling
3987 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003988 * <p>It is presently unsupported to request a network with either
3989 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3990 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3991 * as these {@code NetworkCapabilities} represent states that a particular
3992 * network may never attain, and whether a network will attain these states
3993 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09003994 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003995 *
Chalard Jean7f06b342020-05-20 16:11:50 +09003996 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3997 * number of outstanding requests to 100 per app (identified by their UID), shared with
3998 * all variants of this method, of {@link #registerNetworkCallback} as well as
3999 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4000 * Requesting a network with this method will count toward this limit. If this limit is
4001 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4002 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4003 * or {@link #releaseNetworkRequest(PendingIntent)}.
4004 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004005 * <p>This method requires the caller to hold either the
4006 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4007 * or the ability to modify system settings as determined by
4008 * {@link android.provider.Settings.System#canWrite}.</p>
4009 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004010 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004011 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004012 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08004013 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004014 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4015 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004016 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004017 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004018 public void requestNetwork(@NonNull NetworkRequest request,
4019 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004020 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004021 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004022 try {
Roshan Pius34dc4be2020-01-16 12:17:17 -08004023 mService.pendingRequestForNetwork(
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07004024 request.networkCapabilities, operation, mContext.getOpPackageName(),
4025 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004026 } catch (RemoteException e) {
4027 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004028 } catch (ServiceSpecificException e) {
4029 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004030 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004031 }
4032
4033 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004034 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4035 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004036 * This method has the same behavior as
4037 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004038 * releasing network resources and disconnecting.
4039 *
4040 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4041 * PendingIntent passed to
4042 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4043 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4044 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004045 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004046 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004047 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004048 try {
4049 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004050 } catch (RemoteException e) {
4051 throw e.rethrowFromSystemServer();
4052 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004053 }
4054
Hugo Benichiff4bf602017-05-09 15:19:01 +09004055 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00004056 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004057 }
4058
4059 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00004060 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichiff4bf602017-05-09 15:19:01 +09004061 }
4062
4063 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00004064 if (timeoutMs <= 0) {
4065 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4066 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004067 }
4068
4069 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004070 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004071 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004072 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4073 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004074 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004075 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4076 * number of outstanding requests to 100 per app (identified by their UID), shared with
4077 * all variants of this method, of {@link #requestNetwork} as well as
4078 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4079 * Requesting a network with this method will count toward this limit. If this limit is
4080 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4081 * make sure to unregister the callbacks with
4082 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4083 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004084 * @param request {@link NetworkRequest} describing this request.
4085 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4086 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004087 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004088 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004089 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004090 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004091 public void registerNetworkCallback(@NonNull NetworkRequest request,
4092 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004093 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4094 }
4095
4096 /**
4097 * Registers to receive notifications about all networks which satisfy the given
4098 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004099 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4100 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004101 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004102 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4103 * number of outstanding requests to 100 per app (identified by their UID), shared with
4104 * all variants of this method, of {@link #requestNetwork} as well as
4105 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4106 * Requesting a network with this method will count toward this limit. If this limit is
4107 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4108 * make sure to unregister the callbacks with
4109 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4110 *
4111 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004112 * @param request {@link NetworkRequest} describing this request.
4113 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4114 * networks change state.
4115 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004116 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004117 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004118 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004119 public void registerNetworkCallback(@NonNull NetworkRequest request,
4120 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004121 CallbackHandler cbHandler = new CallbackHandler(handler);
4122 NetworkCapabilities nc = request.networkCapabilities;
4123 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004124 }
4125
4126 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004127 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4128 * {@link NetworkRequest}.
4129 *
4130 * This function behaves identically to the version that takes a NetworkCallback, but instead
4131 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4132 * the request may outlive the calling application and get called back when a suitable
4133 * network is found.
4134 * <p>
4135 * The operation is an Intent broadcast that goes to a broadcast receiver that
4136 * you registered with {@link Context#registerReceiver} or through the
4137 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4138 * <p>
4139 * The operation Intent is delivered with two extras, a {@link Network} typed
4140 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4141 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4142 * the original requests parameters.
4143 * <p>
4144 * If there is already a request for this Intent registered (with the equality of
4145 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4146 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4147 * <p>
4148 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004149 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004150 *
4151 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4152 * number of outstanding requests to 100 per app (identified by their UID), shared with
4153 * all variants of this method, of {@link #requestNetwork} as well as
4154 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4155 * Requesting a network with this method will count toward this limit. If this limit is
4156 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4157 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4158 * or {@link #releaseNetworkRequest(PendingIntent)}.
4159 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004160 * @param request {@link NetworkRequest} describing this request.
4161 * @param operation Action to perform when the network is available (corresponds
4162 * to the {@link NetworkCallback#onAvailable} call. Typically
4163 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004164 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004165 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004166 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004167 public void registerNetworkCallback(@NonNull NetworkRequest request,
4168 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004169 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004170 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004171 try {
Roshan Pius34dc4be2020-01-16 12:17:17 -08004172 mService.pendingListenForNetwork(
Roshan Piusc97d8062020-12-17 14:53:09 -08004173 request.networkCapabilities, operation, mContext.getOpPackageName(),
4174 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004175 } catch (RemoteException e) {
4176 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004177 } catch (ServiceSpecificException e) {
4178 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004179 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004180 }
4181
4182 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004183 * Registers to receive notifications about changes in the application's default network. This
4184 * may be a physical network or a virtual network, such as a VPN that applies to the
4185 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004186 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004187 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004188 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4189 * number of outstanding requests to 100 per app (identified by their UID), shared with
4190 * all variants of this method, of {@link #requestNetwork} as well as
4191 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4192 * Requesting a network with this method will count toward this limit. If this limit is
4193 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4194 * make sure to unregister the callbacks with
4195 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4196 *
Erik Klinee0aed632016-03-16 15:31:39 +09004197 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004198 * application's default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004199 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004200 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004201 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004202 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004203 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004204 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4205 }
4206
4207 /**
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004208 * Registers to receive notifications about changes in the application's default network. This
4209 * may be a physical network or a virtual network, such as a VPN that applies to the
4210 * application. The callbacks will continue to be called until either the application exits or
4211 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4212 *
4213 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4214 * number of outstanding requests to 100 per app (identified by their UID), shared with
4215 * all variants of this method, of {@link #requestNetwork} as well as
4216 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4217 * Requesting a network with this method will count toward this limit. If this limit is
4218 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4219 * make sure to unregister the callbacks with
4220 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4221 *
4222 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4223 * application's default network changes.
4224 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4225 * @throws RuntimeException if the app already has too many callbacks registered.
4226 */
4227 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4228 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4229 @NonNull Handler handler) {
4230 CallbackHandler cbHandler = new CallbackHandler(handler);
4231 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4232 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4233 }
4234
4235 /**
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004236 * Registers to receive notifications about changes in the system default network. The callbacks
4237 * will continue to be called until either the application exits or
4238 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004239 *
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004240 * This method should not be used to determine networking state seen by applications, because in
4241 * many cases, most or even all application traffic may not use the default network directly,
4242 * and traffic from different applications may go on different networks by default. As an
4243 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4244 * and not onto the system default network. Applications or system components desiring to do
4245 * determine network state as seen by applications should use other methods such as
4246 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4247 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004248 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4249 * number of outstanding requests to 100 per app (identified by their UID), shared with
4250 * all variants of this method, of {@link #requestNetwork} as well as
4251 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4252 * Requesting a network with this method will count toward this limit. If this limit is
4253 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4254 * make sure to unregister the callbacks with
4255 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4256 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004257 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4258 * system default network changes.
4259 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004260 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004261 *
4262 * @hide
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004263 */
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004264 @SystemApi(client = MODULE_LIBRARIES)
4265 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4266 @RequiresPermission(anyOf = {
4267 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4268 android.Manifest.permission.NETWORK_SETTINGS})
4269 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean42a9c292019-01-07 19:26:34 +09004270 @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004271 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004272 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09004273 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004274 }
4275
4276 /**
junyulaibd622262021-03-15 11:48:48 +08004277 * Registers to receive notifications about the best matching network which satisfy the given
4278 * {@link NetworkRequest}. The callbacks will continue to be called until
4279 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4280 * called.
4281 *
4282 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4283 * number of outstanding requests to 100 per app (identified by their UID), shared with
4284 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4285 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4286 * Requesting a network with this method will count toward this limit. If this limit is
4287 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4288 * make sure to unregister the callbacks with
4289 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4290 *
4291 *
4292 * @param request {@link NetworkRequest} describing this request.
4293 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4294 * networks change state.
4295 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4296 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai6b0a6a22021-03-05 15:51:17 +08004297 */
junyulai6b0a6a22021-03-05 15:51:17 +08004298 @SuppressLint("ExecutorRegistration")
4299 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4300 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4301 final NetworkCapabilities nc = request.networkCapabilities;
4302 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai8cae3c72021-03-12 20:05:08 +08004303 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai6b0a6a22021-03-05 15:51:17 +08004304 }
4305
4306 /**
fenglu73169332015-04-21 17:12:05 -07004307 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4308 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4309 * network connection for updated bandwidth information. The caller will be notified via
4310 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004311 * method assumes that the caller has previously called
4312 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4313 * changes.
fenglu76564332015-03-20 11:29:56 -07004314 *
fenglu41808e82015-04-27 14:28:04 -07004315 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004316 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004317 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004318 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004319 try {
fenglu73169332015-04-21 17:12:05 -07004320 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004321 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004322 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004323 }
4324 }
4325
4326 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004327 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004328 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4329 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4330 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004331 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4332 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004333 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004334 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4335 * triggering it as soon as this call returns.
4336 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004337 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004338 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004339 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004340 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004341 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004342 final List<NetworkRequest> reqs = new ArrayList<>();
4343 // Find all requests associated to this callback and stop callback triggers immediately.
4344 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4345 synchronized (sCallbacks) {
Remi NGUYEN VANacd6de12021-03-15 07:31:54 +00004346 if (networkCallback.networkRequest == null) {
4347 throw new IllegalArgumentException("NetworkCallback was not registered");
4348 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07004349 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4350 Log.d(TAG, "NetworkCallback was already unregistered");
4351 return;
4352 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004353 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4354 if (e.getValue() == networkCallback) {
4355 reqs.add(e.getKey());
4356 }
4357 }
4358 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4359 for (NetworkRequest r : reqs) {
4360 try {
4361 mService.releaseNetworkRequest(r);
4362 } catch (RemoteException e) {
4363 throw e.rethrowFromSystemServer();
4364 }
4365 // Only remove mapping if rpc was successful.
4366 sCallbacks.remove(r);
4367 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004368 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004369 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004370 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004371
4372 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004373 * Unregisters a callback previously registered via
4374 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4375 *
4376 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4377 * PendingIntent passed to
4378 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4379 * Cannot be null.
4380 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004381 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004382 releaseNetworkRequest(operation);
4383 }
4384
4385 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004386 * Informs the system whether it should switch to {@code network} regardless of whether it is
4387 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4388 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4389 * the system default network regardless of any other network that's currently connected. If
4390 * {@code always} is true, then the choice is remembered, so that the next time the user
4391 * connects to this network, the system will switch to it.
4392 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004393 * @param network The network to accept.
4394 * @param accept Whether to accept the network even if unvalidated.
4395 * @param always Whether to remember this choice in the future.
4396 *
4397 * @hide
4398 */
lucaslin25a50472019-03-12 13:08:03 +08004399 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004400 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4401 try {
4402 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004403 } catch (RemoteException e) {
4404 throw e.rethrowFromSystemServer();
4405 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004406 }
4407
4408 /**
lucaslin25a50472019-03-12 13:08:03 +08004409 * Informs the system whether it should consider the network as validated even if it only has
4410 * partial connectivity. If {@code accept} is true, then the network will be considered as
4411 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4412 * is remembered, so that the next time the user connects to this network, the system will
4413 * switch to it.
4414 *
4415 * @param network The network to accept.
4416 * @param accept Whether to consider the network as validated even if it has partial
4417 * connectivity.
4418 * @param always Whether to remember this choice in the future.
4419 *
4420 * @hide
4421 */
4422 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4423 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4424 try {
4425 mService.setAcceptPartialConnectivity(network, accept, always);
4426 } catch (RemoteException e) {
4427 throw e.rethrowFromSystemServer();
4428 }
4429 }
4430
4431 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004432 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4433 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4434 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4435 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4436 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004437 * @param network The network to accept.
4438 *
4439 * @hide
4440 */
lucaslin25a50472019-03-12 13:08:03 +08004441 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004442 public void setAvoidUnvalidated(Network network) {
4443 try {
4444 mService.setAvoidUnvalidated(network);
4445 } catch (RemoteException e) {
4446 throw e.rethrowFromSystemServer();
4447 }
4448 }
4449
4450 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004451 * Requests that the system open the captive portal app on the specified network.
4452 *
4453 * @param network The network to log into.
4454 *
4455 * @hide
4456 */
paulhud70b7dd2019-08-12 16:25:11 +08004457 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004458 public void startCaptivePortalApp(Network network) {
4459 try {
4460 mService.startCaptivePortalApp(network);
4461 } catch (RemoteException e) {
4462 throw e.rethrowFromSystemServer();
4463 }
4464 }
4465
4466 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004467 * Requests that the system open the captive portal app with the specified extras.
4468 *
4469 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4470 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004471 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004472 * @param appExtras Extras to include in the app start intent.
4473 * @hide
4474 */
4475 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004476 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004477 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004478 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004479 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004480 } catch (RemoteException e) {
4481 throw e.rethrowFromSystemServer();
4482 }
4483 }
4484
4485 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004486 * Determine whether the device is configured to avoid bad wifi.
4487 * @hide
4488 */
4489 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004490 @RequiresPermission(anyOf = {
4491 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4492 android.Manifest.permission.NETWORK_STACK})
4493 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004494 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004495 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004496 } catch (RemoteException e) {
4497 throw e.rethrowFromSystemServer();
4498 }
4499 }
4500
4501 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004502 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4503 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004504 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4505 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004506 *
4507 * An example of such an operation might be a time-sensitive foreground activity, such as a
4508 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4509 */
4510 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4511
4512 /**
4513 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4514 * a backup channel for traffic that is primarily going over another network.
4515 *
4516 * An example might be maintaining backup connections to peers or servers for the purpose of
4517 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4518 * on backup paths should be negligible compared to the traffic on the main path.
4519 */
4520 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4521
4522 /**
4523 * It is acceptable to use metered data to improve network latency and performance.
4524 */
4525 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4526
4527 /**
4528 * Return value to use for unmetered networks. On such networks we currently set all the flags
4529 * to true.
4530 * @hide
4531 */
4532 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4533 MULTIPATH_PREFERENCE_HANDOVER |
4534 MULTIPATH_PREFERENCE_RELIABILITY |
4535 MULTIPATH_PREFERENCE_PERFORMANCE;
4536
4537 /** @hide */
4538 @Retention(RetentionPolicy.SOURCE)
4539 @IntDef(flag = true, value = {
4540 MULTIPATH_PREFERENCE_HANDOVER,
4541 MULTIPATH_PREFERENCE_RELIABILITY,
4542 MULTIPATH_PREFERENCE_PERFORMANCE,
4543 })
4544 public @interface MultipathPreference {
4545 }
4546
4547 /**
4548 * Provides a hint to the calling application on whether it is desirable to use the
4549 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4550 * for multipath data transfer on this network when it is not the system default network.
4551 * Applications desiring to use multipath network protocols should call this method before
4552 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004553 *
4554 * @param network The network on which the application desires to use multipath data.
4555 * If {@code null}, this method will return the a preference that will generally
4556 * apply to metered networks.
4557 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4558 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004559 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004560 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004561 try {
4562 return mService.getMultipathPreference(network);
4563 } catch (RemoteException e) {
4564 throw e.rethrowFromSystemServer();
4565 }
4566 }
4567
4568 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004569 * Resets all connectivity manager settings back to factory defaults.
4570 * @hide
4571 */
paulhud70b7dd2019-08-12 16:25:11 +08004572 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scottd3bb5082015-03-30 13:17:11 -07004573 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004574 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004575 mService.factoryReset();
Amos Bianchiddadca42020-03-04 11:07:38 -08004576 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004577 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004578 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004579 }
4580 }
4581
4582 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004583 * Binds the current process to {@code network}. All Sockets created in the future
4584 * (and not explicitly bound via a bound SocketFactory from
4585 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4586 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4587 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4588 * work and all host name resolutions will fail. This is by design so an application doesn't
4589 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4590 * To clear binding pass {@code null} for {@code network}. Using individually bound
4591 * Sockets created by Network.getSocketFactory().createSocket() and
4592 * performing network-specific host name resolutions via
4593 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004594 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004595 *
4596 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4597 * the current binding.
4598 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4599 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004600 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004601 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004602 // instantiated.
4603 return setProcessDefaultNetwork(network);
4604 }
4605
4606 /**
4607 * Binds the current process to {@code network}. All Sockets created in the future
4608 * (and not explicitly bound via a bound SocketFactory from
4609 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4610 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4611 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4612 * work and all host name resolutions will fail. This is by design so an application doesn't
4613 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4614 * To clear binding pass {@code null} for {@code network}. Using individually bound
4615 * Sockets created by Network.getSocketFactory().createSocket() and
4616 * performing network-specific host name resolutions via
4617 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4618 * {@code setProcessDefaultNetwork}.
4619 *
4620 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4621 * the current binding.
4622 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4623 * @deprecated This function can throw {@link IllegalStateException}. Use
4624 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4625 * is a direct replacement.
4626 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004627 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004628 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004629 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004630 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4631
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004632 if (netId != NETID_UNSET) {
4633 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004634 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004635
4636 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4637 return false;
4638 }
4639
4640 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004641 // Set HTTP proxy system properties to match network.
4642 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004643 try {
Remi NGUYEN VAN9ff113b2021-02-03 10:18:20 +09004644 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti40898252015-04-22 11:52:48 +09004645 } catch (SecurityException e) {
4646 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4647 Log.e(TAG, "Can't set proxy properties", e);
4648 }
Paul Jensen99c36662014-08-27 12:38:45 -04004649 // Must flush DNS cache as new network may have different DNS resolutions.
4650 InetAddress.clearDnsCache();
4651 // Must flush socket pool as idle sockets will be bound to previous network and may
4652 // cause subsequent fetches to be performed on old network.
4653 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004654 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004655
4656 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004657 }
4658
4659 /**
4660 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004661 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004662 *
4663 * @return {@code Network} to which this process is bound, or {@code null}.
4664 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004665 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004666 public Network getBoundNetworkForProcess() {
4667 // Forcing callers to call thru non-static function ensures ConnectivityManager
4668 // instantiated.
4669 return getProcessDefaultNetwork();
4670 }
4671
4672 /**
4673 * Returns the {@link Network} currently bound to this process via
4674 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4675 *
4676 * @return {@code Network} to which this process is bound, or {@code null}.
4677 * @deprecated Using this function can lead to other functions throwing
4678 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4679 * {@code getBoundNetworkForProcess} is a direct replacement.
4680 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004681 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004682 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004683 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004684 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004685 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004686 return new Network(netId);
4687 }
4688
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004689 private void unsupportedStartingFrom(int version) {
4690 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004691 // The getApplicationInfo() call we make below is not supported in system context. Let
4692 // the call through here, and rely on the fact that ConnectivityService will refuse to
4693 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004694 return;
4695 }
4696
4697 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4698 throw new UnsupportedOperationException(
4699 "This method is not supported in target SDK version " + version + " and above");
4700 }
4701 }
4702
4703 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4704 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004705 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004706 // remove these exemptions. Note that this check is not secure, and apps can still access these
4707 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4708 // so is unsupported and may break in the future. http://b/22728205
4709 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07004710 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004711 }
4712
Paul Jensene98c6e02014-05-29 10:12:39 -04004713 /**
4714 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04004715 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04004716 *
4717 * @param network The {@link Network} to bind host resolutions from the current process to, or
4718 * {@code null} to clear the current binding.
4719 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4720 * @hide
4721 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4722 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004723 @Deprecated
Mathew Inwood5a09a712020-11-04 09:29:36 +00004724 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04004725 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04004726 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09004727 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04004728 }
Felipe Lemed16384b2016-01-22 09:44:57 -08004729
4730 /**
4731 * Device is not restricting metered network activity while application is running on
4732 * background.
4733 */
4734 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4735
4736 /**
4737 * Device is restricting metered network activity while application is running on background,
4738 * but application is allowed to bypass it.
4739 * <p>
4740 * In this state, application should take action to mitigate metered network access.
4741 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4742 */
4743 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4744
4745 /**
4746 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08004747 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08004748 * In this state, application should not try to use the network while running on background,
4749 * because it would be denied.
4750 */
4751 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4752
Felipe Leme6a5b7692016-01-27 14:46:39 -08004753 /**
4754 * A change in the background metered network activity restriction has occurred.
4755 * <p>
4756 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4757 * applies to them.
4758 * <p>
4759 * This is only sent to registered receivers, not manifest receivers.
4760 */
4761 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4762 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4763 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4764
Felipe Leme1b42ef92016-01-25 11:48:04 -08004765 /** @hide */
4766 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08004767 @IntDef(flag = false, value = {
4768 RESTRICT_BACKGROUND_STATUS_DISABLED,
4769 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4770 RESTRICT_BACKGROUND_STATUS_ENABLED,
4771 })
Felipe Lemed16384b2016-01-22 09:44:57 -08004772 public @interface RestrictBackgroundStatus {
4773 }
4774
4775 private INetworkPolicyManager getNetworkPolicyManager() {
4776 synchronized (this) {
4777 if (mNPManager != null) {
4778 return mNPManager;
4779 }
4780 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4781 .getService(Context.NETWORK_POLICY_SERVICE));
4782 return mNPManager;
4783 }
4784 }
4785
4786 /**
4787 * Determines if the calling application is subject to metered network restrictions while
4788 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07004789 *
4790 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4791 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4792 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08004793 */
4794 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4795 try {
4796 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4797 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004798 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08004799 }
4800 }
Ricky Waid53cf002018-01-23 04:09:45 +00004801
4802 /**
4803 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00004804 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4805 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00004806 *
4807 * @return Hash of network watchlist config file. Null if config does not exist.
4808 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004809 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00004810 public byte[] getNetworkWatchlistConfigHash() {
4811 try {
4812 return mService.getNetworkWatchlistConfigHash();
4813 } catch (RemoteException e) {
4814 Log.e(TAG, "Unable to get watchlist config hash");
4815 throw e.rethrowFromSystemServer();
4816 }
4817 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004818
4819 /**
4820 * Returns the {@code uid} of the owner of a network connection.
4821 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08004822 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4823 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004824 * @param local The local {@link InetSocketAddress} of a connection.
4825 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004826 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08004827 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4828 * android.os.Process#INVALID_UID} if the connection is not found.
4829 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4830 * user.
4831 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004832 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08004833 public int getConnectionOwnerUid(
4834 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004835 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4836 try {
4837 return mService.getConnectionOwnerUid(connectionInfo);
4838 } catch (RemoteException e) {
4839 throw e.rethrowFromSystemServer();
4840 }
4841 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004842
4843 private void printStackTrace() {
4844 if (DEBUG) {
4845 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4846 final StringBuffer sb = new StringBuffer();
4847 for (int i = 3; i < callStack.length; i++) {
4848 final String stackTrace = callStack[i].toString();
4849 if (stackTrace == null || stackTrace.contains("android.os")) {
4850 break;
4851 }
4852 sb.append(" [").append(stackTrace).append("]");
4853 }
4854 Log.d(TAG, "StackLog:" + sb.toString());
4855 }
4856 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004857
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004858 /** @hide */
4859 public TestNetworkManager startOrGetTestNetworkManager() {
4860 final IBinder tnBinder;
4861 try {
4862 tnBinder = mService.startOrGetTestNetworkService();
4863 } catch (RemoteException e) {
4864 throw e.rethrowFromSystemServer();
4865 }
4866
4867 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4868 }
4869
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004870 /** @hide */
4871 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4872 return new ConnectivityDiagnosticsManager(mContext, mService);
4873 }
4874
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004875 /**
4876 * Simulates a Data Stall for the specified Network.
4877 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004878 * <p>This method should only be used for tests.
4879 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004880 * <p>The caller must be the owner of the specified Network.
4881 *
4882 * @param detectionMethod The detection method used to identify the Data Stall.
4883 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4884 * @param network The Network for which a Data Stall is being simluated.
4885 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4886 * @throws SecurityException if the caller is not the owner of the given network.
4887 * @hide
4888 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004889 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004890 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4891 android.Manifest.permission.NETWORK_STACK})
4892 public void simulateDataStall(int detectionMethod, long timestampMillis,
4893 @NonNull Network network, @NonNull PersistableBundle extras) {
4894 try {
4895 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4896 } catch (RemoteException e) {
4897 e.rethrowFromSystemServer();
4898 }
4899 }
James Mattisdcea9fb2020-10-28 21:48:54 -07004900
Daniel Bright60f02ed2020-06-15 16:10:01 -07004901 @NonNull
4902 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4903
4904 /**
4905 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4906 * receive available QoS events related to the {@link Network} and local ip + port
4907 * specified within socketInfo.
4908 * <p/>
4909 * The same {@link QosCallback} must be unregistered before being registered a second time,
4910 * otherwise {@link QosCallbackRegistrationException} is thrown.
4911 * <p/>
4912 * This API does not, in itself, require any permission if called with a network that is not
4913 * restricted. However, the underlying implementation currently only supports the IMS network,
4914 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4915 * useful, because they'd never be called back on networks that they would have access to.
4916 *
4917 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4918 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4919 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4920 * @throws RuntimeException if the app already has too many callbacks registered.
4921 *
4922 * Exceptions after the time of registration is passed through
4923 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4924 *
4925 * @param socketInfo the socket information used to match QoS events
4926 * @param callback receives qos events that satisfy socketInfo
4927 * @param executor The executor on which the callback will be invoked. The provided
4928 * {@link Executor} must run callback sequentially, otherwise the order of
4929 * callbacks cannot be guaranteed.
4930 *
4931 * @hide
4932 */
4933 @SystemApi
4934 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4935 @NonNull final QosCallback callback,
4936 @CallbackExecutor @NonNull final Executor executor) {
4937 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4938 Objects.requireNonNull(callback, "callback must be non-null");
4939 Objects.requireNonNull(executor, "executor must be non-null");
4940
4941 try {
4942 synchronized (mQosCallbackConnections) {
4943 if (getQosCallbackConnection(callback) == null) {
4944 final QosCallbackConnection connection =
4945 new QosCallbackConnection(this, callback, executor);
4946 mQosCallbackConnections.add(connection);
4947 mService.registerQosSocketCallback(socketInfo, connection);
4948 } else {
4949 Log.e(TAG, "registerQosCallback: Callback already registered");
4950 throw new QosCallbackRegistrationException();
4951 }
4952 }
4953 } catch (final RemoteException e) {
4954 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4955
4956 // The same unregister method method is called for consistency even though nothing
4957 // will be sent to the ConnectivityService since the callback was never successfully
4958 // registered.
4959 unregisterQosCallback(callback);
4960 e.rethrowFromSystemServer();
4961 } catch (final ServiceSpecificException e) {
4962 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4963 unregisterQosCallback(callback);
4964 throw convertServiceException(e);
4965 }
4966 }
4967
4968 /**
4969 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4970 * events once unregistered and can be registered a second time.
4971 * <p/>
4972 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4973 *
4974 * @param callback the callback being unregistered
4975 *
4976 * @hide
4977 */
4978 @SystemApi
4979 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4980 Objects.requireNonNull(callback, "The callback must be non-null");
4981 try {
4982 synchronized (mQosCallbackConnections) {
4983 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4984 if (connection != null) {
4985 connection.stopReceivingMessages();
4986 mService.unregisterQosCallback(connection);
4987 mQosCallbackConnections.remove(connection);
4988 } else {
4989 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4990 }
4991 }
4992 } catch (final RemoteException e) {
4993 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4994 e.rethrowFromSystemServer();
4995 }
4996 }
4997
4998 /**
4999 * Gets the connection related to the callback.
5000 *
5001 * @param callback the callback to look up
5002 * @return the related connection
5003 */
5004 @Nullable
5005 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5006 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5007 // Checking by reference here is intentional
5008 if (connection.getCallback() == callback) {
5009 return connection;
5010 }
5011 }
5012 return null;
5013 }
Junyu Lai23568a42021-01-19 11:10:56 +00005014
5015 /**
Roshan Pius7992afd2020-12-22 15:10:42 -08005016 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Lai23568a42021-01-19 11:10:56 +00005017 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5018 * be used to request that the system provide a network without causing the network to be
5019 * in the foreground.
5020 *
5021 * <p>This method will attempt to find the best network that matches the passed
5022 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5023 * criteria. The platform will evaluate which network is the best at its own discretion.
5024 * Throughput, latency, cost per byte, policy, user preference and other considerations
5025 * may be factored in the decision of what is considered the best network.
5026 *
5027 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5028 * matching this request, while always attempting to match the request to a better network if
5029 * possible. If a better match is found, the platform will switch this request to the now-best
5030 * network and inform the app of the newly best network by invoking
5031 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5032 * will not try to maintain any other network than the best one currently matching the request:
5033 * a network not matching any network request may be disconnected at any time.
5034 *
5035 * <p>For example, an application could use this method to obtain a connected cellular network
5036 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5037 * radio to consume additional power. Or, an application could inform the system that it wants
5038 * a network supporting sending MMSes and have the system let it know about the currently best
5039 * MMS-supporting network through the provided {@link NetworkCallback}.
5040 *
5041 * <p>The status of the request can be followed by listening to the various callbacks described
5042 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5043 * used to direct traffic to the network (although accessing some networks may be subject to
5044 * holding specific permissions). Callers will learn about the specific characteristics of the
5045 * network through
5046 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5047 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5048 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5049 * matching the request at any given time; therefore when a better network matching the request
5050 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5051 * with the new network after which no further updates are given about the previously-best
5052 * network, unless it becomes the best again at some later time. All callbacks are invoked
5053 * in order on the same thread, which by default is a thread created by the framework running
5054 * in the app.
5055 *
5056 * <p>This{@link NetworkRequest} will live until released via
5057 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5058 * which point the system may let go of the network at any time.
5059 *
5060 * <p>It is presently unsupported to request a network with mutable
5061 * {@link NetworkCapabilities} such as
5062 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5063 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5064 * as these {@code NetworkCapabilities} represent states that a particular
5065 * network may never attain, and whether a network will attain these states
5066 * is unknown prior to bringing up the network so the framework does not
5067 * know how to go about satisfying a request with these capabilities.
5068 *
5069 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5070 * number of outstanding requests to 100 per app (identified by their UID), shared with
5071 * all variants of this method, of {@link #registerNetworkCallback} as well as
5072 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5073 * Requesting a network with this method will count toward this limit. If this limit is
5074 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5075 * make sure to unregister the callbacks with
5076 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5077 *
5078 * @param request {@link NetworkRequest} describing this request.
5079 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5080 * If null, the callback is invoked on the default internal Handler.
5081 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5082 * the callback must not be shared - it uniquely specifies this request.
5083 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5084 * @throws SecurityException if missing the appropriate permissions.
5085 * @throws RuntimeException if the app already has too many callbacks registered.
5086 *
5087 * @hide
5088 */
5089 @SystemApi(client = MODULE_LIBRARIES)
5090 @SuppressLint("ExecutorRegistration")
5091 @RequiresPermission(anyOf = {
5092 android.Manifest.permission.NETWORK_SETTINGS,
5093 android.Manifest.permission.NETWORK_STACK,
5094 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5095 })
5096 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaif4bc12f2021-03-09 20:49:48 +08005097 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Lai23568a42021-01-19 11:10:56 +00005098 final NetworkCapabilities nc = request.networkCapabilities;
5099 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaif4bc12f2021-03-09 20:49:48 +08005100 TYPE_NONE, new CallbackHandler(handler));
Junyu Lai23568a42021-01-19 11:10:56 +00005101 }
James Mattis6e6fabf2021-01-10 14:24:24 -08005102
5103 /**
James Mattis6e6fabf2021-01-10 14:24:24 -08005104 * Used by automotive devices to set the network preferences used to direct traffic at an
5105 * application level as per the given OemNetworkPreferences. An example use-case would be an
5106 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5107 * vehicle via a particular network.
5108 *
5109 * Calling this will overwrite the existing preference.
5110 *
5111 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5112 * @param executor the executor on which listener will be invoked.
5113 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5114 * communicate completion of setOemNetworkPreference(). This will only be
5115 * called once upon successful completion of setOemNetworkPreference().
5116 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5117 * @throws SecurityException if missing the appropriate permissions.
5118 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis7a253542021-01-26 16:23:52 -08005119 * @hide
James Mattis6e6fabf2021-01-10 14:24:24 -08005120 */
James Mattis7a253542021-01-26 16:23:52 -08005121 @SystemApi
James Mattis981865c2021-01-26 14:05:36 -08005122 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis7a253542021-01-26 16:23:52 -08005123 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis6e6fabf2021-01-10 14:24:24 -08005124 @Nullable @CallbackExecutor final Executor executor,
Chalard Jeancc9ad152021-03-03 16:37:13 +09005125 @Nullable final Runnable listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08005126 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5127 if (null != listener) {
5128 Objects.requireNonNull(executor, "Executor must be non-null");
5129 }
Chalard Jeancc9ad152021-03-03 16:37:13 +09005130 final IOnCompleteListener listenerInternal = listener == null ? null :
5131 new IOnCompleteListener.Stub() {
James Mattis6e6fabf2021-01-10 14:24:24 -08005132 @Override
5133 public void onComplete() {
Chalard Jeancc9ad152021-03-03 16:37:13 +09005134 executor.execute(listener::run);
James Mattis6e6fabf2021-01-10 14:24:24 -08005135 }
5136 };
5137
5138 try {
5139 mService.setOemNetworkPreference(preference, listenerInternal);
5140 } catch (RemoteException e) {
5141 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5142 throw e.rethrowFromSystemServer();
5143 }
5144 }
lucaslin1a6095c2021-03-12 00:46:33 +08005145
Chalard Jean03433052021-02-25 17:23:40 +09005146 /**
5147 * Request that a user profile is put by default on a network matching a given preference.
5148 *
5149 * See the documentation for the individual preferences for a description of the supported
5150 * behaviors.
5151 *
5152 * @param profile the profile concerned.
5153 * @param preference the preference for this profile.
5154 * @param executor an executor to execute the listener on. Optional if listener is null.
5155 * @param listener an optional listener to listen for completion of the operation.
5156 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5157 * @throws SecurityException if missing the appropriate permissions.
5158 * @hide
5159 */
Chalard Jeancc9ad152021-03-03 16:37:13 +09005160 // This function is for establishing per-profile default networking and can only be called by
5161 // the device policy manager, running as the system server. It would make no sense to call it
5162 // on a context for a user because it does not establish a setting on behalf of a user, rather
5163 // it establishes a setting for a user on behalf of the DPM.
5164 @SuppressLint({"UserHandle"})
5165 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jean03433052021-02-25 17:23:40 +09005166 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5167 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5168 @ProfileNetworkPreference final int preference,
5169 @Nullable @CallbackExecutor final Executor executor,
5170 @Nullable final Runnable listener) {
5171 if (null != listener) {
5172 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5173 }
5174 final IOnCompleteListener proxy;
5175 if (null == listener) {
5176 proxy = null;
5177 } else {
5178 proxy = new IOnCompleteListener.Stub() {
5179 @Override
5180 public void onComplete() {
5181 executor.execute(listener::run);
5182 }
5183 };
5184 }
5185 try {
5186 mService.setProfileNetworkPreference(profile, preference, proxy);
5187 } catch (RemoteException e) {
5188 throw e.rethrowFromSystemServer();
5189 }
5190 }
5191
lucaslin1a6095c2021-03-12 00:46:33 +08005192 // The first network ID of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005193 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin1a6095c2021-03-12 00:46:33 +08005194 // The network ID range of IPSec tunnel interface.
lucaslin28633072021-03-15 17:24:12 +08005195 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin1a6095c2021-03-12 00:46:33 +08005196
5197 /**
5198 * Get the network ID range reserved for IPSec tunnel interfaces.
5199 *
5200 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5201 * @hide
5202 */
5203 @SystemApi(client = MODULE_LIBRARIES)
5204 @NonNull
5205 public static Range<Integer> getIpSecNetIdRange() {
5206 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5207 }
lucaslin8f026612021-03-12 17:56:09 +08005208
5209 /**
5210 * Get private DNS mode from settings.
5211 *
lucaslin73c98602021-03-17 14:53:35 +08005212 * @param context The Context to query the private DNS mode from settings.
lucaslin8f026612021-03-12 17:56:09 +08005213 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5214 *
5215 * @hide
5216 */
5217 @SystemApi(client = MODULE_LIBRARIES)
5218 @NonNull
5219 @PrivateDnsMode
lucaslin11626622021-03-16 17:11:14 +08005220 public static String getPrivateDnsMode(@NonNull Context context) {
5221 final ContentResolver cr = context.getContentResolver();
lucaslin8f026612021-03-12 17:56:09 +08005222 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5223 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5224 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5225 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5226 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5227 return mode;
5228 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005229}